trigger_system 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +127 -0
- package/dist/browser/index.browser.js +48 -0
- package/dist/browser/index.browser.js.map +122 -0
- package/dist/cli/lsp-server.d.ts +3 -0
- package/dist/cli/lsp-server.d.ts.map +1 -0
- package/dist/cli/validate.d.ts +2 -0
- package/dist/cli/validate.d.ts.map +1 -0
- package/dist/core/action-registry.d.ts +12 -0
- package/dist/core/action-registry.d.ts.map +1 -0
- package/dist/core/context-adapter.d.ts +23 -0
- package/dist/core/context-adapter.d.ts.map +1 -0
- package/dist/core/dependency-graph.d.ts +18 -0
- package/dist/core/dependency-graph.d.ts.map +1 -0
- package/dist/core/engine.d.ts +24 -0
- package/dist/core/engine.d.ts.map +1 -0
- package/dist/core/event-queue.d.ts +25 -0
- package/dist/core/event-queue.d.ts.map +1 -0
- package/dist/core/expression-engine.d.ts +31 -0
- package/dist/core/expression-engine.d.ts.map +1 -0
- package/dist/core/index.d.ts +10 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/persistence-browser.d.ts +20 -0
- package/dist/core/persistence-browser.d.ts.map +1 -0
- package/dist/core/persistence.d.ts +34 -0
- package/dist/core/persistence.d.ts.map +1 -0
- package/dist/core/persistence.node.d.ts +18 -0
- package/dist/core/persistence.node.d.ts.map +1 -0
- package/dist/core/plugin-manager.d.ts +15 -0
- package/dist/core/plugin-manager.d.ts.map +1 -0
- package/dist/core/rule-engine.d.ts +39 -0
- package/dist/core/rule-engine.d.ts.map +1 -0
- package/dist/core/state-manager.d.ts +41 -0
- package/dist/core/state-manager.d.ts.map +1 -0
- package/dist/domain/index.d.ts +2 -0
- package/dist/domain/index.d.ts.map +1 -0
- package/dist/domain/validator.d.ts +2433 -0
- package/dist/domain/validator.d.ts.map +1 -0
- package/dist/index.browser.d.ts +6 -0
- package/dist/index.browser.d.ts.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/io/index.d.ts +2 -0
- package/dist/io/index.d.ts.map +1 -0
- package/dist/io/loader.node.d.ts +14 -0
- package/dist/io/loader.node.d.ts.map +1 -0
- package/dist/lsp/completions.d.ts +6 -0
- package/dist/lsp/completions.d.ts.map +1 -0
- package/dist/lsp/completions.js +624 -0
- package/dist/lsp/completions.js.map +1 -0
- package/dist/lsp/data-context.d.ts +60 -0
- package/dist/lsp/data-context.d.ts.map +1 -0
- package/dist/lsp/data-context.js +172 -0
- package/dist/lsp/data-context.js.map +1 -0
- package/dist/lsp/diagnostics.d.ts +7 -0
- package/dist/lsp/diagnostics.d.ts.map +1 -0
- package/dist/lsp/diagnostics.js +373 -0
- package/dist/lsp/diagnostics.js.map +1 -0
- package/dist/lsp/directives.d.ts +44 -0
- package/dist/lsp/directives.d.ts.map +1 -0
- package/dist/lsp/directives.js +232 -0
- package/dist/lsp/directives.js.map +1 -0
- package/dist/lsp/domain/index.d.ts +2 -0
- package/dist/lsp/domain/index.d.ts.map +1 -0
- package/dist/lsp/domain/index.js +18 -0
- package/dist/lsp/domain/index.js.map +1 -0
- package/dist/lsp/domain/validator.d.ts +2433 -0
- package/dist/lsp/domain/validator.d.ts.map +1 -0
- package/dist/lsp/domain/validator.js +225 -0
- package/dist/lsp/domain/validator.js.map +1 -0
- package/dist/lsp/hover.d.ts +7 -0
- package/dist/lsp/hover.d.ts.map +1 -0
- package/dist/lsp/hover.js +462 -0
- package/dist/lsp/hover.js.map +1 -0
- package/dist/lsp/lsp/completions.d.ts +6 -0
- package/dist/lsp/lsp/completions.d.ts.map +1 -0
- package/dist/lsp/lsp/completions.js +624 -0
- package/dist/lsp/lsp/completions.js.map +1 -0
- package/dist/lsp/lsp/data-context.d.ts +60 -0
- package/dist/lsp/lsp/data-context.d.ts.map +1 -0
- package/dist/lsp/lsp/data-context.js +172 -0
- package/dist/lsp/lsp/data-context.js.map +1 -0
- package/dist/lsp/lsp/diagnostics.d.ts +7 -0
- package/dist/lsp/lsp/diagnostics.d.ts.map +1 -0
- package/dist/lsp/lsp/diagnostics.js +373 -0
- package/dist/lsp/lsp/diagnostics.js.map +1 -0
- package/dist/lsp/lsp/directives.d.ts +44 -0
- package/dist/lsp/lsp/directives.d.ts.map +1 -0
- package/dist/lsp/lsp/directives.js +232 -0
- package/dist/lsp/lsp/directives.js.map +1 -0
- package/dist/lsp/lsp/hover.d.ts +7 -0
- package/dist/lsp/lsp/hover.d.ts.map +1 -0
- package/dist/lsp/lsp/hover.js +462 -0
- package/dist/lsp/lsp/hover.js.map +1 -0
- package/dist/lsp/lsp/semantic_tokens.d.ts +4 -0
- package/dist/lsp/lsp/semantic_tokens.d.ts.map +1 -0
- package/dist/lsp/lsp/semantic_tokens.js +158 -0
- package/dist/lsp/lsp/semantic_tokens.js.map +1 -0
- package/dist/lsp/lsp/server.d.ts +2 -0
- package/dist/lsp/lsp/server.d.ts.map +1 -0
- package/dist/lsp/lsp/server.js +216 -0
- package/dist/lsp/lsp/server.js.map +1 -0
- package/dist/lsp/semantic_tokens.d.ts +4 -0
- package/dist/lsp/semantic_tokens.d.ts.map +1 -0
- package/dist/lsp/semantic_tokens.js +158 -0
- package/dist/lsp/semantic_tokens.js.map +1 -0
- package/dist/lsp/server.bundle.d.ts +2 -0
- package/dist/lsp/server.bundle.d.ts.map +1 -0
- package/dist/lsp/server.bundle.js +256 -0
- package/dist/lsp/server.d.ts +2 -0
- package/dist/lsp/server.d.ts.map +1 -0
- package/dist/lsp/server.js +216 -0
- package/dist/lsp/server.js.map +1 -0
- package/dist/lsp/types.d.ts +71 -0
- package/dist/lsp/types.d.ts.map +1 -0
- package/dist/lsp/types.js +4 -0
- package/dist/lsp/types.js.map +1 -0
- package/dist/node/index.js +186 -0
- package/dist/node/index.js.map +196 -0
- package/dist/node/node.js +187 -0
- package/dist/node/node.js.map +198 -0
- package/dist/node.d.ts +4 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/sdk/builder.d.ts +39 -0
- package/dist/sdk/builder.d.ts.map +1 -0
- package/dist/sdk/exporter.d.ts +13 -0
- package/dist/sdk/exporter.d.ts.map +1 -0
- package/dist/sdk/index.d.ts +3 -0
- package/dist/sdk/index.d.ts.map +1 -0
- package/dist/types.d.ts +71 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/emitter.d.ts +25 -0
- package/dist/utils/emitter.d.ts.map +1 -0
- package/dist/utils/utils.d.ts +18 -0
- package/dist/utils/utils.d.ts.map +1 -0
- package/package.json +91 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["..\\..\\src\\core\\expression-engine.ts", "..\\..\\src\\core\\event-queue.ts", "..\\..\\src\\core\\persistence.ts", "..\\..\\src\\core\\persistence-browser.ts", "..\\..\\src\\core\\state-manager.ts", "..\\..\\src\\core\\action-registry.ts", "..\\..\\src\\core\\context-adapter.ts", "..\\..\\src\\utils\\emitter.ts", "..\\..\\src\\core\\rule-engine.ts", "..\\..\\src\\utils\\utils.ts", "..\\..\\src\\core\\engine.ts", "..\\..\\node_modules\\@ark\\util\\out\\arrays.js", "..\\..\\node_modules\\@ark\\util\\out\\domain.js", "..\\..\\node_modules\\@ark\\util\\out\\errors.js", "..\\..\\node_modules\\@ark\\util\\out\\flatMorph.js", "..\\..\\node_modules\\@ark\\util\\out\\records.js", "..\\..\\node_modules\\@ark\\util\\out\\objectKinds.js", "..\\..\\node_modules\\@ark\\util\\out\\clone.js", "..\\..\\node_modules\\@ark\\util\\out\\functions.js", "..\\..\\node_modules\\@ark\\util\\out\\generics.js", "..\\..\\node_modules\\@ark\\util\\out\\hkt.js", "..\\..\\node_modules\\@ark\\util\\out\\isomorphic.js", "..\\..\\node_modules\\@ark\\util\\out\\strings.js", "..\\..\\node_modules\\@ark\\util\\out\\numbers.js", "..\\..\\node_modules\\@ark\\util\\out\\registry.js", "..\\..\\node_modules\\@ark\\util\\out\\primitive.js", "..\\..\\node_modules\\@ark\\util\\out\\serialize.js", "..\\..\\node_modules\\@ark\\util\\out\\path.js", "..\\..\\node_modules\\@ark\\util\\out\\scanner.js", "..\\..\\node_modules\\@ark\\util\\out\\traits.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\registry.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\compile.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\utils.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\implement.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\toJsonSchema.js", "..\\..\\node_modules\\@ark\\schema\\out\\config.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\errors.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\traversal.js", "..\\..\\node_modules\\@ark\\schema\\out\\node.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\disjoint.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\intersections.js", "..\\..\\node_modules\\@ark\\schema\\out\\constraint.js", "..\\..\\node_modules\\@ark\\schema\\out\\generic.js", "..\\..\\node_modules\\@ark\\schema\\out\\predicate.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\divisor.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\range.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\after.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\before.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\exactLength.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\max.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\maxLength.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\min.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\minLength.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\kinds.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\pattern.js", "..\\..\\node_modules\\@ark\\schema\\out\\parse.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\prop.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\optional.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\root.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\utils.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\alias.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\basis.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\domain.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\intersection.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\morph.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\proto.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\union.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\unit.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\index.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\required.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\sequence.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\structure.js", "..\\..\\node_modules\\@ark\\schema\\out\\kinds.js", "..\\..\\node_modules\\@ark\\schema\\out\\module.js", "..\\..\\node_modules\\@ark\\schema\\out\\scope.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\shared.js", "..\\..\\node_modules\\@ark\\schema\\out\\intrinsic.js", "..\\..\\node_modules\\arkregex\\out\\regex.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\date.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\enclosed.js", "..\\..\\node_modules\\arktype\\out\\parser\\ast\\validate.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\tokens.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\genericArgs.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\unenclosed.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\operand.js", "..\\..\\node_modules\\arktype\\out\\parser\\reduce\\shared.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\bounds.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\brand.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\divisor.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\operator.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\default.js", "..\\..\\node_modules\\arktype\\out\\parser\\string.js", "..\\..\\node_modules\\arktype\\out\\parser\\reduce\\dynamic.js", "..\\..\\node_modules\\arktype\\out\\generic.js", "..\\..\\node_modules\\arktype\\out\\fn.js", "..\\..\\node_modules\\arktype\\out\\match.js", "..\\..\\node_modules\\arktype\\out\\parser\\property.js", "..\\..\\node_modules\\arktype\\out\\parser\\objectLiteral.js", "..\\..\\node_modules\\arktype\\out\\parser\\tupleExpressions.js", "..\\..\\node_modules\\arktype\\out\\parser\\tupleLiteral.js", "..\\..\\node_modules\\arktype\\out\\parser\\definition.js", "..\\..\\node_modules\\arktype\\out\\type.js", "..\\..\\node_modules\\arktype\\out\\scope.js", "..\\..\\node_modules\\arktype\\out\\keywords\\builtins.js", "..\\..\\node_modules\\arktype\\out\\keywords\\Array.js", "..\\..\\node_modules\\arktype\\out\\keywords\\FormData.js", "..\\..\\node_modules\\arktype\\out\\keywords\\TypedArray.js", "..\\..\\node_modules\\arktype\\out\\keywords\\constructors.js", "..\\..\\node_modules\\arktype\\out\\keywords\\number.js", "..\\..\\node_modules\\arktype\\out\\keywords\\string.js", "..\\..\\node_modules\\arktype\\out\\keywords\\ts.js", "..\\..\\node_modules\\arktype\\out\\keywords\\keywords.js", "..\\..\\src\\domain\\validator.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"// -----------------------------------------------------------------------------\n// MOTOR DE EXPRESIONES MATEMÁTICAS Y VARIABLES\n// -----------------------------------------------------------------------------\n\nimport type { TriggerContext } from \"../types\";\n\nexport class ExpressionEngine {\n /**\n * Evalúa una expresión matemática simple o una interpolación de variables\n * Soporta operadores: +, -, *, /, %, **, y funciones matemáticas básicas\n */\n\n static evaluate(expression: string, context: TriggerContext): any {\n try {\n // Check for template string interpolation first\n if (expression.includes(\"${\")) {\n const interpolated = this.interpolate(expression, context);\n // If the result is a number-like string, convert it\n if (!isNaN(Number(interpolated)) && interpolated.trim() !== \"\") {\n return Number(interpolated);\n }\n return interpolated;\n }\n\n // Use the flexible JS evaluator by default to support globals and function calls\n return this.evaluateExpression(expression, context);\n } catch (error) {\n console.error(`Error evaluating expression: ${expression}`, error);\n return null;\n }\n }\n\n /**\n * Realiza interpolación de variables en una plantilla de texto\n * Ejemplo: \"Hola ${data.username}, hoy es ${new Date().toLocaleDateString()}\"\n */\n static interpolate(template: string, context: TriggerContext): string {\n return template.replace(/\\$\\{([^}]+)\\}/g, (match, expression) => {\n try {\n const result = this.evaluateExpression(expression, context);\n if (result === undefined || result === null) {\n return \"undefined\"; // Explicitly return string \"undefined\" or \"\"?\n // User request: \"cases without o incorrect data ${data.username} if data is null\"\n // Usually keeping it as \"undefined\" is honest but ugly.\n // Let's use a standard \"N/A\" or empty string? \n // Or better: check if the user wants default values e.g. ${name || 'Guest'}\n // evaluateExpression might handle || operator if it falls back to JS evaluation.\n return \"undefined\"; \n }\n return String(result);\n } catch (error) {\n console.error(`Error en interpolación: ${match}`, error);\n return match; // Devuelve la expresión original si hay error\n }\n });\n }\n /**\n * Evalúa una expresión matemática segura usando Function constructor\n */\n private static evaluateMathExpression(expression: string): any {\n try {\n // Crear una función segura que solo permita operaciones matemáticas básicas\n const mathFunction = new Function(\"Math\", `return ${expression}`);\n return mathFunction(Math);\n } catch (error) {\n throw new Error(`Error evaluando expresión matemática: ${expression}`);\n }\n }\n\n /**\n * Evalúa una expresión individual en el contexto\n */\n private static evaluateExpression(\n expression: string,\n context: TriggerContext,\n ): any {\n // Intentar obtener un valor del contexto SI es una ruta simple (sin espacios, operadores, etc.)\n // Regex: Start with reserved root, followed by dots and words. No spaces.\n if (/^(data|globals|request|computed)(\\.[a-zA-Z0-9_]+)+$/.test(expression)) {\n const val = this.getNestedValue(expression, context);\n // If found, return. If undefined, we might accept it as undefined, \n // OR if technically it shouldn't be undefined, we might fail? \n // But for robustness, let's return it.\n return val;\n }\n\n // Intentar evaluar como expresión de JavaScript\n try {\n return new Function(\n \"context\",\n \"with(context) { return \" + expression + \" }\",\n )(context);\n } catch (error) {\n console.error(`ERROR evaluating expression '${expression}':`, error);\n // Si falla, devolver la expresión original\n return expression;\n }\n }\n\n /**\n * Obtiene un valor anidado de un objeto usando notación de puntos\n * Ejemplo: getNestedValue(\"data.user.profile.name\", context)\n */\n static getNestedValue(path: string, context: TriggerContext): any {\n const parts = path.split(\".\");\n let current: any = context;\n\n for (const part of parts) {\n if (current === null || current === undefined || !(part in current)) {\n return undefined;\n }\n current = current[part];\n }\n\n return current;\n }\n\n /**\n * Ejecuta una expresión matemática específica (como \"1 + 2\")\n */\n static evaluateMath(expression: string, context: TriggerContext): number {\n // Extraer variables de la expresión\n let processedExpression = expression;\n\n // Reemplazar variables de contexto en la expresión\n processedExpression = processedExpression.replace(\n /\\b[a-zA-Z_][a-zA-Z0-9_]*\\b/g,\n (match) => {\n // Verificar si es una palabra reservada de JavaScript o función Math\n if (\n [\n \"Math\",\n \"random\",\n \"floor\",\n \"ceil\",\n \"round\",\n \"sqrt\",\n \"abs\",\n \"pow\",\n \"min\",\n \"max\",\n \"sin\",\n \"cos\",\n \"tan\",\n ].includes(match)\n ) {\n return match;\n }\n\n // Intentar obtener valor del contexto\n const value = this.getNestedValue(match, context);\n if (value !== undefined) {\n return typeof value === \"string\" ? `\"${value}\"` : String(value);\n }\n\n return match;\n },\n );\n\n try {\n // Evaluar la expresión matemática\n return this.evaluateMathExpression(processedExpression);\n } catch (error) {\n console.error(`Error en evaluación matemática: ${expression}`, error);\n return NaN;\n }\n }\n}\n",
|
|
6
|
+
"\r\nimport type { TriggerContext } from \"../types\";\r\nimport { RuleEngine } from \"./rule-engine\";\r\n\r\nexport interface EventQueueConfig {\r\n maxBatchSize: number;\r\n flushIntervalMs: number;\r\n}\r\n\r\nexport class EventQueue {\r\n private queue: TriggerContext[] = [];\r\n private engine: RuleEngine;\r\n private config: EventQueueConfig;\r\n private timer: Timer | null = null;\r\n private isProcessing = false;\r\n\r\n constructor(engine: RuleEngine, config: EventQueueConfig = { maxBatchSize: 10, flushIntervalMs: 100 }) {\r\n this.engine = engine;\r\n this.config = config;\r\n }\r\n\r\n /**\r\n * Enqueue a new event context.\r\n * Automatically triggers processing if batch size reached.\r\n */\r\n push(context: TriggerContext) {\r\n this.queue.push(context);\r\n \r\n if (this.queue.length >= this.config.maxBatchSize) {\r\n this.processQueue();\r\n } else if (!this.timer) {\r\n this.timer = setTimeout(() => this.processQueue(), this.config.flushIntervalMs);\r\n }\r\n }\r\n\r\n /**\r\n * Process all buffered events.\r\n */\r\n async processQueue() {\r\n if (this.isProcessing) return;\r\n this.isProcessing = true;\r\n\r\n if (this.timer) {\r\n clearTimeout(this.timer);\r\n this.timer = null;\r\n }\r\n\r\n const batch = this.queue.splice(0, this.config.maxBatchSize);\r\n if (batch.length === 0) {\r\n this.isProcessing = false;\r\n return;\r\n }\r\n\r\n console.debug(`[EventQueue] Processing batch of ${batch.length} events.`);\r\n\r\n // Process sequentially to maintain state consistency\r\n // (Or parallel if state not involved, but for \"Stateful Triggers\" sequential is safer)\r\n for (const context of batch) {\r\n try {\r\n await this.engine.evaluateContext(context);\r\n } catch (error) {\r\n console.error(`[EventQueue] Error processing event ${context.event}:`, error);\r\n }\r\n }\r\n\r\n // If more items remain, schedule immediate next tick\r\n if (this.queue.length > 0) {\r\n setTimeout(() => this.processQueue(), 0);\r\n }\r\n \r\n this.isProcessing = false;\r\n }\r\n\r\n getQueueLength(): number {\r\n return this.queue.length;\r\n }\r\n}\r\n",
|
|
7
|
+
"\r\n/**\r\n * Persistence Adapter Interface\r\n * Allows the StateManager to save/load state from external storage (Redis, SQLite, File, etc.)\r\n */\r\nexport interface PersistenceAdapter {\r\n /**\r\n * Load state from storage on startup\r\n */\r\n loadState(): Promise<Map<string, any>>;\r\n\r\n /**\r\n * Save a single key-value pair\r\n */\r\n saveState(key: string, value: any): Promise<void>;\r\n\r\n /**\r\n * Delete a key\r\n */\r\n deleteState(key: string): Promise<void>;\r\n\r\n /**\r\n * Clear all state\r\n */\r\n clearState(): Promise<void>;\r\n}\r\n\r\n/**\r\n * InMemory Adapter (Default)\r\n * Does not persist across restarts, but fulfills the interface.\r\n */\r\nexport class InMemoryPersistence implements PersistenceAdapter {\r\n private store = new Map<string, any>();\r\n\r\n async loadState(): Promise<Map<string, any>> {\r\n return new Map(this.store);\r\n }\r\n\r\n async saveState(key: string, value: any): Promise<void> {\r\n this.store.set(key, value);\r\n }\r\n\r\n async deleteState(key: string): Promise<void> {\r\n this.store.delete(key);\r\n }\r\n\r\n async clearState(): Promise<void> {\r\n this.store.clear();\r\n }\r\n}\r\n",
|
|
8
|
+
"\r\nimport { type PersistenceAdapter } from \"./persistence\";\r\n\r\n/**\r\n * Browser LocalStorage Persistence Adapter\r\n * Uses window.localStorage to save state.\r\n * Fallbacks to in-memory if not available (e.g. Node env without polyfill).\r\n */\r\nexport class BrowserPersistence implements PersistenceAdapter {\r\n private keyPrefix: string;\r\n private cache: Map<string, any> = new Map();\r\n private isLoaded: boolean = false;\r\n\r\n constructor(prefix: string = \"trigger_system:\") {\r\n this.keyPrefix = prefix;\r\n }\r\n\r\n private isAvailable(): boolean {\r\n return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';\r\n }\r\n\r\n private ensureLoaded() {\r\n if (this.isLoaded) return;\r\n \r\n if (this.isAvailable()) {\r\n try {\r\n const raw = window.localStorage.getItem(this.keyPrefix + \"state\");\r\n if (raw) {\r\n const json = JSON.parse(raw);\r\n this.cache = new Map(Object.entries(json));\r\n }\r\n } catch (error) {\r\n console.error(`[BrowserPersistence] Failed to load from localStorage:`, error);\r\n }\r\n }\r\n this.isLoaded = true;\r\n }\r\n\r\n private persist() {\r\n if (this.isAvailable()) {\r\n try {\r\n const obj = Object.fromEntries(this.cache);\r\n window.localStorage.setItem(this.keyPrefix + \"state\", JSON.stringify(obj));\r\n } catch (error) {\r\n console.error(`[BrowserPersistence] Failed to save to localStorage:`, error);\r\n }\r\n }\r\n }\r\n\r\n async loadState(): Promise<Map<string, any>> {\r\n this.ensureLoaded();\r\n return new Map(this.cache);\r\n }\r\n\r\n async saveState(key: string, value: any): Promise<void> {\r\n this.ensureLoaded();\r\n this.cache.set(key, value);\r\n this.persist();\r\n }\r\n\r\n async deleteState(key: string): Promise<void> {\r\n this.ensureLoaded();\r\n this.cache.delete(key);\r\n this.persist();\r\n }\r\n\r\n async clearState(): Promise<void> {\r\n this.cache.clear();\r\n this.persist();\r\n }\r\n}\r\n",
|
|
9
|
+
"\r\nimport { type PersistenceAdapter, InMemoryPersistence } from \"./persistence\";\r\n\r\n/**\r\n * State Manager\r\n * Handles persistent state across rule executions.\r\n * Allows for \"Stateful Triggers\" like counters, sequences, and goals.\r\n */\r\nexport class StateManager {\r\n private static instance: StateManager;\r\n private state: Map<string, any>;\r\n private persistence: PersistenceAdapter;\r\n\r\n private constructor() {\r\n this.state = new Map();\r\n this.persistence = new InMemoryPersistence();\r\n }\r\n\r\n static getInstance(): StateManager {\r\n if (!StateManager.instance) {\r\n StateManager.instance = new StateManager();\r\n }\r\n return StateManager.instance;\r\n }\r\n\r\n /**\r\n * Configure the persistence adapter.\r\n */\r\n setPersistence(adapter: PersistenceAdapter) {\r\n this.persistence = adapter;\r\n }\r\n\r\n /**\r\n * Load state from persistence. Should be called at startup.\r\n */\r\n async initialize(): Promise<void> {\r\n const loaded = await this.persistence.loadState();\r\n this.state = loaded;\r\n console.log(`[StateManager] Initialized with ${this.state.size} keys.`);\r\n }\r\n\r\n /**\r\n * Get a value from the state. \r\n */\r\n get(key: string): any {\r\n return this.state.get(key);\r\n }\r\n\r\n /**\r\n * Set a value in the state and persist it.\r\n */\r\n async set(key: string, value: any): Promise<void> {\r\n this.state.set(key, value);\r\n await this.persistence.saveState(key, value);\r\n }\r\n\r\n /**\r\n * Increment a numeric value explicitly.\r\n */\r\n async increment(key: string, amount: number = 1): Promise<number> {\r\n const current = this.get(key) || 0;\r\n const newVal = Number(current) + amount;\r\n await this.set(key, newVal);\r\n return newVal;\r\n }\r\n \r\n async decrement(key: string, amount: number = 1): Promise<number> {\r\n return this.increment(key, -amount);\r\n }\r\n\r\n async delete(key: string): Promise<boolean> {\r\n const deleted = this.state.delete(key);\r\n if (deleted) {\r\n await this.persistence.deleteState(key);\r\n }\r\n return deleted;\r\n }\r\n\r\n async clear(): Promise<void> {\r\n this.state.clear();\r\n await this.persistence.clearState();\r\n }\r\n\r\n /**\r\n * Export state as a plain object (for Context injection).\r\n */\r\n getAll(): Record<string, any> {\r\n return Object.fromEntries(this.state);\r\n }\r\n}\r\n",
|
|
10
|
+
"import type { TriggerAction, TriggerContext } from \"../types\";\r\nimport { ExpressionEngine } from \"./expression-engine\";\r\nimport { StateManager } from \"./state-manager\";\r\n\r\nexport type ActionHandler = (action: TriggerAction, context: TriggerContext) => Promise<any> | any;\r\n\r\nexport class ActionRegistry {\r\n private static instance: ActionRegistry;\r\n private handlers = new Map<string, ActionHandler>();\r\n\r\n private constructor() {\r\n this.registerDefaults();\r\n }\r\n\r\n static getInstance(): ActionRegistry {\r\n if (!this.instance) {\r\n this.instance = new ActionRegistry();\r\n }\r\n return this.instance;\r\n }\r\n\r\n register(type: string, handler: ActionHandler) {\r\n this.handlers.set(type.toUpperCase(), handler);\r\n }\r\n\r\n get(type: string): ActionHandler | undefined {\r\n return this.handlers.get(type.toUpperCase());\r\n }\r\n\r\n\r\n private registerDefaults() {\r\n // Log Action\r\n this.register(\"log\", (action, context) => {\r\n const messageTemplate = action.params?.message || action.params?.content || \"Log Trigger\";\r\n const message = ExpressionEngine.interpolate(messageTemplate, context);\r\n console.log(`[TriggerLog] ${message}`);\r\n return { message };\r\n });\r\n\r\n // Response Action\r\n this.register(\"response\", (action, context) => {\r\n const contentTemplate = action.params?.content || action.params?.body || \"\";\r\n const content = ExpressionEngine.interpolate(contentTemplate, context);\r\n return {\r\n statusCode: action.params?.statusCode || 200,\r\n headers: action.params?.headers || { \"Content-Type\": \"application/json\" },\r\n body: content,\r\n };\r\n });\r\n\r\n // Execute Action\r\n this.register(\"execute\", async (action, context) => {\r\n const commandTemplate = action.params?.command || action.params?.content || \"\";\r\n const command = ExpressionEngine.interpolate(commandTemplate, context);\r\n\r\n if (!action.params?.safe) {\r\n console.warn(`[Trigger] Ejecutando comando no seguro: ${command}`);\r\n }\r\n\r\n try {\r\n const proc = Bun.spawn(command.split(\" \"), {\r\n stdout: \"pipe\",\r\n stderr: \"pipe\",\r\n });\r\n const [stdout, stderr] = await Promise.all([\r\n new Response(proc.stdout).text(),\r\n new Response(proc.stderr).text(),\r\n ]);\r\n return {\r\n command,\r\n stdout,\r\n stderr,\r\n exitCode: await proc.exited,\r\n };\r\n } catch (error) {\r\n return { command, error: String(error) };\r\n }\r\n });\r\n\r\n // Forward Action\r\n this.register(\"forward\", async (action, context) => {\r\n const urlTemplate = action.params?.url || \"\";\r\n const url = ExpressionEngine.interpolate(urlTemplate, context);\r\n const method = action.params?.method || \"POST\";\r\n\r\n try {\r\n const response = await fetch(url, {\r\n method,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n ...action.params?.headers,\r\n },\r\n body: JSON.stringify(context.data),\r\n });\r\n return {\r\n url,\r\n method,\r\n status: response.status,\r\n headers: (() => {\r\n const h: Record<string, string> = {};\r\n response.headers.forEach((v, k) => h[k] = v);\r\n return h;\r\n })(),\r\n body: await response.text(),\r\n };\r\n } catch (error) {\r\n return { url, method, error: String(error) };\r\n }\r\n });\r\n\r\n\r\n // --- State Actions ---\r\n\r\n this.register(\"STATE_SET\", async (action, context) => {\r\n const key = action.params?.key;\r\n const value = action.params?.value;\r\n if (!key) return { error: \"Missing key for STATE_SET\" };\r\n \r\n // Evaluate value if it's dynamic\r\n let finalValue = value;\r\n if (typeof value === 'string' && value.includes('${')) {\r\n finalValue = ExpressionEngine.interpolate(value, context);\r\n }\r\n\r\n await StateManager.getInstance().set(key, finalValue);\r\n return { key, value: finalValue };\r\n });\r\n\r\n this.register(\"STATE_INCREMENT\", async (action, context) => {\r\n const key = action.params?.key;\r\n const amount = Number(action.params?.amount) || 1;\r\n if (!key) return { error: \"Missing key for STATE_INCREMENT\" };\r\n\r\n const newValue = await StateManager.getInstance().increment(key, amount);\r\n return { key, newValue };\r\n });\r\n\r\n this.register(\"EMIT_EVENT\", (action, context) => {\r\n // This action is special. The engine or host must handle the result \r\n // and feed it back if desired. \r\n // We simply return the instruction to emit.\r\n return { \r\n event: action.params?.event, \r\n payload: action.params?.data || {} \r\n };\r\n });\r\n }\r\n}\r\n",
|
|
11
|
+
"\r\nimport type { TriggerContext } from \"../types\";\r\n\r\nexport interface ContextSource {\r\n type: string;\r\n payload: any;\r\n timestamp?: number;\r\n}\r\n\r\nexport class ContextAdapter {\r\n \r\n /**\r\n * Creates a standardized TriggerContext from a generic source.\r\n */\r\n static create(event: string, data: any, globals: Record<string, any> = {}): TriggerContext {\r\n return {\r\n event,\r\n timestamp: Date.now(),\r\n data: typeof data === 'object' ? data : { value: data },\r\n globals,\r\n helpers: this.getDefaultHelpers()\r\n };\r\n }\r\n\r\n /**\r\n * Adapts a standard HTTP Request (like from Bun.serve) into a TriggerContext.\r\n * Note: Accessing body requires it to be read previously or passed mainly as objects.\r\n */\r\n static fromRequest(req: Request, bodyData?: any, globals: Record<string, any> = {}): TriggerContext {\r\n const url = new URL(req.url);\r\n \r\n return {\r\n event: \"HTTP_REQUEST\",\r\n timestamp: Date.now(),\r\n data: {\r\n method: req.method,\r\n path: url.pathname,\r\n query: Object.fromEntries(url.searchParams),\r\n headers: (() => {\r\n const h: Record<string, string> = {};\r\n req.headers.forEach((v, k) => h[k] = v);\r\n return h;\r\n })(),\r\n body: bodyData || {}\r\n },\r\n globals: {\r\n ...globals,\r\n ip: req.headers.get(\"x-forwarded-for\") || \"unknown\"\r\n },\r\n helpers: this.getDefaultHelpers()\r\n };\r\n }\r\n\r\n /**\r\n * Adapts a generic Webhook payload.\r\n */\r\n static fromWebhook(provider: string, eventName: string, payload: any, globals: Record<string, any> = {}): TriggerContext {\r\n return {\r\n event: `WEBHOOK_${provider.toUpperCase()}_${eventName.toUpperCase()}`,\r\n timestamp: Date.now(),\r\n data: payload,\r\n globals: {\r\n ...globals,\r\n provider\r\n },\r\n helpers: this.getDefaultHelpers()\r\n };\r\n }\r\n\r\n private static getDefaultHelpers(): Record<string, Function> {\r\n return {\r\n now: () => Date.now(),\r\n uuid: () => crypto.randomUUID(),\r\n jsonParse: (str: string) => JSON.parse(str),\r\n jsonStringify: (obj: any) => JSON.stringify(obj)\r\n };\r\n }\r\n}\r\n",
|
|
12
|
+
"type Handler<T = any> = (data: T) => void;\r\n\r\n/**\r\n * Enumeration of all built-in engine events.\r\n * Use these constants instead of raw strings to ensure type safety.\r\n */\r\nexport enum EngineEvent {\r\n ENGINE_START = 'engine:start',\r\n ENGINE_DONE = 'engine:done',\r\n RULE_MATCH = 'rule:match',\r\n ACTION_SUCCESS = 'action:success',\r\n ACTION_ERROR = 'action:error'\r\n}\r\nexport const engineEvents = EngineEvent;\r\nexport class TriggerEmitter {\r\n private static instance: TriggerEmitter;\r\n private handlers = new Map<string, Set<Handler>>();\r\n\r\n private constructor() {}\r\n\r\n static getInstance(): TriggerEmitter {\r\n if (!this.instance) {\r\n this.instance = new TriggerEmitter();\r\n }\r\n return this.instance;\r\n }\r\n\r\n on<T = any>(event: EngineEvent | string, handler: Handler<T>): () => void {\r\n const eventName = event as string;\r\n if (!this.handlers.has(eventName)) {\r\n this.handlers.set(eventName, new Set());\r\n }\r\n this.handlers.get(eventName)!.add(handler);\r\n \r\n // Return unsubscribe function\r\n return () => this.off(eventName, handler);\r\n }\r\n\r\n off(event: EngineEvent | string, handler: Handler): void {\r\n const eventName = event as string;\r\n const set = this.handlers.get(eventName);\r\n if (set) {\r\n set.delete(handler);\r\n }\r\n }\r\n\r\n emit<T = any>(event: EngineEvent | string, data: T): void {\r\n const eventName = event as string;\r\n const set = this.handlers.get(eventName);\r\n if (set) {\r\n set.forEach(handler => {\r\n try {\r\n handler(data);\r\n } catch (error) {\r\n console.error(`Error in event handler for ${eventName}:`, error);\r\n }\r\n });\r\n }\r\n }\r\n\r\n}\r\n\r\n// Shortcut export\r\nexport const triggerEmitter = TriggerEmitter.getInstance();\r\n",
|
|
13
|
+
"// -----------------------------------------------------------------------------\n// MOTOR DE REGLAS PARA TRIGGERS\n// -----------------------------------------------------------------------------\n\nimport type {\n TriggerRule,\n TriggerCondition,\n ConditionGroup,\n RuleCondition,\n TriggerAction,\n ActionGroup,\n TriggerContext,\n TriggerResult,\n RuleEngineConfig,\n} from \"../types\";\nimport { ExpressionEngine } from \"../core/expression-engine\";\n\n\nimport { ActionRegistry } from \"./action-registry\";\nimport { StateManager } from \"./state-manager\";\nimport { triggerEmitter, EngineEvent } from \"../utils/emitter\";\n\n\nexport class RuleEngine {\n private rules: TriggerRule[] = [];\n private config: RuleEngineConfig;\n private lastExecutionTimes: Map<string, number> = new Map();\n private actionRegistry: ActionRegistry;\n\n constructor(config: RuleEngineConfig) {\n this.config = config;\n this.rules = [...config.rules];\n this.rules.sort((a, b) => (b.priority || 0) - (a.priority || 0));\n this.actionRegistry = ActionRegistry.getInstance();\n }\n\n /**\n * Convenience method to process an event with a simple payload\n */\n async processEvent(eventType: string, data: Record<string, any> = {}, globals: Record<string, any> = {}): Promise<TriggerResult[]> {\n const context: TriggerContext = {\n event: eventType,\n data: data,\n globals: globals,\n timestamp: Date.now(),\n state: {} // State will be injected by evaluateContext\n };\n return this.evaluateContext(context);\n }\n\n\n /**\n * Evalúa todas las reglas contra el contexto proporcionado\n */\n async evaluateContext(context: TriggerContext): Promise<TriggerResult[]> {\n const results: TriggerResult[] = [];\n \n // Inject current state into context\n context.state = StateManager.getInstance().getAll();\n\n if (this.config.globalSettings.debugMode) {\n console.log(\n `[RuleEngine] Evaluando contexto con ${this.rules.length} reglas para evento: ${context.event}`,\n );\n }\n\n triggerEmitter.emit(EngineEvent.ENGINE_START, { context, rulesCount: this.rules.length });\n\n\n for (const rule of this.rules) {\n if (rule.enabled === false) continue;\n \n // Check event type match\n if (rule.on !== context.event) continue;\n\n // Verificar cooldown\n if (rule.cooldown && !this.checkCooldown(rule.id, rule.cooldown)) {\n if (this.config.globalSettings.debugMode) {\n console.log(`[RuleEngine] Regla ${rule.id} en cooldown`);\n }\n continue;\n }\n\n // Evaluar condiciones\n // rule.if can be undefined (always true), a single condition, or an array\n const conditionMet = this.evaluateRuleConditions(rule.if, context);\n\n if (conditionMet) {\n if (this.config.globalSettings.debugMode) {\n console.log(\n `[RuleEngine] Ejecutando regla: ${rule.name || rule.id}`,\n );\n }\n\n triggerEmitter.emit(EngineEvent.RULE_MATCH, { rule, context });\n\n\n // Ejecutar acciones\n const executedActions = await this.executeRuleActions(rule.do, context);\n\n results.push({\n ruleId: rule.id,\n executedActions: executedActions,\n success: true,\n });\n\n // Actualizar tiempo de última ejecución\n this.lastExecutionTimes.set(rule.id, Date.now());\n\n // Si no se deben evaluar todas las reglas, salir después de la primera coincidencia\n if (!this.config.globalSettings.evaluateAll) {\n break;\n }\n }\n }\n\n triggerEmitter.emit(EngineEvent.ENGINE_DONE, { results, context });\n\n return results;\n }\n\n // --- Condition Evaluation ---\n\n private evaluateRuleConditions(\n conditions: RuleCondition | RuleCondition[] | undefined,\n context: TriggerContext\n ): boolean {\n if (!conditions) return true; // No conditions = always trigger if event matches\n\n if (Array.isArray(conditions)) {\n // Implicit AND for array of conditions at root\n return conditions.every(c => this.evaluateRecursiveCondition(c, context));\n } else {\n return this.evaluateRecursiveCondition(conditions, context);\n }\n }\n\n private evaluateRecursiveCondition(\n condition: RuleCondition,\n context: TriggerContext\n ): boolean {\n // Check if it's a group\n if ('conditions' in condition && 'operator' in condition) {\n return this.evaluateConditionGroup(condition as ConditionGroup, context);\n } else {\n return this.evaluateSingleCondition(condition as TriggerCondition, context);\n }\n }\n\n private evaluateConditionGroup(group: ConditionGroup, context: TriggerContext): boolean {\n if (group.operator === 'OR') {\n return group.conditions.some(c => this.evaluateRecursiveCondition(c, context));\n } else {\n // AND\n return group.conditions.every(c => this.evaluateRecursiveCondition(c, context));\n }\n }\n\n\n /**\n * Evalúa una condición individual\n */\n private evaluateSingleCondition(\n condition: TriggerCondition,\n context: TriggerContext,\n ): boolean {\n try {\n // Obtener el valor del campo especificado\n const fieldValue = ExpressionEngine.getNestedValue(\n condition.field,\n context,\n );\n\n // Process condition.value - if it's a string, try to interpolate it\n // This allows comparing field: \"data.amount\" with value: \"${globals.threshold}\"\n let targetValue = condition.value;\n if (typeof targetValue === 'string' && (targetValue.includes('${') || targetValue.startsWith('data.') || targetValue.startsWith('globals.'))) {\n // If it looks like an expression or variable reference, evaluate it\n targetValue = ExpressionEngine.evaluate(targetValue, context);\n }\n\n // Helper for Date comparisons\n const getDate = (val: any) => {\n if (val instanceof Date) return val.getTime();\n if (typeof val === 'number') return val;\n const d = new Date(val);\n return isNaN(d.getTime()) ? 0 : d.getTime();\n };\n\n // Helper for Safe Numeric comparisons\n // Returns null if values are not strictly comparable as numbers (prevents null -> 0 coercion)\n const getSafeNumber = (val: any): number | null => {\n if (typeof val === 'number') return val;\n if (val === null || val === undefined || val === '') return null;\n const num = Number(val);\n return isNaN(num) ? null : num;\n };\n\n // Evaluar según el operador\n switch (condition.operator) {\n case \"EQ\":\n case \"==\":\n return fieldValue == targetValue; // Loose equality for flexibility\n\n case \"NEQ\":\n case \"!=\":\n return fieldValue != targetValue;\n\n case \"GT\":\n case \">\": {\n const nField = getSafeNumber(fieldValue);\n const nTarget = getSafeNumber(targetValue);\n return (nField !== null && nTarget !== null) && nField > nTarget;\n }\n\n case \"GTE\":\n case \">=\": {\n const nField = getSafeNumber(fieldValue);\n const nTarget = getSafeNumber(targetValue);\n return (nField !== null && nTarget !== null) && nField >= nTarget;\n }\n\n case \"LT\":\n case \"<\": {\n const nField = getSafeNumber(fieldValue);\n const nTarget = getSafeNumber(targetValue);\n return (nField !== null && nTarget !== null) && nField < nTarget;\n }\n\n case \"LTE\":\n case \"<=\": {\n const nField = getSafeNumber(fieldValue);\n const nTarget = getSafeNumber(targetValue);\n return (nField !== null && nTarget !== null) && nField <= nTarget;\n }\n\n case \"CONTAINS\":\n return String(fieldValue).includes(String(targetValue));\n \n case \"MATCHES\":\n return new RegExp(String(targetValue)).test(String(fieldValue));\n \n case \"IN\":\n return Array.isArray(targetValue) && targetValue.includes(fieldValue);\n\n case \"NOT_IN\":\n return Array.isArray(targetValue) && !targetValue.includes(fieldValue);\n \n // Date operators\n case \"SINCE\": // field >= value (Chronologically after or same)\n case \"AFTER\":\n return getDate(fieldValue) >= getDate(targetValue);\n \n case \"BEFORE\": // field < value\n case \"UNTIL\":\n return getDate(fieldValue) < getDate(targetValue);\n\n case \"RANGE\": // Special Case: Value should be [min, max]\n if (Array.isArray(targetValue) && targetValue.length === 2) {\n const nField = getSafeNumber(fieldValue);\n return nField !== null && nField >= Number(targetValue[0]) && nField <= Number(targetValue[1]);\n }\n return false;\n\n default:\n console.error(`Operador desconocido: ${condition.operator}`);\n return false;\n }\n } catch (error) {\n console.error(`Error evaluando condición:`, condition, error);\n return false;\n }\n }\n\n // --- Action Execution ---\n\n private async executeRuleActions(\n actions: TriggerAction | TriggerAction[] | ActionGroup,\n context: TriggerContext\n ): Promise<TriggerResult['executedActions']> {\n const enactedActions: TriggerResult['executedActions'] = [];\n\n let actionList: TriggerAction[] = [];\n let mode: 'ALL' | 'SEQUENCE' | 'EITHER' = 'ALL';\n\n if (this.isActionGroup(actions)) {\n actionList = actions.actions;\n mode = actions.mode;\n } else if (Array.isArray(actions)) {\n actionList = actions;\n } else {\n actionList = [actions];\n }\n\n if (mode === 'EITHER' && actionList.length > 0) {\n // Pick one randomly\n // Support probability later, for now uniform\n const randomIndex = Math.floor(Math.random() * actionList.length);\n const selectedAction = actionList[randomIndex];\n if (selectedAction) {\n actionList = [selectedAction];\n }\n }\n\n // Execute\n if (mode === 'SEQUENCE') {\n for (const action of actionList) {\n const result = await this.executeSingleAction(action, context);\n enactedActions.push(result);\n }\n } else {\n // ALL (Parallel-ish)\n // Note: We await them sequentially here to simplify, but logically they are \"all\". \n // If true parallel is needed, Promise.all could be used, but side-effects might clash.\n for (const action of actionList) {\n const result = await this.executeSingleAction(action, context);\n enactedActions.push(result);\n }\n }\n\n return enactedActions;\n }\n\n private isActionGroup(action: any): action is ActionGroup {\n return 'mode' in action && 'actions' in action;\n }\n\n\n private async executeSingleAction(\n action: TriggerAction,\n context: TriggerContext,\n ): Promise<TriggerResult['executedActions'][0]> {\n \n // Check probability\n if (action.probability !== undefined && Math.random() > action.probability) {\n return {\n type: action.type,\n timestamp: Date.now(),\n result: { skipped: \"probability check failed\" }\n };\n }\n\n // Check delay\n if (action.delay && action.delay > 0) {\n await new Promise(resolve => setTimeout(resolve, action.delay));\n }\n\n try {\n const handler = this.actionRegistry.get(action.type);\n let result;\n\n if (handler) {\n result = await handler(action, context);\n } else {\n const msg = `Tipo de acción genérica o desconocida: ${action.type}`;\n if (this.config.globalSettings.strictActions) {\n throw new Error(msg);\n }\n console.warn(msg);\n result = { warning: `Generic action executed: ${action.type}` };\n }\n\n triggerEmitter.emit(EngineEvent.ACTION_SUCCESS, { action, context, result });\n\n return {\n type: action.type,\n result,\n timestamp: Date.now()\n };\n } catch (error) {\n console.error(`Error ejecutando acción:`, action, error);\n triggerEmitter.emit(EngineEvent.ACTION_ERROR, { action, context, error: String(error) });\n\n return {\n type: action.type,\n error: String(error),\n timestamp: Date.now()\n };\n }\n }\n\n\n /**\n * Verifica si una regla está en cooldown\n */\n private checkCooldown(ruleId: string, cooldownMs: number): boolean {\n const lastExecution = this.lastExecutionTimes.get(ruleId);\n\n if (!lastExecution) return true;\n\n return Date.now() - lastExecution > cooldownMs;\n }\n\n /**\n * Actualiza las reglas del motor\n */\n updateRules(newRules: TriggerRule[]): void {\n this.rules = [...newRules];\n this.rules.sort((a, b) => (b.priority || 0) - (a.priority || 0));\n }\n\n /**\n * Obtiene todas las reglas\n */\n getRules(): TriggerRule[] {\n return [...this.rules];\n }\n}\n",
|
|
14
|
+
"// src/trigger_system/utils.ts\r\nimport type { TriggerContext } from \"../types\";\r\n\r\nexport class TriggerUtils {\r\n /**\r\n * Retrieves a nested value from the context using dot notation.\r\n * supports: data.field, globals.envVal, computed.result\r\n */\r\n static getNestedValue(path: string, context: TriggerContext): any {\r\n const parts = path.split(\".\");\r\n let current: any = context;\r\n\r\n for (const part of parts) {\r\n if (current === null || current === undefined) {\r\n return undefined;\r\n }\r\n current = current[part];\r\n }\r\n\r\n return current;\r\n }\r\n\r\n /**\r\n * Interpolates a string with values from the context.\r\n * Example: \"Hello ${data.username}\" -> \"Hello Steve\"\r\n */\r\n static interpolate(template: string, context: TriggerContext): string {\r\n if (typeof template !== 'string') return template;\r\n \r\n return template.replace(/\\$\\{([^}]+)\\}/g, (match, expression) => {\r\n // 1. Try direct path access first (fast)\r\n const directValue = this.getNestedValue(expression, context);\r\n if (directValue !== undefined) {\r\n return String(directValue);\r\n }\r\n \r\n // 2. Fallback to simple math evaluation if needed (optional, keeps it safe)\r\n // For now, we return the match if not found to avoid crashing or weird replacements\r\n return match;\r\n });\r\n }\r\n \r\n /**\r\n * Checks if a value satisfies a comparison operator against a criteria.\r\n */\r\n static compare(actual: any, operator: string, criteria: any): boolean {\r\n switch (operator) {\r\n case 'EQ':\r\n case '==':\r\n return actual == criteria;\r\n case 'NEQ':\r\n case '!=':\r\n return actual != criteria;\r\n case 'GT':\r\n case '>':\r\n return Number(actual) > Number(criteria);\r\n case 'GTE':\r\n case '>=':\r\n return Number(actual) >= Number(criteria);\r\n case 'LT':\r\n case '<':\r\n return Number(actual) < Number(criteria);\r\n case 'LTE':\r\n case '<=':\r\n return Number(actual) <= Number(criteria);\r\n case 'IN':\r\n return Array.isArray(criteria) && criteria.includes(actual);\r\n case 'NOT_IN':\r\n return Array.isArray(criteria) && !criteria.includes(actual);\r\n case 'CONTAINS':\r\n if (Array.isArray(actual) || typeof actual === 'string') {\r\n return actual.includes(criteria);\r\n }\r\n return false;\r\n case 'MATCHES':\r\n return new RegExp(criteria).test(String(actual));\r\n case 'RANGE':\r\n // criteria should be [min, max]\r\n if (Array.isArray(criteria) && criteria.length === 2) {\r\n const val = Number(actual);\r\n return val >= criteria[0] && val <= criteria[1];\r\n }\r\n return false;\r\n default:\r\n console.warn(`Unknown operator: ${operator}`);\r\n return false;\r\n }\r\n }\r\n}\r\n",
|
|
15
|
+
"// src/trigger_system/engine.ts\r\nimport type { \r\n TriggerRule, \r\n TriggerContext, \r\n TriggerResult, \r\n Action, \r\n ActionGroup, \r\n RuleCondition,\r\n Condition,\r\n ConditionGroup\r\n} from \"../types\";\r\nimport { TriggerUtils } from \"../utils/utils\";\r\n// import { TriggerLoader } from \"../io/loader\"; // Removed dependency\r\nimport { ExpressionEngine } from \"./expression-engine\";\r\n\r\nexport type EngineActionHandler = (params: any, context: TriggerContext) => Promise<any> | any;\r\n\r\nexport class TriggerEngine {\r\n private rules: TriggerRule[] = [];\r\n private actionHandlers: Map<string, EngineActionHandler> = new Map();\r\n private lastExecution: Map<string, number> = new Map();\r\n\r\n // Rules should be loaded externally and passed here\r\n constructor(rules: TriggerRule[] = []) {\r\n this.rules = rules;\r\n // Sort logic moved to where rules are set\r\n this.sortRules();\r\n }\r\n\r\n private sortRules() {\r\n this.rules.sort((a, b) => (b.priority || 0) - (a.priority || 0));\r\n }\r\n\r\n\r\n /**\r\n * Register a handler for a specific action type\r\n */\r\n registerAction(type: string, handler: EngineActionHandler) {\r\n this.actionHandlers.set(type, handler);\r\n }\r\n\r\n /**\r\n * Process an incoming event\r\n */\r\n async processEvent(context: TriggerContext): Promise<TriggerResult[]> {\r\n const results: TriggerResult[] = [];\r\n\r\n // Filter rules by event name\r\n const candidates = this.rules.filter(r => r.enabled !== false && r.on === context.event);\r\n\r\n for (const rule of candidates) {\r\n // Check Cooldown\r\n if (rule.cooldown && this.checkCooldown(rule.id, rule.cooldown)) {\r\n continue; // Skip if in cooldown\r\n }\r\n\r\n // Evaluate Conditions\r\n if (this.evaluateConditions(rule.if, context)) {\r\n // Execute Actions\r\n const execResult = await this.executeRuleActions(rule.do, context);\r\n \r\n // Update Cooldown\r\n this.lastExecution.set(rule.id, Date.now());\r\n\r\n results.push({\r\n ruleId: rule.id,\r\n success: true,\r\n executedActions: execResult\r\n });\r\n }\r\n }\r\n\r\n return results;\r\n }\r\n\r\n private checkCooldown(ruleId: string, cooldown: number): boolean {\r\n const last = this.lastExecution.get(ruleId);\r\n if (!last) return false;\r\n return (Date.now() - last) < cooldown;\r\n }\r\n\r\n private evaluateConditions(\r\n condition: RuleCondition | RuleCondition[] | undefined, \r\n context: TriggerContext\r\n ): boolean {\r\n if (!condition) return true; // No conditions = always true\r\n\r\n if (Array.isArray(condition)) {\r\n // Implicit AND for array of conditions\r\n return condition.every(c => this.evaluateSingleCondition(c, context));\r\n }\r\n\r\n return this.evaluateSingleCondition(condition, context);\r\n }\r\n\r\n private evaluateSingleCondition(cond: RuleCondition, context: TriggerContext): boolean {\r\n // Check if it's a Group\r\n if ('operator' in cond && 'conditions' in cond) {\r\n const group = cond as ConditionGroup;\r\n if (group.operator === 'OR') {\r\n return group.conditions.some(c => this.evaluateSingleCondition(c, context));\r\n } else { // AND\r\n return group.conditions.every(c => this.evaluateSingleCondition(c, context));\r\n }\r\n }\r\n\r\n // It's a simple Condition\r\n const c = cond as Condition;\r\n const actualValue = TriggerUtils.getNestedValue(c.field, context);\r\n // Interpolate the expected value if it's a string containing variables\r\n let expectedValue = c.value;\r\n if (typeof expectedValue === 'string' && expectedValue.includes('${')) {\r\n expectedValue = ExpressionEngine.interpolate(expectedValue, context);\r\n }\r\n \r\n return TriggerUtils.compare(actualValue, c.operator, expectedValue);\r\n }\r\n\r\n private async executeRuleActions(\r\n actionConfig: Action | Action[] | ActionGroup, \r\n context: TriggerContext\r\n ): Promise<any[]> {\r\n const executionLogs: any[] = [];\r\n\r\n // Normalize to ActionGroup or List\r\n let actionsToExecute: Action[] = [];\r\n let mode = 'ALL';\r\n\r\n if (Array.isArray(actionConfig)) {\r\n actionsToExecute = actionConfig;\r\n } else if ('mode' in actionConfig && 'actions' in actionConfig) {\r\n const group = actionConfig as ActionGroup;\r\n mode = group.mode;\r\n actionsToExecute = group.actions;\r\n } else {\r\n // Single Action\r\n actionsToExecute = [actionConfig as Action];\r\n }\r\n\r\n // Handle Modes\r\n if (mode === 'EITHER') {\r\n // Pick one randomly\r\n // Support probability weights if present?\r\n // For now simple random\r\n const totalWeight = actionsToExecute.reduce((sum, a) => sum + (a.probability || 1), 0);\r\n let random = Math.random() * totalWeight;\r\n \r\n let selected: Action | undefined;\r\n for (const action of actionsToExecute) {\r\n const weight = action.probability || 1;\r\n random -= weight;\r\n if (random <= 0) {\r\n selected = action;\r\n break;\r\n }\r\n }\r\n // Fallback\r\n if (!selected && actionsToExecute.length > 0) selected = actionsToExecute[actionsToExecute.length - 1];\r\n\r\n if (selected) {\r\n actionsToExecute = [selected];\r\n } else {\r\n actionsToExecute = [];\r\n }\r\n }\r\n\r\n // Execute\r\n for (const action of actionsToExecute) {\r\n // Interpolate Params\r\n const processedParams = this.interpolateParams(action.params || {}, context);\r\n const handler = this.actionHandlers.get(action.type);\r\n\r\n if (handler) {\r\n try {\r\n // Handle Delay\r\n if (action.delay && action.delay > 0) {\r\n await new Promise(r => setTimeout(r, action.delay));\r\n }\r\n\r\n const result = await handler(processedParams, context);\r\n executionLogs.push({\r\n type: action.type,\r\n result,\r\n timestamp: Date.now()\r\n });\r\n } catch (err) {\r\n console.error(`Action ${action.type} failed:`, err);\r\n executionLogs.push({\r\n type: action.type,\r\n error: err,\r\n timestamp: Date.now()\r\n });\r\n }\r\n } else {\r\n console.warn(`No handler registered for action type: ${action.type}`);\r\n executionLogs.push({\r\n type: action.type,\r\n error: \"No handler registered\",\r\n timestamp: Date.now()\r\n });\r\n }\r\n }\r\n\r\n return executionLogs;\r\n }\r\n\r\n private interpolateParams(params: Record<string, any>, context: TriggerContext): Record<string, any> {\r\n const result: Record<string, any> = {};\r\n for (const [key, val] of Object.entries(params)) {\r\n if (typeof val === 'string') {\r\n result[key] = ExpressionEngine.interpolate(val, context);\r\n } else if (typeof val === 'object' && val !== null) {\r\n // Recursive?\r\n // JSON objects might need deep interpolation.\r\n // For now simple 1-level or stringify\r\n // Let's do simple recursion for nice nested params\r\n result[key] = this.interpolateDeep(val, context);\r\n } else {\r\n result[key] = val;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private interpolateDeep(obj: any, context: TriggerContext): any {\r\n if (typeof obj === 'string') return ExpressionEngine.interpolate(obj, context);\r\n if (Array.isArray(obj)) return obj.map(v => this.interpolateDeep(v, context));\r\n if (typeof obj === 'object' && obj !== null) {\r\n const res: any = {};\r\n for(const k in obj) res[k] = this.interpolateDeep(obj[k], context);\r\n return res;\r\n }\r\n return obj;\r\n }\r\n}\r\n",
|
|
16
|
+
"/**\n * Extracts duplicated elements and their indices from an array, returning them.\n *\n * Note that given `a === b && b === c`, then `c === a` must be `true` for this to give accurate results.\n *\n * @param arr The array to extract duplicate elements from.\n */ export const getDuplicatesOf = (arr, opts) => {\n const isEqual = opts?.isEqual ?? ((l, r) => l === r);\n const elementFirstSeenIndx = new Map();\n const duplicates = [];\n for (const [indx, element] of arr.entries()) {\n const duplicatesIndx = duplicates.findIndex(duplicate => isEqual(duplicate.element, element));\n if (duplicatesIndx !== -1) {\n // This is at least the third occurrence of an item equal to `element`,\n // so add this index to the list of indices where the element is duplicated.\n duplicates[duplicatesIndx].indices.push(indx);\n continue;\n }\n // At this point, we know this is either the first\n // or second occurrence of an item equal to `element`...\n let found = false;\n for (const [existingElement, firstSeenIndx] of elementFirstSeenIndx) {\n if (isEqual(element, existingElement)) {\n // This is the second occurrence of an item equal to `element`,\n // so store it as a duplicate.\n found = true;\n duplicates.push({\n element: existingElement,\n indices: [firstSeenIndx, indx]\n });\n }\n }\n if (!found) {\n // We haven't seen this element before,\n // so just store the index it was first seen\n elementFirstSeenIndx.set(element, indx);\n }\n }\n return duplicates;\n};\nexport const join = (segments, delimiter) => segments.join(delimiter);\nexport const getPath = (root, path) => {\n let result = root;\n for (const segment of path) {\n if (typeof result !== \"object\" || result === null)\n return undefined;\n result = result[segment];\n }\n return result;\n};\nexport const intersectUniqueLists = (l, r) => {\n const intersection = [...l];\n for (const item of r)\n if (!l.includes(item))\n intersection.push(item);\n return intersection;\n};\nexport const liftArray = (data) => (Array.isArray(data) ? data : [data]);\n/**\n * Splits an array into two arrays based on the result of a predicate\n *\n * @param predicate - The guard function used to determine which items to include.\n * @returns A tuple containing two arrays:\n * \t\t\t\t- the first includes items for which `predicate` returns true\n * \t\t\t\t- the second includes items for which `predicate` returns false\n *\n * @example\n * const list = [1, \"2\", \"3\", 4, 5];\n * const [numbers, strings] = spliterate(list, (x) => typeof x === \"number\");\n * // Type: number[]\n * // Output: [1, 4, 5]\n * console.log(evens);\n * // Type: string[]\n * // Output: [\"2\", \"3\"]\n * console.log(odds);\n */\nexport const spliterate = (arr, predicate) => {\n const result = [[], []];\n for (const item of arr) {\n if (predicate(item))\n result[0].push(item);\n else\n result[1].push(item);\n }\n return result;\n};\nexport const ReadonlyArray = Array;\nexport const includes = (array, element) => array.includes(element);\nexport const range = (length, offset = 0) => [...new Array(length)].map((_, i) => i + offset);\n/**\n * Adds a value or array to an array, returning the concatenated result\n */\nexport const append = (to, value, opts) => {\n if (to === undefined) {\n return (value === undefined ? []\n : Array.isArray(value) ? value\n : [value]);\n }\n if (opts?.prepend) {\n if (Array.isArray(value))\n to.unshift(...value);\n else\n to.unshift(value);\n }\n else {\n if (Array.isArray(value))\n to.push(...value);\n else\n to.push(value);\n }\n return to;\n};\n/**\n * Concatenates an element or list with a readonly list\n */\nexport const conflatenate = (to, elementOrList) => {\n if (elementOrList === undefined || elementOrList === null)\n return to ?? [];\n if (to === undefined || to === null)\n return liftArray(elementOrList);\n return to.concat(elementOrList);\n};\n/**\n * Concatenates a variadic list of elements or lists with a readonly list\n */\nexport const conflatenateAll = (...elementsOrLists) => elementsOrLists.reduce(conflatenate, []);\n/**\n * Appends a value or concatenates an array to an array if it is not already included, returning the array\n */\nexport const appendUnique = (to, value, opts) => {\n if (to === undefined)\n return Array.isArray(value) ? value : [value];\n const isEqual = opts?.isEqual ?? ((l, r) => l === r);\n for (const v of liftArray(value))\n if (!to.some(existing => isEqual(existing, v)))\n to.push(v);\n return to;\n};\nexport const groupBy = (array, discriminant) => array.reduce((result, item) => {\n const key = item[discriminant];\n result[key] = append(result[key], item);\n return result;\n}, {});\nexport const arrayEquals = (l, r, opts) => l.length === r.length &&\n l.every(opts?.isEqual ?\n (lItem, i) => opts.isEqual(lItem, r[i])\n : (lItem, i) => lItem === r[i]);\n",
|
|
17
|
+
"export const hasDomain = (data, kind) => domainOf(data) === kind;\nexport const domainOf = (data) => {\n const builtinType = typeof data;\n return (builtinType === \"object\" ?\n data === null ?\n \"null\"\n : \"object\"\n : builtinType === \"function\" ? \"object\"\n : builtinType);\n};\n/** Each domain's completion for the phrase \"must be _____\" */\nexport const domainDescriptions = {\n boolean: \"boolean\",\n null: \"null\",\n undefined: \"undefined\",\n bigint: \"a bigint\",\n number: \"a number\",\n object: \"an object\",\n string: \"a string\",\n symbol: \"a symbol\"\n};\nexport const jsTypeOfDescriptions = {\n ...domainDescriptions,\n function: \"a function\"\n};\n",
|
|
18
|
+
"export class InternalArktypeError extends Error {\n}\nexport const throwInternalError = message => throwError(message, InternalArktypeError);\nexport const throwError = (message, ctor = Error) => {\n throw new ctor(message);\n};\nexport class ParseError extends Error {\n name = \"ParseError\";\n}\nexport const throwParseError = message => throwError(message, ParseError);\n/**\n * TypeScript won't suggest strings beginning with a space as properties.\n * Useful for symbol-like string properties.\n */\nexport const noSuggest = (s) => ` ${s}`;\n/** Unrendered character (U+200B) used to mark a string type */\nexport const ZeroWidthSpace = \"\\u{200B}\";\n",
|
|
19
|
+
"import { append } from \"./arrays.js\";\nexport const flatMorph = (o, flatMapEntry) => {\n const result = {};\n const inputIsArray = Array.isArray(o);\n let outputShouldBeArray = false;\n for (const [i, entry] of Object.entries(o).entries()) {\n const mapped = inputIsArray ? flatMapEntry(i, entry[1]) : flatMapEntry(...entry, i);\n outputShouldBeArray ||= typeof mapped[0] === \"number\";\n const flattenedEntries = Array.isArray(mapped[0]) || mapped.length === 0 ?\n // if we have an empty array (for filtering) or an array with\n // another array as its first element, treat it as a list\n mapped\n // otherwise, it should be a single entry, so nest it in a tuple\n // so it doesn't get spread when the result is flattened\n : [mapped];\n for (const [k, v] of flattenedEntries) {\n if (typeof k === \"object\")\n result[k.group] = append(result[k.group], v);\n else\n result[k] = v;\n }\n }\n return outputShouldBeArray ? Object.values(result) : result;\n};\n",
|
|
20
|
+
"import { noSuggest, ZeroWidthSpace } from \"./errors.js\";\nimport { flatMorph } from \"./flatMorph.js\";\n/**\n * Object.entries wrapper providing narrowed types for objects with known sets\n * of keys, e.g. those defined internally as configs\n */\nexport const entriesOf = Object.entries;\nexport const fromEntries = (entries) => Object.fromEntries(entries);\nexport const keysOf = (o) => Object.keys(o);\nexport const isKeyOf = (k, o) => k in o;\nexport const hasKey = (o, k) => k in o;\n// must be defined this way to avoid https://github.com/microsoft/TypeScript/issues/55049\nexport const hasDefinedKey = (o, k) => o[k] !== undefined;\nexport const InnerDynamicBase = class {\n};\nexport class DynamicBase {\n constructor(properties) {\n Object.assign(this, properties);\n }\n}\nexport const NoopBase = class {\n};\n/** @ts-ignore (needed to extend `t`) **/\nexport class CastableBase extends NoopBase {\n}\nexport const splitByKeys = (o, leftKeys) => {\n const l = {};\n const r = {};\n let k;\n for (k in o) {\n if (k in leftKeys)\n l[k] = o[k];\n else\n r[k] = o[k];\n }\n return [l, r];\n};\nexport const pick = (o, keys) => splitByKeys(o, keys)[0];\nexport const omit = (o, keys) => splitByKeys(o, keys)[1];\nexport const isEmptyObject = (o) => Object.keys(o).length === 0;\nexport const stringAndSymbolicEntriesOf = (o) => [\n ...Object.entries(o),\n ...Object.getOwnPropertySymbols(o).map(k => [k, o[k]])\n];\n/** Like Object.assign, but it will preserve getters instead of evaluating them. */\nexport const defineProperties = (base, merged) => \n// declared like this to avoid https://github.com/microsoft/TypeScript/issues/55049\nObject.defineProperties(base, Object.getOwnPropertyDescriptors(merged));\n/** Copies enumerable keys of o to a new object in alphabetical order */\nexport const withAlphabetizedKeys = (o) => {\n const keys = Object.keys(o).sort();\n const result = {};\n for (let i = 0; i < keys.length; i++)\n result[keys[i]] = o[keys[i]];\n return result;\n};\nexport const invert = (t) => flatMorph(t, (k, v) => [v, k]);\nexport const unset = noSuggest(`unset${ZeroWidthSpace}`);\nexport const enumValues = (tsEnum) => Object.values(tsEnum).filter(v => {\n if (typeof v === \"number\")\n return true;\n return typeof tsEnum[v] !== \"number\";\n});\n",
|
|
21
|
+
"import { domainOf } from \"./domain.js\";\nimport { isKeyOf } from \"./records.js\";\n// ECMAScript Objects\n// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects\nexport const ecmascriptConstructors = {\n Array,\n Boolean,\n Date,\n Error,\n Function,\n Map,\n Number,\n Promise,\n RegExp,\n Set,\n String,\n WeakMap,\n WeakSet\n};\n/** Node18 */\nexport const FileConstructor = globalThis.File ?? Blob;\n// Platform APIs\n// See https://developer.mozilla.org/en-US/docs/Web/API\n// Must be implemented in Node etc. as well as the browser to include here\nexport const platformConstructors = {\n ArrayBuffer,\n Blob,\n File: FileConstructor,\n FormData,\n Headers,\n Request,\n Response,\n URL\n};\nexport const typedArrayConstructors = {\n Int8Array,\n Uint8Array,\n Uint8ClampedArray,\n Int16Array,\n Uint16Array,\n Int32Array,\n Uint32Array,\n Float32Array,\n Float64Array,\n BigInt64Array,\n BigUint64Array\n};\n// Built-in object constructors based on a subset of:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects\nexport const builtinConstructors = {\n ...ecmascriptConstructors,\n ...platformConstructors,\n ...typedArrayConstructors,\n String,\n Number,\n Boolean\n};\nexport const objectKindOf = (data) => {\n let prototype = Object.getPrototypeOf(data);\n while (prototype?.constructor &&\n (!isKeyOf(prototype.constructor.name, builtinConstructors) ||\n !(data instanceof builtinConstructors[prototype.constructor.name])))\n prototype = Object.getPrototypeOf(prototype);\n const name = prototype?.constructor?.name;\n if (name === undefined || name === \"Object\")\n return undefined;\n return name;\n};\nexport const objectKindOrDomainOf = (data) => (typeof data === \"object\" && data !== null ?\n (objectKindOf(data) ?? \"object\")\n : domainOf(data));\nexport const hasObjectKind = (data, kind) => objectKindOf(data) === kind;\nexport const isArray = Array.isArray;\nexport const ecmascriptDescriptions = {\n Array: \"an array\",\n Function: \"a function\",\n Date: \"a Date\",\n RegExp: \"a RegExp\",\n Error: \"an Error\",\n Map: \"a Map\",\n Set: \"a Set\",\n String: \"a String object\",\n Number: \"a Number object\",\n Boolean: \"a Boolean object\",\n Promise: \"a Promise\",\n WeakMap: \"a WeakMap\",\n WeakSet: \"a WeakSet\"\n};\nexport const platformDescriptions = {\n ArrayBuffer: \"an ArrayBuffer instance\",\n Blob: \"a Blob instance\",\n File: \"a File instance\",\n FormData: \"a FormData instance\",\n Headers: \"a Headers instance\",\n Request: \"a Request instance\",\n Response: \"a Response instance\",\n URL: \"a URL instance\"\n};\nexport const typedArrayDescriptions = {\n Int8Array: \"an Int8Array\",\n Uint8Array: \"a Uint8Array\",\n Uint8ClampedArray: \"a Uint8ClampedArray\",\n Int16Array: \"an Int16Array\",\n Uint16Array: \"a Uint16Array\",\n Int32Array: \"an Int32Array\",\n Uint32Array: \"a Uint32Array\",\n Float32Array: \"a Float32Array\",\n Float64Array: \"a Float64Array\",\n BigInt64Array: \"a BigInt64Array\",\n BigUint64Array: \"a BigUint64Array\"\n};\n/** Each defaultObjectKind's completion for the phrase \"must be _____\" */\nexport const objectKindDescriptions = {\n ...ecmascriptDescriptions,\n ...platformDescriptions,\n ...typedArrayDescriptions\n};\n/**\n * this will only return an object kind if it's the root constructor\n * example TypeError would return null not 'Error'\n **/\nexport const getBuiltinNameOfConstructor = (ctor) => {\n const constructorName = Object(ctor).name ?? null;\n return (constructorName &&\n isKeyOf(constructorName, builtinConstructors) &&\n builtinConstructors[constructorName] === ctor) ?\n constructorName\n : null;\n};\n/**\n * Returns an array of constructors for all ancestors (i.e., prototypes) of a given object.\n */\nexport const ancestorsOf = (o) => {\n let proto = Object.getPrototypeOf(o);\n const result = [];\n while (proto !== null) {\n result.push(proto.constructor);\n proto = Object.getPrototypeOf(proto);\n }\n return result;\n};\nexport const constructorExtends = (ctor, base) => {\n let current = ctor.prototype;\n while (current !== null) {\n if (current === base.prototype)\n return true;\n current = Object.getPrototypeOf(current);\n }\n return false;\n};\n",
|
|
22
|
+
"import { getBuiltinNameOfConstructor } from \"./objectKinds.js\";\n/** Shallowly copy the properties of the object. */\nexport const shallowClone = input => _clone(input, null);\n/** Deeply copy the properties of the a non-subclassed Object, Array or Date.*/\nexport const deepClone = (input) => _clone(input, new Map());\nconst _clone = (input, seen) => {\n if (typeof input !== \"object\" || input === null)\n return input;\n if (seen?.has(input))\n return seen.get(input);\n const builtinConstructorName = getBuiltinNameOfConstructor(input.constructor);\n if (builtinConstructorName === \"Date\")\n return new Date(input.getTime());\n // we don't try and clone other prototypes here since this we can't guarantee arrow functions attached to the object\n // are rebound in case they reference `this` (see https://x.com/colinhacks/status/1818422039210049985)\n if (builtinConstructorName && builtinConstructorName !== \"Array\")\n return input;\n const cloned = Array.isArray(input) ?\n input.slice()\n : Object.create(Object.getPrototypeOf(input));\n const propertyDescriptors = Object.getOwnPropertyDescriptors(input);\n if (seen) {\n seen.set(input, cloned);\n for (const k in propertyDescriptors) {\n const desc = propertyDescriptors[k];\n if (\"get\" in desc || \"set\" in desc)\n continue;\n desc.value = _clone(desc.value, seen);\n }\n }\n Object.defineProperties(cloned, propertyDescriptors);\n return cloned;\n};\n",
|
|
23
|
+
"import { throwInternalError } from \"./errors.js\";\nimport { unset } from \"./records.js\";\nexport const cached = (thunk) => {\n let result = unset;\n return () => (result === unset ? (result = thunk()) : result);\n};\nexport const isThunk = (value) => typeof value === \"function\" && value.length === 0;\nexport const tryCatch = (fn, onError) => {\n try {\n return fn();\n }\n catch (e) {\n return onError?.(e);\n }\n};\nexport const DynamicFunction = class extends Function {\n constructor(...args) {\n const params = args.slice(0, -1);\n const body = args[args.length - 1];\n try {\n super(...params, body);\n }\n catch (e) {\n return throwInternalError(`Encountered an unexpected error while compiling your definition:\n Message: ${e} \n Source: (${args.slice(0, -1)}) => {\n ${args[args.length - 1]}\n }`);\n }\n }\n};\nexport class Callable {\n constructor(fn, ...[opts]) {\n return Object.assign(Object.setPrototypeOf(fn.bind(opts?.bind ?? this), this.constructor.prototype), opts?.attach);\n }\n}\n/**\n * Checks if the environment has Content Security Policy (CSP) enabled,\n * preventing JIT-optimized code from being compiled via new Function().\n *\n * @returns `true` if a function created using new Function() can be\n * successfully invoked in the environment, `false` otherwise.\n *\n * The result is cached for subsequent invocations.\n */\nexport const envHasCsp = cached(() => {\n try {\n return new Function(\"return false\")();\n }\n catch {\n return true;\n }\n});\n",
|
|
24
|
+
"import { noSuggest } from \"./errors.js\";\nexport const brand = noSuggest(\"brand\");\nexport const narrow = (t) => t;\n/** primitive key used to represent an inferred type at compile-time */\nexport const inferred = noSuggest(\"arkInferred\");\n",
|
|
25
|
+
"import { noSuggest } from \"./errors.js\";\nconst args = noSuggest(\"args\");\nexport class Hkt {\n constructor() { }\n}\n",
|
|
26
|
+
"// based on the util of the same name in @ark/fs\n// isolated here for use with registry\n/** get a CJS/ESM compatible string representing the current file */\nconst fileName = () => {\n try {\n const error = new Error();\n const stackLine = error.stack?.split(\"\\n\")[2]?.trim() || \"\"; // [1]=this func, [2]=caller\n const filePath = stackLine.match(/\\(?(.+?)(?::\\d+:\\d+)?\\)?$/)?.[1] || \"unknown\";\n return filePath.replace(/^file:\\/\\//, \"\");\n }\n catch {\n return \"unknown\";\n }\n};\nconst env = globalThis.process?.env ?? {};\nexport const isomorphic = {\n fileName,\n env\n};\n",
|
|
27
|
+
"export const capitalize = (s) => (s[0].toUpperCase() + s.slice(1));\nexport const uncapitalize = (s) => (s[0].toLowerCase() + s.slice(1));\nexport const anchoredRegex = (regex) => new RegExp(anchoredSource(regex), typeof regex === \"string\" ? \"\" : regex.flags);\nexport const deanchoredRegex = (regex) => new RegExp(deanchoredSource(regex), typeof regex === \"string\" ? \"\" : regex.flags);\nexport const anchoredSource = (regex) => {\n const source = typeof regex === \"string\" ? regex : regex.source;\n return `^(?:${source})$`;\n};\nexport const deanchoredSource = (regex) => {\n const source = typeof regex === \"string\" ? regex : regex.source;\n if (source.startsWith(\"^(?:\") && source.endsWith(\")$\"))\n return source.slice(4, -2);\n return source.slice(source[0] === \"^\" ? 1 : 0, source[source.length - 1] === \"$\" ? -1 : undefined);\n};\nexport const RegexPatterns = {\n negativeLookahead: (pattern) => `(?!${pattern})`,\n nonCapturingGroup: (pattern) => `(?:${pattern})`\n};\nexport const Backslash = \"\\\\\";\nexport const whitespaceChars = {\n \" \": 1,\n \"\\n\": 1,\n \"\\t\": 1\n};\nexport const emojiToUnicode = (emoji) => emoji\n .split(\"\")\n .map(char => {\n const codePoint = char.codePointAt(0);\n return codePoint ? `\\\\u${codePoint.toString(16).padStart(4, \"0\")}` : \"\";\n})\n .join(\"\");\nexport const alphabet = [\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];\n",
|
|
28
|
+
"import { throwParseError } from \"./errors.js\";\nimport { anchoredRegex, RegexPatterns } from \"./strings.js\";\n/*\n * The goal of the number literal and bigint literal regular expressions is to:\n *\n * 1. Ensure definitions form a bijection with the values they represent.\n * 2. Attempt to mirror TypeScript's own format for stringification of numeric\n * values such that the regex should match a given definition if any only if\n * a precise literal type will be inferred (in TS4.8+).\n */\nconst anchoredNegativeZeroPattern = /^-0\\.?0*$/.source;\nconst positiveIntegerPattern = /[1-9]\\d*/.source;\nconst looseDecimalPattern = /\\.\\d+/.source;\nconst strictDecimalPattern = /\\.\\d*[1-9]/.source;\nconst createNumberMatcher = (opts) => anchoredRegex(RegexPatterns.negativeLookahead(anchoredNegativeZeroPattern) +\n RegexPatterns.nonCapturingGroup(\"-?\" +\n RegexPatterns.nonCapturingGroup(RegexPatterns.nonCapturingGroup(\"0|\" + positiveIntegerPattern) +\n RegexPatterns.nonCapturingGroup(opts.decimalPattern) +\n \"?\") +\n (opts.allowDecimalOnly ? \"|\" + opts.decimalPattern : \"\") +\n \"?\"));\n/**\n * Matches a well-formatted numeric expression according to the following rules:\n * 1. Must include an integer portion (i.e. '.321' must be written as '0.321')\n * 2. The first digit of the value must not be 0, unless the entire integer portion is 0\n * 3. If the value includes a decimal, its last digit may not be 0\n * 4. The value may not be \"-0\"\n */\nexport const wellFormedNumberMatcher = createNumberMatcher({\n decimalPattern: strictDecimalPattern,\n allowDecimalOnly: false\n});\nexport const isWellFormedNumber = wellFormedNumberMatcher.test.bind(wellFormedNumberMatcher);\n/**\n * Similar to wellFormedNumber but more permissive in the following ways:\n *\n * - Allows numbers without an integer portion like \".5\" (well-formed equivalent is \"0.5\")\n * - Allows decimals with trailing zeroes like \"0.10\" (well-formed equivalent is \"0.1\")\n */\nexport const numericStringMatcher = createNumberMatcher({\n decimalPattern: looseDecimalPattern,\n allowDecimalOnly: true\n});\nexport const isNumericString = numericStringMatcher.test.bind(numericStringMatcher);\nexport const numberLikeMatcher = /^-?\\d*\\.?\\d*$/;\nconst isNumberLike = (s) => s.length !== 0 && numberLikeMatcher.test(s);\n/**\n * Matches a well-formatted integer according to the following rules:\n * 1. must begin with an integer, the first digit of which cannot be 0 unless the entire value is 0\n * 2. The value may not be \"-0\"\n */\nexport const wellFormedIntegerMatcher = anchoredRegex(RegexPatterns.negativeLookahead(\"^-0$\") +\n \"-?\" +\n RegexPatterns.nonCapturingGroup(RegexPatterns.nonCapturingGroup(\"0|\" + positiveIntegerPattern)));\nexport const isWellFormedInteger = wellFormedIntegerMatcher.test.bind(wellFormedIntegerMatcher);\nexport const integerLikeMatcher = /^-?\\d+$/;\nconst isIntegerLike = integerLikeMatcher.test.bind(integerLikeMatcher);\nconst numericLiteralDescriptions = {\n number: \"a number\",\n bigint: \"a bigint\",\n integer: \"an integer\"\n};\nexport const writeMalformedNumericLiteralMessage = (def, kind) => `'${def}' was parsed as ${numericLiteralDescriptions[kind]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`;\nconst isWellFormed = (def, kind) => kind === \"number\" ? isWellFormedNumber(def) : isWellFormedInteger(def);\nconst parseKind = (def, kind) => kind === \"number\" ? Number(def) : Number.parseInt(def);\nconst isKindLike = (def, kind) => kind === \"number\" ? isNumberLike(def) : isIntegerLike(def);\nexport const tryParseNumber = (token, options) => parseNumeric(token, \"number\", options);\nexport const tryParseWellFormedNumber = (token, options) => parseNumeric(token, \"number\", { ...options, strict: true });\nexport const tryParseInteger = (token, options) => parseNumeric(token, \"integer\", options);\nconst parseNumeric = (token, kind, options) => {\n const value = parseKind(token, kind);\n if (!Number.isNaN(value)) {\n if (isKindLike(token, kind)) {\n if (options?.strict) {\n return isWellFormed(token, kind) ? value : (throwParseError(writeMalformedNumericLiteralMessage(token, kind)));\n }\n return value;\n }\n }\n return (options?.errorOnFail ?\n throwParseError(options?.errorOnFail === true ?\n `Failed to parse ${numericLiteralDescriptions[kind]} from '${token}'`\n : options?.errorOnFail)\n : undefined);\n};\nexport const tryParseWellFormedBigint = (def) => {\n if (def[def.length - 1] !== \"n\")\n return;\n const maybeIntegerLiteral = def.slice(0, -1);\n let value;\n try {\n value = BigInt(maybeIntegerLiteral);\n }\n catch {\n return;\n }\n if (wellFormedIntegerMatcher.test(maybeIntegerLiteral))\n return value;\n if (integerLikeMatcher.test(maybeIntegerLiteral)) {\n // If the definition looks like a bigint but is\n // not well-formed, throw.\n return throwParseError(writeMalformedNumericLiteralMessage(def, \"bigint\"));\n }\n};\n/**\n * Returns the next or previous representable floating-point number after the given input.\n *\n * @param {\"+\" | \"-\"} [direction=\"+\"] - The direction to find the nearest float. \"+\" for the next float, \"-\" for the previous float.\n * @throws {Error} If the input is not a finite number.\n *\n * @example\n * console.log(nearestFloat(0)); // Smallest positive number\n * console.log(nearestFloat(2)); // 2.0000000000000004\n * console.log(nearestFloat(2.1)); // 2.1000000000000005\n * console.log(nearestFloat(2, \"-\")); // 1.9999999999999998\n * console.log(nearestFloat(2.1, \"-\")); // 2.0999999999999996\n * // as size of input increases, the increments become larger to stay within what\n * // JS can represent in a numeric value\n * console.log(nearestFloat(5555555555555555)); // 5555555555555556\n * console.log(nearestFloat(5555555555555555, \"-\")); // 5555555555555554\n */\nexport const nearestFloat = (n, direction = \"+\") => {\n const buffer = new ArrayBuffer(8);\n const f64 = new Float64Array(buffer);\n const u32 = new Uint32Array(buffer);\n f64[0] = n;\n if (n === 0) {\n u32[0] = 1;\n u32[1] = direction === \"-\" ? 1 << 31 : 0;\n }\n else if ((n > 0 && direction === \"+\") || (n < 0 && direction === \"-\")) {\n if (u32[0]++ === 0xffffffff)\n u32[1]++;\n }\n else if (u32[0]-- === 0)\n u32[1]--;\n return f64[0];\n};\n",
|
|
29
|
+
"import { domainOf } from \"./domain.js\";\nimport { throwInternalError } from \"./errors.js\";\nimport { isomorphic } from \"./isomorphic.js\";\nimport { FileConstructor, objectKindOf } from \"./objectKinds.js\";\n// Eventually we can just import from package.json in the source itself\n// but for now, import assertions are too unstable and it wouldn't support\n// recent node versions (https://nodejs.org/api/esm.html#json-modules).\n// For now, we assert this matches the package.json version via a unit test.\nexport const arkUtilVersion = \"0.56.0\";\nexport const initialRegistryContents = {\n version: arkUtilVersion,\n filename: isomorphic.fileName(),\n FileConstructor\n};\nexport const registry = initialRegistryContents;\nconst namesByResolution = new Map();\nconst nameCounts = Object.create(null);\nexport const register = (value) => {\n const existingName = namesByResolution.get(value);\n if (existingName)\n return existingName;\n let name = baseNameFor(value);\n if (nameCounts[name])\n name = `${name}${nameCounts[name]++}`;\n else\n nameCounts[name] = 1;\n registry[name] = value;\n namesByResolution.set(value, name);\n return name;\n};\nexport const isDotAccessible = (keyName) => /^[$A-Z_a-z][\\w$]*$/.test(keyName);\nconst baseNameFor = (value) => {\n switch (typeof value) {\n case \"object\": {\n if (value === null)\n break;\n const prefix = objectKindOf(value) ?? \"object\";\n // convert to camelCase\n return prefix[0].toLowerCase() + prefix.slice(1);\n }\n case \"function\":\n return isDotAccessible(value.name) ? value.name : \"fn\";\n case \"symbol\":\n return value.description && isDotAccessible(value.description) ?\n value.description\n : \"symbol\";\n }\n return throwInternalError(`Unexpected attempt to register serializable value of type ${domainOf(value)}`);\n};\n",
|
|
30
|
+
"export const serializePrimitive = (value) => (typeof value === \"string\" ? JSON.stringify(value)\n : typeof value === \"bigint\" ? `${value}n`\n : `${value}`);\n",
|
|
31
|
+
"import { domainOf } from \"./domain.js\";\nimport { serializePrimitive } from \"./primitive.js\";\nimport { stringAndSymbolicEntriesOf } from \"./records.js\";\nimport { isDotAccessible, register } from \"./registry.js\";\nexport const snapshot = (data, opts = {}) => _serialize(data, {\n onUndefined: `$ark.undefined`,\n onBigInt: n => `$ark.bigint-${n}`,\n ...opts\n}, []);\nexport const print = (data, opts) => console.log(printable(data, opts));\nexport const printable = (data, opts) => {\n switch (domainOf(data)) {\n case \"object\":\n const o = data;\n const ctorName = o.constructor?.name ?? \"Object\";\n return (ctorName === \"Object\" || ctorName === \"Array\" ?\n opts?.quoteKeys === false ?\n stringifyUnquoted(o, opts?.indent ?? 0, \"\")\n : JSON.stringify(_serialize(o, printableOpts, []), null, opts?.indent)\n : stringifyUnquoted(o, opts?.indent ?? 0, \"\"));\n case \"symbol\":\n return printableOpts.onSymbol(data);\n default:\n return serializePrimitive(data);\n }\n};\nconst stringifyUnquoted = (value, indent, currentIndent) => {\n if (typeof value === \"function\")\n return printableOpts.onFunction(value);\n if (typeof value !== \"object\" || value === null)\n return serializePrimitive(value);\n const nextIndent = currentIndent + \" \".repeat(indent);\n if (Array.isArray(value)) {\n if (value.length === 0)\n return \"[]\";\n const items = value\n .map(item => stringifyUnquoted(item, indent, nextIndent))\n .join(\",\\n\" + nextIndent);\n return indent ? `[\\n${nextIndent}${items}\\n${currentIndent}]` : `[${items}]`;\n }\n const ctorName = value.constructor?.name ?? \"Object\";\n if (ctorName === \"Object\") {\n const keyValues = stringAndSymbolicEntriesOf(value).map(([key, val]) => {\n const stringifiedKey = typeof key === \"symbol\" ? printableOpts.onSymbol(key)\n : isDotAccessible(key) ? key\n : JSON.stringify(key);\n const stringifiedValue = stringifyUnquoted(val, indent, nextIndent);\n return `${nextIndent}${stringifiedKey}: ${stringifiedValue}`;\n });\n if (keyValues.length === 0)\n return \"{}\";\n return indent ?\n `{\\n${keyValues.join(\",\\n\")}\\n${currentIndent}}`\n : `{${keyValues.join(\", \")}}`;\n }\n if (value instanceof Date)\n return describeCollapsibleDate(value);\n if (\"expression\" in value && typeof value.expression === \"string\")\n return value.expression;\n return ctorName;\n};\nconst printableOpts = {\n onCycle: () => \"(cycle)\",\n onSymbol: v => `Symbol(${register(v)})`,\n onFunction: v => `Function(${register(v)})`\n};\nconst _serialize = (data, opts, seen) => {\n switch (domainOf(data)) {\n case \"object\": {\n const o = data;\n if (\"toJSON\" in o && typeof o.toJSON === \"function\")\n return o.toJSON();\n if (typeof o === \"function\")\n return printableOpts.onFunction(o);\n if (seen.includes(o))\n return \"(cycle)\";\n const nextSeen = [...seen, o];\n if (Array.isArray(o))\n return o.map(item => _serialize(item, opts, nextSeen));\n if (o instanceof Date)\n return o.toDateString();\n const result = {};\n for (const k in o)\n result[k] = _serialize(o[k], opts, nextSeen);\n for (const s of Object.getOwnPropertySymbols(o)) {\n result[opts.onSymbol?.(s) ?? s.toString()] = _serialize(o[s], opts, nextSeen);\n }\n return result;\n }\n case \"symbol\":\n return printableOpts.onSymbol(data);\n case \"bigint\":\n return opts.onBigInt?.(data) ?? `${data}n`;\n case \"undefined\":\n return opts.onUndefined ?? \"undefined\";\n case \"string\":\n return data.replace(/\\\\/g, \"\\\\\\\\\");\n default:\n return data;\n }\n};\n/**\n * Converts a Date instance to a human-readable description relative to its precision\n */\nexport const describeCollapsibleDate = (date) => {\n const year = date.getFullYear();\n const month = date.getMonth();\n const dayOfMonth = date.getDate();\n const hours = date.getHours();\n const minutes = date.getMinutes();\n const seconds = date.getSeconds();\n const milliseconds = date.getMilliseconds();\n if (month === 0 &&\n dayOfMonth === 1 &&\n hours === 0 &&\n minutes === 0 &&\n seconds === 0 &&\n milliseconds === 0)\n return `${year}`;\n const datePortion = `${months[month]} ${dayOfMonth}, ${year}`;\n if (hours === 0 && minutes === 0 && seconds === 0 && milliseconds === 0)\n return datePortion;\n let timePortion = date.toLocaleTimeString();\n const suffix = timePortion.endsWith(\" AM\") || timePortion.endsWith(\" PM\") ?\n timePortion.slice(-3)\n : \"\";\n if (suffix)\n timePortion = timePortion.slice(0, -suffix.length);\n if (milliseconds)\n timePortion += `.${pad(milliseconds, 3)}`;\n else if (timeWithUnnecessarySeconds.test(timePortion))\n timePortion = timePortion.slice(0, -3);\n return `${timePortion + suffix}, ${datePortion}`;\n};\nconst months = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\nconst timeWithUnnecessarySeconds = /:\\d\\d:00$/;\nconst pad = (value, length) => String(value).padStart(length, \"0\");\n",
|
|
32
|
+
"import { ReadonlyArray } from \"./arrays.js\";\nimport { throwParseError } from \"./errors.js\";\nimport { isDotAccessible } from \"./registry.js\";\nimport { printable } from \"./serialize.js\";\nexport const appendStringifiedKey = (path, prop, ...[opts]) => {\n const stringifySymbol = opts?.stringifySymbol ?? printable;\n let propAccessChain = path;\n switch (typeof prop) {\n case \"string\":\n propAccessChain =\n isDotAccessible(prop) ?\n path === \"\" ?\n prop\n : `${path}.${prop}`\n : `${path}[${JSON.stringify(prop)}]`;\n break;\n case \"number\":\n propAccessChain = `${path}[${prop}]`;\n break;\n case \"symbol\":\n propAccessChain = `${path}[${stringifySymbol(prop)}]`;\n break;\n default:\n if (opts?.stringifyNonKey)\n propAccessChain = `${path}[${opts.stringifyNonKey(prop)}]`;\n else {\n throwParseError(`${printable(prop)} must be a PropertyKey or stringifyNonKey must be passed to options`);\n }\n }\n return propAccessChain;\n};\nexport const stringifyPath = (path, ...opts) => path.reduce((s, k) => appendStringifiedKey(s, k, ...opts), \"\");\nexport class ReadonlyPath extends ReadonlyArray {\n // alternate strategy for caching since the base object is frozen\n cache = {};\n constructor(...items) {\n super();\n this.push(...items);\n }\n toJSON() {\n if (this.cache.json)\n return this.cache.json;\n this.cache.json = [];\n for (let i = 0; i < this.length; i++) {\n this.cache.json.push(typeof this[i] === \"symbol\" ? printable(this[i]) : this[i]);\n }\n return this.cache.json;\n }\n stringify() {\n if (this.cache.stringify)\n return this.cache.stringify;\n return (this.cache.stringify = stringifyPath(this));\n }\n stringifyAncestors() {\n if (this.cache.stringifyAncestors)\n return this.cache.stringifyAncestors;\n let propString = \"\";\n const result = [propString];\n for (const path of this) {\n propString = appendStringifiedKey(propString, path);\n result.push(propString);\n }\n return (this.cache.stringifyAncestors = result);\n }\n}\n",
|
|
33
|
+
"import { Backslash, whitespaceChars } from \"./strings.js\";\nexport class Scanner {\n chars;\n i;\n def;\n constructor(def) {\n this.def = def;\n this.chars = [...def];\n this.i = 0;\n }\n /** Get lookahead and advance scanner by one */\n shift() {\n return (this.chars[this.i++] ?? \"\");\n }\n get lookahead() {\n return (this.chars[this.i] ?? \"\");\n }\n get nextLookahead() {\n return this.chars[this.i + 1] ?? \"\";\n }\n get length() {\n return this.chars.length;\n }\n shiftUntil(condition) {\n let shifted = \"\";\n while (this.lookahead) {\n if (condition(this, shifted))\n break;\n else\n shifted += this.shift();\n }\n return shifted;\n }\n shiftUntilEscapable(condition) {\n let shifted = \"\";\n while (this.lookahead) {\n if (this.lookahead === Backslash) {\n this.shift();\n if (condition(this, shifted))\n shifted += this.shift();\n else if (this.lookahead === Backslash)\n shifted += this.shift();\n else\n shifted += `${Backslash}${this.shift()}`;\n }\n else if (condition(this, shifted))\n break;\n else\n shifted += this.shift();\n }\n return shifted;\n }\n shiftUntilLookahead(charOrSet) {\n return typeof charOrSet === \"string\" ?\n this.shiftUntil(s => s.lookahead === charOrSet)\n : this.shiftUntil(s => s.lookahead in charOrSet);\n }\n shiftUntilNonWhitespace() {\n return this.shiftUntil(() => !(this.lookahead in whitespaceChars));\n }\n jumpToIndex(i) {\n this.i = i < 0 ? this.length + i : i;\n }\n jumpForward(count) {\n this.i += count;\n }\n get location() {\n return this.i;\n }\n get unscanned() {\n return this.chars.slice(this.i, this.length).join(\"\");\n }\n get scanned() {\n return this.chars.slice(0, this.i).join(\"\");\n }\n sliceChars(start, end) {\n return this.chars.slice(start, end).join(\"\");\n }\n lookaheadIs(char) {\n return this.lookahead === char;\n }\n lookaheadIsIn(tokens) {\n return this.lookahead in tokens;\n }\n}\nexport const writeUnmatchedGroupCloseMessage = (char, unscanned) => `Unmatched ${char}${(unscanned === \"\" ? \"\" : ` before ${unscanned}`)}`;\nexport const writeUnclosedGroupMessage = (missingChar) => `Missing ${missingChar}`;\n",
|
|
34
|
+
"import { hasDomain } from \"./domain.js\";\nimport { noSuggest } from \"./errors.js\";\nimport { ancestorsOf } from \"./objectKinds.js\";\nimport { NoopBase } from \"./records.js\";\n// even though the value we attach will be identical, we use this so classes\n// won't be treated as instanceof a Trait\nconst implementedTraits = noSuggest(\"implementedTraits\");\nexport const hasTrait = (traitClass) => (o) => {\n if (!hasDomain(o, \"object\"))\n return false;\n if (implementedTraits in o.constructor &&\n o.constructor[implementedTraits].includes(traitClass))\n return true;\n // emulate standard instanceof behavior\n return ancestorsOf(o).includes(traitClass);\n};\n/** @ts-ignore required to extend NoopBase */\nexport class Trait extends NoopBase {\n static get [Symbol.hasInstance]() {\n return hasTrait(this);\n }\n traitsOf() {\n return implementedTraits in this.constructor ?\n this.constructor[implementedTraits]\n : [];\n }\n}\nconst collectPrototypeDescriptors = (trait) => {\n let proto = trait.prototype;\n let result = {};\n do {\n // ensure prototypes are sorted from lowest to highest precedence\n result = Object.assign(Object.getOwnPropertyDescriptors(proto), result);\n proto = Object.getPrototypeOf(proto);\n } while (proto !== Object.prototype && proto !== null);\n return result;\n};\nexport const compose = ((...traits) => {\n const base = function (...args) {\n for (const trait of traits) {\n const instance = Reflect.construct(trait, args, this.constructor);\n Object.assign(this, instance);\n }\n };\n const flatImplementedTraits = [];\n for (const trait of traits) {\n // copy static properties\n Object.assign(base, trait);\n // flatten and copy prototype\n Object.defineProperties(base.prototype, collectPrototypeDescriptors(trait));\n if (implementedTraits in trait) {\n // add any ancestor traits from which the current trait was composed\n for (const innerTrait of trait[implementedTraits]) {\n if (!flatImplementedTraits.includes(innerTrait))\n flatImplementedTraits.push(innerTrait);\n }\n }\n if (!flatImplementedTraits.includes(trait))\n flatImplementedTraits.push(trait);\n }\n Object.defineProperty(base, implementedTraits, {\n value: flatImplementedTraits,\n enumerable: false\n });\n return base;\n});\nexport const implement = (...args) => {\n if (args[args.length - 1] instanceof Trait)\n return compose(...args);\n const implementation = args[args.length - 1];\n const base = compose(...args.slice(0, -1));\n // copy implementation last since it overrides traits\n Object.defineProperties(base.prototype, Object.getOwnPropertyDescriptors(implementation));\n return base;\n};\n",
|
|
35
|
+
"import { register, registry } from \"@ark/util\";\nlet _registryName = \"$ark\";\nlet suffix = 2;\nwhile (_registryName in globalThis)\n _registryName = `$ark${suffix++}`;\nexport const registryName = _registryName;\nglobalThis[registryName] = registry;\nexport const $ark = registry;\nexport const reference = (name) => `${registryName}.${name}`;\nexport const registeredReference = (value) => reference(register(value));\n",
|
|
36
|
+
"import { CastableBase, DynamicFunction, hasDomain, isDotAccessible, serializePrimitive } from \"@ark/util\";\nimport { registeredReference } from \"./registry.js\";\nexport class CompiledFunction extends CastableBase {\n argNames;\n body = \"\";\n constructor(...args) {\n super();\n this.argNames = args;\n for (const arg of args) {\n if (arg in this) {\n throw new Error(`Arg name '${arg}' would overwrite an existing property on FunctionBody`);\n }\n ;\n this[arg] = arg;\n }\n }\n indentation = 0;\n indent() {\n this.indentation += 4;\n return this;\n }\n dedent() {\n this.indentation -= 4;\n return this;\n }\n prop(key, optional = false) {\n return compileLiteralPropAccess(key, optional);\n }\n index(key, optional = false) {\n return indexPropAccess(`${key}`, optional);\n }\n line(statement) {\n ;\n this.body += `${\" \".repeat(this.indentation)}${statement}\\n`;\n return this;\n }\n const(identifier, expression) {\n this.line(`const ${identifier} = ${expression}`);\n return this;\n }\n let(identifier, expression) {\n return this.line(`let ${identifier} = ${expression}`);\n }\n set(identifier, expression) {\n return this.line(`${identifier} = ${expression}`);\n }\n if(condition, then) {\n return this.block(`if (${condition})`, then);\n }\n elseIf(condition, then) {\n return this.block(`else if (${condition})`, then);\n }\n else(then) {\n return this.block(\"else\", then);\n }\n /** Current index is \"i\" */\n for(until, body, initialValue = 0) {\n return this.block(`for (let i = ${initialValue}; ${until}; i++)`, body);\n }\n /** Current key is \"k\" */\n forIn(object, body) {\n return this.block(`for (const k in ${object})`, body);\n }\n block(prefix, contents, suffix = \"\") {\n this.line(`${prefix} {`);\n this.indent();\n contents(this);\n this.dedent();\n return this.line(`}${suffix}`);\n }\n return(expression = \"\") {\n return this.line(`return ${expression}`);\n }\n write(name = \"anonymous\", indent = 0) {\n return `${name}(${this.argNames.join(\", \")}) { ${indent ?\n this.body\n .split(\"\\n\")\n .map(l => \" \".repeat(indent) + `${l}`)\n .join(\"\\n\")\n : this.body} }`;\n }\n compile() {\n return new DynamicFunction(...this.argNames, this.body);\n }\n}\nexport const compileSerializedValue = (value) => hasDomain(value, \"object\") || typeof value === \"symbol\" ?\n registeredReference(value)\n : serializePrimitive(value);\nexport const compileLiteralPropAccess = (key, optional = false) => {\n if (typeof key === \"string\" && isDotAccessible(key))\n return `${optional ? \"?\" : \"\"}.${key}`;\n return indexPropAccess(serializeLiteralKey(key), optional);\n};\nexport const serializeLiteralKey = (key) => typeof key === \"symbol\" ? registeredReference(key) : JSON.stringify(key);\nexport const indexPropAccess = (key, optional = false) => `${optional ? \"?.\" : \"\"}[${key}]`;\nexport class NodeCompiler extends CompiledFunction {\n traversalKind;\n optimistic;\n constructor(ctx) {\n super(\"data\", \"ctx\");\n this.traversalKind = ctx.kind;\n this.optimistic = ctx.optimistic === true;\n }\n invoke(node, opts) {\n const arg = opts?.arg ?? this.data;\n const requiresContext = typeof node === \"string\" ? true : this.requiresContextFor(node);\n const id = typeof node === \"string\" ? node : node.id;\n if (requiresContext)\n return `${this.referenceToId(id, opts)}(${arg}, ${this.ctx})`;\n return `${this.referenceToId(id, opts)}(${arg})`;\n }\n referenceToId(id, opts) {\n const invokedKind = opts?.kind ?? this.traversalKind;\n const base = `this.${id}${invokedKind}`;\n return opts?.bind ? `${base}.bind(${opts?.bind})` : base;\n }\n requiresContextFor(node) {\n return this.traversalKind === \"Apply\" || node.allowsRequiresContext;\n }\n initializeErrorCount() {\n return this.const(\"errorCount\", \"ctx.currentErrorCount\");\n }\n returnIfFail() {\n return this.if(\"ctx.currentErrorCount > errorCount\", () => this.return());\n }\n returnIfFailFast() {\n return this.if(\"ctx.failFast && ctx.currentErrorCount > errorCount\", () => this.return());\n }\n traverseKey(keyExpression, accessExpression, node) {\n const requiresContext = this.requiresContextFor(node);\n if (requiresContext)\n this.line(`${this.ctx}.path.push(${keyExpression})`);\n this.check(node, {\n arg: accessExpression\n });\n if (requiresContext)\n this.line(`${this.ctx}.path.pop()`);\n return this;\n }\n check(node, opts) {\n return this.traversalKind === \"Allows\" ?\n this.if(`!${this.invoke(node, opts)}`, () => this.return(false))\n : this.line(this.invoke(node, opts));\n }\n}\n",
|
|
37
|
+
"import { flatMorph, isArray, noSuggest } from \"@ark/util\";\nexport const makeRootAndArrayPropertiesMutable = (o) => \n// this cast should not be required, but it seems TS is referencing\n// the wrong parameters here?\nflatMorph(o, (k, v) => [k, isArray(v) ? [...v] : v]);\nexport const arkKind = noSuggest(\"arkKind\");\nexport const hasArkKind = (value, kind) => value?.[arkKind] === kind;\nexport const isNode = (value) => hasArkKind(value, \"root\") || hasArkKind(value, \"constraint\");\n",
|
|
38
|
+
"import { flatMorph, printable, throwParseError } from \"@ark/util\";\nimport { compileSerializedValue } from \"./compile.js\";\nimport { isNode } from \"./utils.js\";\nexport const basisKinds = [\"unit\", \"proto\", \"domain\"];\nexport const structuralKinds = [\n \"required\",\n \"optional\",\n \"index\",\n \"sequence\"\n];\nexport const prestructuralKinds = [\n \"pattern\",\n \"divisor\",\n \"exactLength\",\n \"max\",\n \"min\",\n \"maxLength\",\n \"minLength\",\n \"before\",\n \"after\"\n];\nexport const refinementKinds = [\n ...prestructuralKinds,\n \"structure\",\n \"predicate\"\n];\nexport const constraintKinds = [...refinementKinds, ...structuralKinds];\nexport const rootKinds = [\n \"alias\",\n \"union\",\n \"morph\",\n \"unit\",\n \"intersection\",\n \"proto\",\n \"domain\"\n];\nexport const nodeKinds = [...rootKinds, ...constraintKinds];\nexport const constraintKeys = flatMorph(constraintKinds, (i, kind) => [kind, 1]);\nexport const structureKeys = flatMorph([...structuralKinds, \"undeclared\"], (i, k) => [k, 1]);\nexport const precedenceByKind = flatMorph(nodeKinds, (i, kind) => [kind, i]);\nexport const isNodeKind = (value) => typeof value === \"string\" && value in precedenceByKind;\nexport function assertNodeKind(value, kind) {\n const valueIsNode = isNode(value);\n if (!valueIsNode || value.kind !== kind) {\n throwParseError(`Expected node of kind ${kind} (was ${valueIsNode ? `${value.kind} node` : printable(value)})`);\n }\n}\nexport const precedenceOfKind = (kind) => precedenceByKind[kind];\nexport const schemaKindsRightOf = (kind) => rootKinds.slice(precedenceOfKind(kind) + 1);\nexport const unionChildKinds = [\n ...schemaKindsRightOf(\"union\"),\n \"alias\"\n];\nexport const morphChildKinds = [\n ...schemaKindsRightOf(\"morph\"),\n \"alias\"\n];\nexport const defaultValueSerializer = (v) => {\n if (typeof v === \"string\" || typeof v === \"boolean\" || v === null)\n return v;\n if (typeof v === \"number\") {\n if (Number.isNaN(v))\n return \"NaN\";\n if (v === Number.POSITIVE_INFINITY)\n return \"Infinity\";\n if (v === Number.NEGATIVE_INFINITY)\n return \"-Infinity\";\n return v;\n }\n return compileSerializedValue(v);\n};\nexport const compileObjectLiteral = (ctx) => {\n let result = \"{ \";\n for (const [k, v] of Object.entries(ctx))\n result += `${k}: ${compileSerializedValue(v)}, `;\n return result + \" }\";\n};\nexport const implementNode = (_) => {\n const implementation = _;\n if (implementation.hasAssociatedError) {\n implementation.defaults.expected ??= ctx => \"description\" in ctx ?\n ctx.description\n : implementation.defaults.description(ctx);\n implementation.defaults.actual ??= data => printable(data);\n implementation.defaults.problem ??= ctx => `must be ${ctx.expected}${ctx.actual ? ` (was ${ctx.actual})` : \"\"}`;\n implementation.defaults.message ??= ctx => {\n if (ctx.path.length === 0)\n return ctx.problem;\n const problemWithLocation = `${ctx.propString} ${ctx.problem}`;\n if (problemWithLocation[0] === \"[\") {\n // clarify paths like [1], [0][1], and [\"key!\"] that could be confusing\n return `value at ${problemWithLocation}`;\n }\n return problemWithLocation;\n };\n }\n return implementation;\n};\n",
|
|
39
|
+
"import { printable, throwInternalError } from \"@ark/util\";\nclass ToJsonSchemaError extends Error {\n name = \"ToJsonSchemaError\";\n code;\n context;\n constructor(code, context) {\n super(printable(context, { quoteKeys: false, indent: 4 }));\n this.code = code;\n this.context = context;\n }\n hasCode(code) {\n return this.code === code;\n }\n}\nconst defaultConfig = {\n target: \"draft-2020-12\",\n dialect: \"https://json-schema.org/draft/2020-12/schema\",\n useRefs: false,\n fallback: {\n arrayObject: ctx => ToJsonSchema.throw(\"arrayObject\", ctx),\n arrayPostfix: ctx => ToJsonSchema.throw(\"arrayPostfix\", ctx),\n defaultValue: ctx => ToJsonSchema.throw(\"defaultValue\", ctx),\n domain: ctx => ToJsonSchema.throw(\"domain\", ctx),\n morph: ctx => ToJsonSchema.throw(\"morph\", ctx),\n patternIntersection: ctx => ToJsonSchema.throw(\"patternIntersection\", ctx),\n predicate: ctx => ToJsonSchema.throw(\"predicate\", ctx),\n proto: ctx => ToJsonSchema.throw(\"proto\", ctx),\n symbolKey: ctx => ToJsonSchema.throw(\"symbolKey\", ctx),\n unit: ctx => ToJsonSchema.throw(\"unit\", ctx),\n date: ctx => ToJsonSchema.throw(\"date\", ctx)\n }\n};\nexport const ToJsonSchema = {\n Error: ToJsonSchemaError,\n throw: (...args) => {\n throw new ToJsonSchema.Error(...args);\n },\n throwInternalOperandError: (kind, schema) => throwInternalError(`Unexpected JSON Schema input for ${kind}: ${printable(schema)}`),\n defaultConfig\n};\n",
|
|
40
|
+
"import { isNodeKind } from \"./shared/implement.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { ToJsonSchema } from \"./shared/toJsonSchema.js\";\n// $ark.config could already be set if it were imported previously from the\n// dedicated config entrypoint, in which case we don't want to reinitialize it\n$ark.config ??= {};\nexport const configureSchema = (config) => {\n const result = Object.assign($ark.config, mergeConfigs($ark.config, config));\n if ($ark.resolvedConfig)\n $ark.resolvedConfig = mergeConfigs($ark.resolvedConfig, result);\n return result;\n};\nexport const mergeConfigs = (base, merged) => {\n if (!merged)\n return base;\n const result = { ...base };\n let k;\n for (k in merged) {\n const keywords = { ...base.keywords };\n if (k === \"keywords\") {\n for (const flatAlias in merged[k]) {\n const v = merged.keywords[flatAlias];\n if (v === undefined)\n continue;\n keywords[flatAlias] = typeof v === \"string\" ? { description: v } : v;\n }\n result.keywords = keywords;\n }\n else if (k === \"toJsonSchema\") {\n result[k] = mergeToJsonSchemaConfigs(base.toJsonSchema, merged.toJsonSchema);\n }\n else if (isNodeKind(k)) {\n result[k] =\n // not casting this makes TS compute a very inefficient\n // type that is not needed\n {\n ...base[k],\n ...merged[k]\n };\n }\n else\n result[k] = merged[k];\n }\n return result;\n};\nconst jsonSchemaTargetToDialect = {\n \"draft-2020-12\": \"https://json-schema.org/draft/2020-12/schema\",\n \"draft-07\": \"http://json-schema.org/draft-07/schema#\"\n};\nexport const mergeToJsonSchemaConfigs = ((baseConfig, mergedConfig) => {\n if (!baseConfig)\n return resolveTargetToDialect(mergedConfig ?? {}, undefined);\n if (!mergedConfig)\n return baseConfig;\n const result = { ...baseConfig };\n let k;\n for (k in mergedConfig) {\n if (k === \"fallback\") {\n result.fallback = mergeFallbacks(baseConfig.fallback, mergedConfig.fallback);\n }\n else\n result[k] = mergedConfig[k];\n }\n return resolveTargetToDialect(result, mergedConfig);\n});\nconst resolveTargetToDialect = (opts, userOpts) => {\n // If user explicitly provided a dialect, use it\n // Otherwise, if user provided a target, resolve it to dialect\n // If neither, use the default dialect from opts\n if (userOpts?.dialect !== undefined)\n return opts; // dialect was already merged\n if (userOpts?.target !== undefined) {\n return {\n ...opts,\n dialect: jsonSchemaTargetToDialect[userOpts.target]\n };\n }\n return opts;\n};\nconst mergeFallbacks = (base, merged) => {\n base = normalizeFallback(base);\n merged = normalizeFallback(merged);\n const result = {};\n let code;\n for (code in ToJsonSchema.defaultConfig.fallback) {\n result[code] =\n merged[code] ??\n merged.default ??\n base[code] ??\n base.default ??\n ToJsonSchema.defaultConfig.fallback[code];\n }\n return result;\n};\nconst normalizeFallback = (fallback) => typeof fallback === \"function\" ? { default: fallback } : (fallback ?? {});\n",
|
|
41
|
+
"import { CastableBase, ReadonlyArray, ReadonlyPath, append, conflatenateAll, defineProperties, flatMorph, stringifyPath } from \"@ark/util\";\nimport { arkKind } from \"./utils.js\";\nexport class ArkError extends CastableBase {\n [arkKind] = \"error\";\n path;\n data;\n nodeConfig;\n input;\n ctx;\n // TS gets confused by <code>, so internally we just use the base type for input\n constructor({ prefixPath, relativePath, ...input }, ctx) {\n super();\n this.input = input;\n this.ctx = ctx;\n defineProperties(this, input);\n const data = ctx.data;\n if (input.code === \"union\") {\n input.errors = input.errors.flatMap(innerError => {\n // flatten union errors to avoid repeating context like \"foo must be foo must be\"...\n const flat = innerError.hasCode(\"union\") ? innerError.errors : [innerError];\n if (!prefixPath && !relativePath)\n return flat;\n return flat.map(e => e.transform(e => ({\n ...e,\n path: conflatenateAll(prefixPath, e.path, relativePath)\n })));\n });\n }\n this.nodeConfig = ctx.config[this.code];\n const basePath = [...(input.path ?? ctx.path)];\n if (relativePath)\n basePath.push(...relativePath);\n if (prefixPath)\n basePath.unshift(...prefixPath);\n this.path = new ReadonlyPath(...basePath);\n this.data = \"data\" in input ? input.data : data;\n }\n transform(f) {\n return new ArkError(f({\n data: this.data,\n path: this.path,\n ...this.input\n }), this.ctx);\n }\n hasCode(code) {\n return this.code === code;\n }\n get propString() {\n return stringifyPath(this.path);\n }\n get expected() {\n if (this.input.expected)\n return this.input.expected;\n const config = this.meta?.expected ?? this.nodeConfig.expected;\n return typeof config === \"function\" ? config(this.input) : config;\n }\n get actual() {\n if (this.input.actual)\n return this.input.actual;\n const config = this.meta?.actual ?? this.nodeConfig.actual;\n return typeof config === \"function\" ? config(this.data) : config;\n }\n get problem() {\n if (this.input.problem)\n return this.input.problem;\n const config = this.meta?.problem ?? this.nodeConfig.problem;\n return typeof config === \"function\" ? config(this) : config;\n }\n get message() {\n if (this.input.message)\n return this.input.message;\n const config = this.meta?.message ?? this.nodeConfig.message;\n return typeof config === \"function\" ? config(this) : config;\n }\n get flat() {\n return this.hasCode(\"intersection\") ? [...this.errors] : [this];\n }\n toJSON() {\n return {\n data: this.data,\n path: this.path,\n ...this.input,\n expected: this.expected,\n actual: this.actual,\n problem: this.problem,\n message: this.message\n };\n }\n toString() {\n return this.message;\n }\n throw() {\n throw this;\n }\n}\n/**\n * A ReadonlyArray of `ArkError`s returned by a Type on invalid input.\n *\n * Subsequent errors added at an existing path are merged into an\n * ArkError intersection.\n */\nexport class ArkErrors extends ReadonlyArray {\n [arkKind] = \"errors\";\n ctx;\n constructor(ctx) {\n super();\n this.ctx = ctx;\n }\n /**\n * Errors by a pathString representing their location.\n */\n byPath = Object.create(null);\n /**\n * {@link byPath} flattened so that each value is an array of ArkError instances at that path.\n *\n * ✅ Since \"intersection\" errors will be flattened to their constituent `.errors`,\n * they will never be directly present in this representation.\n */\n get flatByPath() {\n return flatMorph(this.byPath, (k, v) => [k, v.flat]);\n }\n /**\n * {@link byPath} flattened so that each value is an array of problem strings at that path.\n */\n get flatProblemsByPath() {\n return flatMorph(this.byPath, (k, v) => [k, v.flat.map(e => e.problem)]);\n }\n /**\n * All pathStrings at which errors are present mapped to the errors occuring\n * at that path or any nested path within it.\n */\n byAncestorPath = Object.create(null);\n count = 0;\n mutable = this;\n /**\n * Throw a TraversalError based on these errors.\n */\n throw() {\n throw this.toTraversalError();\n }\n /**\n * Converts ArkErrors to TraversalError, a subclass of `Error` suitable for throwing with nice\n * formatting.\n */\n toTraversalError() {\n return new TraversalError(this);\n }\n /**\n * Append an ArkError to this array, ignoring duplicates.\n */\n add(error) {\n const existing = this.byPath[error.propString];\n if (existing) {\n if (error === existing)\n return;\n // If the existing error is an error for a value constrained to \"never\",\n // then we don't want to intersect the error messages.\n if (existing.hasCode(\"union\") && existing.errors.length === 0)\n return;\n // If the new error is an error for a value constrained to \"never\",\n // then we want to override any existing errors.\n const errorIntersection = error.hasCode(\"union\") && error.errors.length === 0 ?\n error\n : new ArkError({\n code: \"intersection\",\n errors: existing.hasCode(\"intersection\") ?\n [...existing.errors, error]\n : [existing, error]\n }, this.ctx);\n const existingIndex = this.indexOf(existing);\n this.mutable[existingIndex === -1 ? this.length : existingIndex] =\n errorIntersection;\n this.byPath[error.propString] = errorIntersection;\n // add the original error here rather than the intersection\n // since the intersection is reflected by the array of errors at\n // this path\n this.addAncestorPaths(error);\n }\n else {\n this.byPath[error.propString] = error;\n this.addAncestorPaths(error);\n this.mutable.push(error);\n }\n this.count++;\n }\n transform(f) {\n const result = new ArkErrors(this.ctx);\n for (const e of this)\n result.add(f(e));\n return result;\n }\n /**\n * Add all errors from an ArkErrors instance, ignoring duplicates and\n * prefixing their paths with that of the current Traversal.\n */\n merge(errors) {\n for (const e of errors) {\n this.add(new ArkError({ ...e, path: [...this.ctx.path, ...e.path] }, this.ctx));\n }\n }\n /**\n * @internal\n */\n affectsPath(path) {\n if (this.length === 0)\n return false;\n return (\n // this would occur if there is an existing error at a prefix of path\n // e.g. the path is [\"foo\", \"bar\"] and there is an error at [\"foo\"]\n path.stringifyAncestors().some(s => s in this.byPath) ||\n // this would occur if there is an existing error at a suffix of path\n // e.g. the path is [\"foo\"] and there is an error at [\"foo\", \"bar\"]\n path.stringify() in this.byAncestorPath);\n }\n /**\n * A human-readable summary of all errors.\n */\n get summary() {\n return this.toString();\n }\n /**\n * Alias of this ArkErrors instance for StandardSchema compatibility.\n */\n get issues() {\n return this;\n }\n toJSON() {\n return [...this.map(e => e.toJSON())];\n }\n toString() {\n return this.join(\"\\n\");\n }\n addAncestorPaths(error) {\n for (const propString of error.path.stringifyAncestors()) {\n this.byAncestorPath[propString] = append(this.byAncestorPath[propString], error);\n }\n }\n}\nexport class TraversalError extends Error {\n name = \"TraversalError\";\n constructor(errors) {\n if (errors.length === 1)\n super(errors.summary);\n else\n super(\"\\n\" + errors.map(error => ` • ${indent(error)}`).join(\"\\n\"));\n Object.defineProperty(this, \"arkErrors\", {\n value: errors,\n enumerable: false\n });\n }\n}\nconst indent = (error) => error.toString().split(\"\\n\").join(\"\\n \");\n",
|
|
42
|
+
"import { ReadonlyPath, stringifyPath } from \"@ark/util\";\nimport { ArkError, ArkErrors } from \"./errors.js\";\nimport { isNode } from \"./utils.js\";\nexport class Traversal {\n /**\n * #### the path being validated or morphed\n *\n * ✅ array indices represented as numbers\n * ⚠️ mutated during traversal - use `path.slice(0)` to snapshot\n * 🔗 use {@link propString} for a stringified version\n */\n path = [];\n /**\n * #### {@link ArkErrors} that will be part of this traversal's finalized result\n *\n * ✅ will always be an empty array for a valid traversal\n */\n errors = new ArkErrors(this);\n /**\n * #### the original value being traversed\n */\n root;\n /**\n * #### configuration for this traversal\n *\n * ✅ options can affect traversal results and error messages\n * ✅ defaults < global config < scope config\n * ✅ does not include options configured on individual types\n */\n config;\n queuedMorphs = [];\n branches = [];\n seen = {};\n constructor(root, config) {\n this.root = root;\n this.config = config;\n }\n /**\n * #### the data being validated or morphed\n *\n * ✅ extracted from {@link root} at {@link path}\n */\n get data() {\n let result = this.root;\n for (const segment of this.path)\n result = result?.[segment];\n return result;\n }\n /**\n * #### a string representing {@link path}\n *\n * @propString\n */\n get propString() {\n return stringifyPath(this.path);\n }\n /**\n * #### add an {@link ArkError} and return `false`\n *\n * ✅ useful for predicates like `.narrow`\n */\n reject(input) {\n this.error(input);\n return false;\n }\n /**\n * #### add an {@link ArkError} from a description and return `false`\n *\n * ✅ useful for predicates like `.narrow`\n * 🔗 equivalent to {@link reject}({ expected })\n */\n mustBe(expected) {\n this.error(expected);\n return false;\n }\n error(input) {\n const errCtx = typeof input === \"object\" ?\n input.code ?\n input\n : { ...input, code: \"predicate\" }\n : { code: \"predicate\", expected: input };\n return this.errorFromContext(errCtx);\n }\n /**\n * #### whether {@link currentBranch} (or the traversal root, outside a union) has one or more errors\n */\n hasError() {\n return this.currentErrorCount !== 0;\n }\n get currentBranch() {\n return this.branches[this.branches.length - 1];\n }\n queueMorphs(morphs) {\n const input = {\n path: new ReadonlyPath(...this.path),\n morphs\n };\n if (this.currentBranch)\n this.currentBranch.queuedMorphs.push(input);\n else\n this.queuedMorphs.push(input);\n }\n finalize(onFail) {\n if (this.queuedMorphs.length) {\n if (typeof this.root === \"object\" &&\n this.root !== null &&\n this.config.clone)\n this.root = this.config.clone(this.root);\n this.applyQueuedMorphs();\n }\n if (this.hasError())\n return onFail ? onFail(this.errors) : this.errors;\n return this.root;\n }\n get currentErrorCount() {\n return (this.currentBranch ?\n this.currentBranch.error ?\n 1\n : 0\n : this.errors.count);\n }\n get failFast() {\n return this.branches.length !== 0;\n }\n pushBranch() {\n this.branches.push({\n error: undefined,\n queuedMorphs: []\n });\n }\n popBranch() {\n return this.branches.pop();\n }\n /**\n * @internal\n * Convenience for casting from InternalTraversal to Traversal\n * for cases where the extra methods on the external type are expected, e.g.\n * a morph or predicate.\n */\n get external() {\n return this;\n }\n errorFromNodeContext(input) {\n return this.errorFromContext(input);\n }\n errorFromContext(errCtx) {\n const error = new ArkError(errCtx, this);\n if (this.currentBranch)\n this.currentBranch.error = error;\n else\n this.errors.add(error);\n return error;\n }\n applyQueuedMorphs() {\n // invoking morphs that are Nodes will reuse this context, potentially\n // adding additional morphs, so we have to continue looping until\n // queuedMorphs is empty rather than iterating over the list once\n while (this.queuedMorphs.length) {\n const queuedMorphs = this.queuedMorphs;\n this.queuedMorphs = [];\n for (const { path, morphs } of queuedMorphs) {\n // even if we already have an error, apply morphs that are not at a path\n // with errors to capture potential validation errors\n if (this.errors.affectsPath(path))\n continue;\n this.applyMorphsAtPath(path, morphs);\n }\n }\n }\n applyMorphsAtPath(path, morphs) {\n const key = path[path.length - 1];\n let parent;\n if (key !== undefined) {\n // find the object on which the key to be morphed exists\n parent = this.root;\n for (let pathIndex = 0; pathIndex < path.length - 1; pathIndex++)\n parent = parent[path[pathIndex]];\n }\n for (const morph of morphs) {\n // ensure morphs are applied relative to the correct path\n // in case previous operations modified this.path\n this.path = [...path];\n const morphIsNode = isNode(morph);\n const result = morph((parent === undefined ? this.root : parent[key]), this);\n if (result instanceof ArkError) {\n // if an ArkError was returned, ensure it has been added to errors\n // (it may have already been added via ctx.error() within the morph)\n // Only add if it's not already in the errors collection\n if (!this.errors.includes(result))\n this.errors.add(result);\n // skip any remaining morphs at the current path\n break;\n }\n if (result instanceof ArkErrors) {\n // if the morph was a direct reference to another node,\n // errors will have been added directly via this piped context\n if (!morphIsNode) {\n // otherwise, we have to ensure each error has been added\n this.errors.merge(result);\n }\n // skip any remaining morphs at the current path\n this.queuedMorphs = [];\n break;\n }\n // if the morph was successful, assign the result to the\n // corresponding property, or to root if path is empty\n if (parent === undefined)\n this.root = result;\n else\n parent[key] = result;\n // if the current morph queued additional morphs,\n // applying them before subsequent morphs\n this.applyQueuedMorphs();\n }\n }\n}\nexport const traverseKey = (key, fn, \n// ctx will be undefined if this node isn't context-dependent\nctx) => {\n if (!ctx)\n return fn();\n ctx.path.push(key);\n const result = fn();\n ctx.path.pop();\n return result;\n};\n",
|
|
43
|
+
"import { Callable, appendUnique, flatMorph, includes, isArray, isEmptyObject, isKeyOf, liftArray, printable, stringifyPath, throwError, throwInternalError } from \"@ark/util\";\nimport { basisKinds, constraintKinds, precedenceOfKind, refinementKinds, rootKinds, structuralKinds } from \"./shared/implement.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { Traversal } from \"./shared/traversal.js\";\nimport { isNode } from \"./shared/utils.js\";\nexport class BaseNode extends Callable {\n attachments;\n $;\n onFail;\n includesTransform;\n includesContextualPredicate;\n isCyclic;\n allowsRequiresContext;\n rootApplyStrategy;\n contextFreeMorph;\n rootApply;\n referencesById;\n shallowReferences;\n flatRefs;\n flatMorphs;\n allows;\n get shallowMorphs() {\n return [];\n }\n constructor(attachments, $) {\n super((data, pipedFromCtx, onFail = this.onFail) => {\n if (pipedFromCtx) {\n this.traverseApply(data, pipedFromCtx);\n return pipedFromCtx.hasError() ?\n pipedFromCtx.errors\n : pipedFromCtx.data;\n }\n return this.rootApply(data, onFail);\n }, { attach: attachments });\n this.attachments = attachments;\n this.$ = $;\n this.onFail = this.meta.onFail ?? this.$.resolvedConfig.onFail;\n this.includesTransform =\n this.hasKind(\"morph\") ||\n (this.hasKind(\"structure\") && this.structuralMorph !== undefined) ||\n (this.hasKind(\"sequence\") && this.inner.defaultables !== undefined);\n // if a predicate accepts exactly one arg, we can safely skip passing context\n // technically, a predicate could be written like `(data, ...[ctx]) => ctx.mustBe(\"malicious\")`\n // that would break here, but it feels like a pathological case and is better to let people optimize\n this.includesContextualPredicate =\n this.hasKind(\"predicate\") && this.inner.predicate.length !== 1;\n this.isCyclic = this.kind === \"alias\";\n this.referencesById = { [this.id]: this };\n this.shallowReferences =\n this.hasKind(\"structure\") ?\n [this, ...this.children]\n : this.children.reduce((acc, child) => appendUniqueNodes(acc, child.shallowReferences), [this]);\n const isStructural = this.isStructural();\n this.flatRefs = [];\n this.flatMorphs = [];\n for (let i = 0; i < this.children.length; i++) {\n this.includesTransform ||= this.children[i].includesTransform;\n this.includesContextualPredicate ||=\n this.children[i].includesContextualPredicate;\n this.isCyclic ||= this.children[i].isCyclic;\n if (!isStructural) {\n const childFlatRefs = this.children[i].flatRefs;\n for (let j = 0; j < childFlatRefs.length; j++) {\n const childRef = childFlatRefs[j];\n if (!this.flatRefs.some(existing => flatRefsAreEqual(existing, childRef))) {\n this.flatRefs.push(childRef);\n for (const branch of childRef.node.branches) {\n if (branch.hasKind(\"morph\") ||\n (branch.hasKind(\"intersection\") &&\n branch.structure?.structuralMorph !== undefined)) {\n this.flatMorphs.push({\n path: childRef.path,\n propString: childRef.propString,\n node: branch\n });\n }\n }\n }\n }\n }\n Object.assign(this.referencesById, this.children[i].referencesById);\n }\n this.flatRefs.sort((l, r) => l.path.length > r.path.length ? 1\n : l.path.length < r.path.length ? -1\n : l.propString > r.propString ? 1\n : l.propString < r.propString ? -1\n : l.node.expression < r.node.expression ? -1\n : 1);\n this.allowsRequiresContext =\n this.includesContextualPredicate || this.isCyclic;\n this.rootApplyStrategy =\n !this.allowsRequiresContext && this.flatMorphs.length === 0 ?\n this.shallowMorphs.length === 0 ? \"allows\"\n : (this.shallowMorphs.every(morph => morph.length === 1 || morph.name === \"$arkStructuralMorph\")) ?\n this.hasKind(\"union\") ?\n // multiple morphs not yet supported for optimistic compilation\n this.branches.some(branch => branch.shallowMorphs.length > 1) ?\n \"contextual\"\n : \"branchedOptimistic\"\n : this.shallowMorphs.length > 1 ? \"contextual\"\n : \"optimistic\"\n : \"contextual\"\n : \"contextual\";\n this.rootApply = this.createRootApply();\n this.allows =\n this.allowsRequiresContext ?\n data => this.traverseAllows(data, new Traversal(data, this.$.resolvedConfig))\n : data => this.traverseAllows(data);\n }\n createRootApply() {\n switch (this.rootApplyStrategy) {\n case \"allows\":\n return (data, onFail) => {\n if (this.allows(data))\n return data;\n const ctx = new Traversal(data, this.$.resolvedConfig);\n this.traverseApply(data, ctx);\n return ctx.finalize(onFail);\n };\n case \"contextual\":\n return (data, onFail) => {\n const ctx = new Traversal(data, this.$.resolvedConfig);\n this.traverseApply(data, ctx);\n return ctx.finalize(onFail);\n };\n case \"optimistic\":\n this.contextFreeMorph = this.shallowMorphs[0];\n const clone = this.$.resolvedConfig.clone;\n return (data, onFail) => {\n if (this.allows(data)) {\n return this.contextFreeMorph((clone &&\n ((typeof data === \"object\" && data !== null) ||\n typeof data === \"function\")) ?\n clone(data)\n : data);\n }\n const ctx = new Traversal(data, this.$.resolvedConfig);\n this.traverseApply(data, ctx);\n return ctx.finalize(onFail);\n };\n case \"branchedOptimistic\":\n return this.createBranchedOptimisticRootApply();\n default:\n this.rootApplyStrategy;\n return throwInternalError(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`);\n }\n }\n compiledMeta = compileMeta(this.metaJson);\n cacheGetter(name, value) {\n Object.defineProperty(this, name, { value });\n return value;\n }\n get description() {\n return this.cacheGetter(\"description\", this.meta?.description ??\n this.$.resolvedConfig[this.kind].description(this));\n }\n // we don't cache this currently since it can be updated once a scope finishes\n // resolving cyclic references, although it may be possible to ensure it is cached safely\n get references() {\n return Object.values(this.referencesById);\n }\n precedence = precedenceOfKind(this.kind);\n precompilation;\n // defined as an arrow function since it is often detached, e.g. when passing to tRPC\n // otherwise, would run into issues with this binding\n assert = (data, pipedFromCtx) => this(data, pipedFromCtx, errors => errors.throw());\n traverse(data, pipedFromCtx) {\n return this(data, pipedFromCtx, null);\n }\n /** rawIn should be used internally instead */\n get in() {\n // ensure the node has been finalized if in is being used externally\n return this.cacheGetter(\"in\", this.rawIn.isRoot() ? this.$.finalize(this.rawIn) : this.rawIn);\n }\n get rawIn() {\n return this.cacheGetter(\"rawIn\", this.getIo(\"in\"));\n }\n /** rawOut should be used internally instead */\n get out() {\n // ensure the node has been finalized if out is being used externally\n return this.cacheGetter(\"out\", this.rawOut.isRoot() ? this.$.finalize(this.rawOut) : this.rawOut);\n }\n get rawOut() {\n return this.cacheGetter(\"rawOut\", this.getIo(\"out\"));\n }\n // Should be refactored to use transform\n // https://github.com/arktypeio/arktype/issues/1020\n getIo(ioKind) {\n if (!this.includesTransform)\n return this;\n const ioInner = {};\n for (const [k, v] of this.innerEntries) {\n const keySchemaImplementation = this.impl.keys[k];\n if (keySchemaImplementation.reduceIo)\n keySchemaImplementation.reduceIo(ioKind, ioInner, v);\n else if (keySchemaImplementation.child) {\n const childValue = v;\n ioInner[k] =\n isArray(childValue) ?\n childValue.map(child => ioKind === \"in\" ? child.rawIn : child.rawOut)\n : ioKind === \"in\" ? childValue.rawIn\n : childValue.rawOut;\n }\n else\n ioInner[k] = v;\n }\n return this.$.node(this.kind, ioInner);\n }\n toJSON() {\n return this.json;\n }\n toString() {\n return `Type<${this.expression}>`;\n }\n equals(r) {\n const rNode = isNode(r) ? r : this.$.parseDefinition(r);\n return this.innerHash === rNode.innerHash;\n }\n ifEquals(r) {\n return this.equals(r) ? this : undefined;\n }\n hasKind(kind) {\n return this.kind === kind;\n }\n assertHasKind(kind) {\n if (this.kind !== kind)\n throwError(`${this.kind} node was not of asserted kind ${kind}`);\n return this;\n }\n hasKindIn(...kinds) {\n return kinds.includes(this.kind);\n }\n assertHasKindIn(...kinds) {\n if (!includes(kinds, this.kind))\n throwError(`${this.kind} node was not one of asserted kinds ${kinds}`);\n return this;\n }\n isBasis() {\n return includes(basisKinds, this.kind);\n }\n isConstraint() {\n return includes(constraintKinds, this.kind);\n }\n isStructural() {\n return includes(structuralKinds, this.kind);\n }\n isRefinement() {\n return includes(refinementKinds, this.kind);\n }\n isRoot() {\n return includes(rootKinds, this.kind);\n }\n isUnknown() {\n return this.hasKind(\"intersection\") && this.children.length === 0;\n }\n isNever() {\n return this.hasKind(\"union\") && this.children.length === 0;\n }\n hasUnit(value) {\n return this.hasKind(\"unit\") && this.allows(value);\n }\n hasOpenIntersection() {\n return this.impl.intersectionIsOpen;\n }\n get nestableExpression() {\n return this.expression;\n }\n select(selector) {\n const normalized = NodeSelector.normalize(selector);\n return this._select(normalized);\n }\n _select(selector) {\n let nodes = NodeSelector.applyBoundary[selector.boundary ?? \"references\"](this);\n if (selector.kind)\n nodes = nodes.filter(n => n.kind === selector.kind);\n if (selector.where)\n nodes = nodes.filter(selector.where);\n return NodeSelector.applyMethod[selector.method ?? \"filter\"](nodes, this, selector);\n }\n transform(mapper, opts) {\n return this._transform(mapper, this._createTransformContext(opts));\n }\n _createTransformContext(opts) {\n return {\n root: this,\n selected: undefined,\n seen: {},\n path: [],\n parseOptions: {\n prereduced: opts?.prereduced ?? false\n },\n undeclaredKeyHandling: undefined,\n ...opts\n };\n }\n _transform(mapper, ctx) {\n const $ = ctx.bindScope ?? this.$;\n if (ctx.seen[this.id])\n // Cyclic handling needs to be made more robust\n // https://github.com/arktypeio/arktype/issues/944\n return this.$.lazilyResolve(ctx.seen[this.id]);\n if (ctx.shouldTransform?.(this, ctx) === false)\n return this;\n let transformedNode;\n ctx.seen[this.id] = () => transformedNode;\n if (this.hasKind(\"structure\") &&\n this.undeclared !== ctx.undeclaredKeyHandling) {\n ctx = {\n ...ctx,\n undeclaredKeyHandling: this.undeclared\n };\n }\n const innerWithTransformedChildren = flatMorph(this.inner, (k, v) => {\n if (!this.impl.keys[k].child)\n return [k, v];\n const children = v;\n if (!isArray(children)) {\n const transformed = children._transform(mapper, ctx);\n return transformed ? [k, transformed] : [];\n }\n // if the value was previously explicitly set to an empty list,\n // (e.g. branches for `never`), ensure it is not pruned\n if (children.length === 0)\n return [k, v];\n const transformed = children.flatMap(n => {\n const transformedChild = n._transform(mapper, ctx);\n return transformedChild ?? [];\n });\n return transformed.length ? [k, transformed] : [];\n });\n delete ctx.seen[this.id];\n const innerWithMeta = Object.assign(innerWithTransformedChildren, {\n meta: this.meta\n });\n const transformedInner = ctx.selected && !ctx.selected.includes(this) ?\n innerWithMeta\n : mapper(this.kind, innerWithMeta, ctx);\n if (transformedInner === null)\n return null;\n if (isNode(transformedInner))\n return (transformedNode = transformedInner);\n const transformedKeys = Object.keys(transformedInner);\n const hasNoTypedKeys = transformedKeys.length === 0 ||\n (transformedKeys.length === 1 && transformedKeys[0] === \"meta\");\n if (hasNoTypedKeys &&\n // if inner was previously an empty object (e.g. unknown) ensure it is not pruned\n !isEmptyObject(this.inner))\n return null;\n if ((this.kind === \"required\" ||\n this.kind === \"optional\" ||\n this.kind === \"index\") &&\n !(\"value\" in transformedInner)) {\n return ctx.undeclaredKeyHandling ?\n { ...transformedInner, value: $ark.intrinsic.unknown }\n : null;\n }\n if (this.kind === \"morph\") {\n ;\n transformedInner.in ??= $ark.intrinsic\n .unknown;\n }\n return (transformedNode = $.node(this.kind, transformedInner, ctx.parseOptions));\n }\n configureReferences(meta, selector = \"references\") {\n const normalized = NodeSelector.normalize(selector);\n const mapper = (typeof meta === \"string\" ?\n (kind, inner) => ({\n ...inner,\n meta: { ...inner.meta, description: meta }\n })\n : typeof meta === \"function\" ?\n (kind, inner) => ({ ...inner, meta: meta(inner.meta) })\n : (kind, inner) => ({\n ...inner,\n meta: { ...inner.meta, ...meta }\n }));\n if (normalized.boundary === \"self\") {\n return this.$.node(this.kind, mapper(this.kind, { ...this.inner, meta: this.meta }));\n }\n const rawSelected = this._select(normalized);\n const selected = rawSelected && liftArray(rawSelected);\n const shouldTransform = normalized.boundary === \"child\" ?\n (node, ctx) => ctx.root.children.includes(node)\n : normalized.boundary === \"shallow\" ? node => node.kind !== \"structure\"\n : () => true;\n return this.$.finalize(this.transform(mapper, {\n shouldTransform,\n selected\n }));\n }\n}\nconst NodeSelector = {\n applyBoundary: {\n self: node => [node],\n child: node => [...node.children],\n shallow: node => [...node.shallowReferences],\n references: node => [...node.references]\n },\n applyMethod: {\n filter: nodes => nodes,\n assertFilter: (nodes, from, selector) => {\n if (nodes.length === 0)\n throwError(writeSelectAssertionMessage(from, selector));\n return nodes;\n },\n find: nodes => nodes[0],\n assertFind: (nodes, from, selector) => {\n if (nodes.length === 0)\n throwError(writeSelectAssertionMessage(from, selector));\n return nodes[0];\n }\n },\n normalize: (selector) => typeof selector === \"function\" ?\n { boundary: \"references\", method: \"filter\", where: selector }\n : typeof selector === \"string\" ?\n isKeyOf(selector, NodeSelector.applyBoundary) ?\n { method: \"filter\", boundary: selector }\n : { boundary: \"references\", method: \"filter\", kind: selector }\n : { boundary: \"references\", method: \"filter\", ...selector }\n};\nconst writeSelectAssertionMessage = (from, selector) => `${from} had no references matching ${printable(selector)}.`;\nexport const typePathToPropString = (path) => stringifyPath(path, {\n stringifyNonKey: node => node.expression\n});\nconst referenceMatcher = /\"(\\$ark\\.[^\"]+)\"/g;\nconst compileMeta = (metaJson) => JSON.stringify(metaJson).replace(referenceMatcher, \"$1\");\nexport const flatRef = (path, node) => ({\n path,\n node,\n propString: typePathToPropString(path)\n});\nexport const flatRefsAreEqual = (l, r) => l.propString === r.propString && l.node.equals(r.node);\nexport const appendUniqueFlatRefs = (existing, refs) => appendUnique(existing, refs, {\n isEqual: flatRefsAreEqual\n});\nexport const appendUniqueNodes = (existing, refs) => appendUnique(existing, refs, {\n isEqual: (l, r) => l.equals(r)\n});\n",
|
|
44
|
+
"import { isArray, stringifyPath, throwParseError } from \"@ark/util\";\nimport { $ark } from \"./registry.js\";\nimport { isNode } from \"./utils.js\";\nexport class Disjoint extends Array {\n static init(kind, l, r, ctx) {\n return new Disjoint({\n kind,\n l,\n r,\n path: ctx?.path ?? [],\n optional: ctx?.optional ?? false\n });\n }\n add(kind, l, r, ctx) {\n this.push({\n kind,\n l,\n r,\n path: ctx?.path ?? [],\n optional: ctx?.optional ?? false\n });\n return this;\n }\n get summary() {\n return this.describeReasons();\n }\n describeReasons() {\n if (this.length === 1) {\n const { path, l, r } = this[0];\n const pathString = stringifyPath(path);\n return writeUnsatisfiableExpressionError(`Intersection${pathString && ` at ${pathString}`} of ${describeReasons(l, r)}`);\n }\n return `The following intersections result in unsatisfiable types:\\n• ${this.map(({ path, l, r }) => `${path}: ${describeReasons(l, r)}`).join(\"\\n• \")}`;\n }\n throw() {\n return throwParseError(this.describeReasons());\n }\n invert() {\n const result = this.map(entry => ({\n ...entry,\n l: entry.r,\n r: entry.l\n }));\n // Workaround for Static Hermes, which doesn't preserve the Array subclass here\n // https://github.com/arktypeio/arktype/issues/1027\n if (!(result instanceof Disjoint))\n return new Disjoint(...result);\n return result;\n }\n withPrefixKey(key, kind) {\n return this.map(entry => ({\n ...entry,\n path: [key, ...entry.path],\n optional: entry.optional || kind === \"optional\"\n }));\n }\n toNeverIfDisjoint() {\n return $ark.intrinsic.never;\n }\n}\nconst describeReasons = (l, r) => `${describeReason(l)} and ${describeReason(r)}`;\nconst describeReason = (value) => isNode(value) ? value.expression\n : isArray(value) ? value.map(describeReason).join(\" | \") || \"never\"\n : String(value);\nexport const writeUnsatisfiableExpressionError = (expression) => `${expression} results in an unsatisfiable type`;\n",
|
|
45
|
+
"import { Disjoint } from \"./disjoint.js\";\nimport { rootKinds } from \"./implement.js\";\nimport { isNode } from \"./utils.js\";\nconst intersectionCache = {};\nexport const intersectNodesRoot = (l, r, $) => intersectOrPipeNodes(l, r, {\n $,\n invert: false,\n pipe: false\n});\nexport const pipeNodesRoot = (l, r, $) => intersectOrPipeNodes(l, r, {\n $,\n invert: false,\n pipe: true\n});\nexport const intersectOrPipeNodes = ((l, r, ctx) => {\n const operator = ctx.pipe ? \"|>\" : \"&\";\n const lrCacheKey = `${l.hash}${operator}${r.hash}`;\n if (intersectionCache[lrCacheKey] !== undefined)\n return intersectionCache[lrCacheKey];\n if (!ctx.pipe) {\n // we can only use this for the commutative & operator\n const rlCacheKey = `${r.hash}${operator}${l.hash}`;\n if (intersectionCache[rlCacheKey] !== undefined) {\n // if the cached result was a Disjoint and the operands originally\n // appeared in the opposite order, we need to invert it to match\n const rlResult = intersectionCache[rlCacheKey];\n const lrResult = rlResult instanceof Disjoint ? rlResult.invert() : rlResult;\n // add the lr result to the cache directly to bypass this check in the future\n intersectionCache[lrCacheKey] = lrResult;\n return lrResult;\n }\n }\n const isPureIntersection = !ctx.pipe || (!l.includesTransform && !r.includesTransform);\n if (isPureIntersection && l.equals(r))\n return l;\n let result = isPureIntersection ? _intersectNodes(l, r, ctx)\n : l.hasKindIn(...rootKinds) ?\n // if l is a RootNode, r will be as well\n _pipeNodes(l, r, ctx)\n : _intersectNodes(l, r, ctx);\n if (isNode(result)) {\n // if the result equals one of the operands, preserve its metadata by\n // returning the original reference\n if (l.equals(result))\n result = l;\n else if (r.equals(result))\n result = r;\n }\n intersectionCache[lrCacheKey] = result;\n return result;\n});\nconst _intersectNodes = (l, r, ctx) => {\n const leftmostKind = l.precedence < r.precedence ? l.kind : r.kind;\n const implementation = l.impl.intersections[r.kind] ?? r.impl.intersections[l.kind];\n if (implementation === undefined) {\n // should be two ConstraintNodes that have no relation\n // this could also happen if a user directly intersects a Type and a ConstraintNode,\n // but that is not allowed by the external function signature\n return null;\n }\n else if (leftmostKind === l.kind)\n return implementation(l, r, ctx);\n else {\n let result = implementation(r, l, { ...ctx, invert: !ctx.invert });\n if (result instanceof Disjoint)\n result = result.invert();\n return result;\n }\n};\nconst _pipeNodes = (l, r, ctx) => l.includesTransform || r.includesTransform ?\n ctx.invert ?\n pipeMorphed(r, l, ctx)\n : pipeMorphed(l, r, ctx)\n : _intersectNodes(l, r, ctx);\nconst pipeMorphed = (from, to, ctx) => from.distribute(fromBranch => _pipeMorphed(fromBranch, to, ctx), results => {\n const viableBranches = results.filter(isNode);\n if (viableBranches.length === 0)\n return Disjoint.init(\"union\", from.branches, to.branches);\n // if the input type has changed, create a new node without preserving metadata\n if (viableBranches.length < from.branches.length ||\n !from.branches.every((branch, i) => branch.rawIn.equals(viableBranches[i].rawIn)))\n return ctx.$.parseSchema(viableBranches);\n // otherwise, the input has not changed so preserve metadata\n let meta;\n if (viableBranches.length === 1) {\n const onlyBranch = viableBranches[0];\n if (!meta)\n return onlyBranch;\n return ctx.$.node(\"morph\", {\n ...onlyBranch.inner,\n in: onlyBranch.rawIn.configure(meta, \"self\")\n });\n }\n const schema = {\n branches: viableBranches\n };\n if (meta)\n schema.meta = meta;\n return ctx.$.parseSchema(schema);\n});\nconst _pipeMorphed = (from, to, ctx) => {\n const fromIsMorph = from.hasKind(\"morph\");\n if (fromIsMorph) {\n const morphs = [...from.morphs];\n if (from.lastMorphIfNode) {\n // still piped from context, so allows appending additional morphs\n const outIntersection = intersectOrPipeNodes(from.lastMorphIfNode, to, ctx);\n if (outIntersection instanceof Disjoint)\n return outIntersection;\n morphs[morphs.length - 1] = outIntersection;\n }\n else\n morphs.push(to);\n return ctx.$.node(\"morph\", {\n morphs,\n in: from.inner.in\n });\n }\n if (to.hasKind(\"morph\")) {\n const inTersection = intersectOrPipeNodes(from, to.rawIn, ctx);\n if (inTersection instanceof Disjoint)\n return inTersection;\n return ctx.$.node(\"morph\", {\n morphs: [to],\n in: inTersection\n });\n }\n return ctx.$.node(\"morph\", {\n morphs: [to],\n in: from\n });\n};\n",
|
|
46
|
+
"import { append, appendUnique, capitalize, isArray, throwInternalError, throwParseError } from \"@ark/util\";\nimport { BaseNode } from \"./node.js\";\nimport { Disjoint } from \"./shared/disjoint.js\";\nimport { compileObjectLiteral, constraintKeys } from \"./shared/implement.js\";\nimport { intersectNodesRoot, intersectOrPipeNodes } from \"./shared/intersections.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { arkKind } from \"./shared/utils.js\";\nexport class BaseConstraint extends BaseNode {\n constructor(attachments, $) {\n super(attachments, $);\n // define as a getter to avoid it being enumerable/spreadable\n Object.defineProperty(this, arkKind, {\n value: \"constraint\",\n enumerable: false\n });\n }\n impliedSiblings;\n intersect(r) {\n return intersectNodesRoot(this, r, this.$);\n }\n}\nexport class InternalPrimitiveConstraint extends BaseConstraint {\n traverseApply = (data, ctx) => {\n if (!this.traverseAllows(data, ctx))\n ctx.errorFromNodeContext(this.errorContext);\n };\n compile(js) {\n if (js.traversalKind === \"Allows\")\n js.return(this.compiledCondition);\n else {\n js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`));\n }\n }\n get errorContext() {\n return {\n code: this.kind,\n description: this.description,\n meta: this.meta,\n ...this.inner\n };\n }\n get compiledErrorContext() {\n return compileObjectLiteral(this.errorContext);\n }\n}\nexport const constraintKeyParser = (kind) => (schema, ctx) => {\n if (isArray(schema)) {\n if (schema.length === 0) {\n // Omit empty lists as input\n return;\n }\n const nodes = schema.map(schema => ctx.$.node(kind, schema));\n // predicate order must be preserved to ensure inputs are narrowed\n // and checked in the correct order\n if (kind === \"predicate\")\n return nodes;\n return nodes.sort((l, r) => (l.hash < r.hash ? -1 : 1));\n }\n const child = ctx.$.node(kind, schema);\n return (child.hasOpenIntersection() ? [child] : child);\n};\nexport const intersectConstraints = (s) => {\n const head = s.r.shift();\n if (!head) {\n let result = s.l.length === 0 && s.kind === \"structure\" ?\n $ark.intrinsic.unknown.internal\n : s.ctx.$.node(s.kind, Object.assign(s.baseInner, unflattenConstraints(s.l)), { prereduced: true });\n for (const root of s.roots) {\n if (result instanceof Disjoint)\n return result;\n result = intersectOrPipeNodes(root, result, s.ctx);\n }\n return result;\n }\n let matched = false;\n for (let i = 0; i < s.l.length; i++) {\n const result = intersectOrPipeNodes(s.l[i], head, s.ctx);\n if (result === null)\n continue;\n if (result instanceof Disjoint)\n return result;\n if (result.isRoot()) {\n s.roots.push(result);\n s.l.splice(i);\n return intersectConstraints(s);\n }\n if (!matched) {\n s.l[i] = result;\n matched = true;\n }\n else if (!s.l.includes(result)) {\n return throwInternalError(`Unexpectedly encountered multiple distinct intersection results for refinement ${head}`);\n }\n }\n if (!matched)\n s.l.push(head);\n if (s.kind === \"intersection\") {\n if (head.impliedSiblings)\n for (const node of head.impliedSiblings)\n appendUnique(s.r, node);\n }\n return intersectConstraints(s);\n};\nexport const flattenConstraints = (inner) => {\n const result = Object.entries(inner)\n .flatMap(([k, v]) => k in constraintKeys ? v : [])\n .sort((l, r) => l.precedence < r.precedence ? -1\n : l.precedence > r.precedence ? 1\n // preserve order for predicates\n : l.kind === \"predicate\" && r.kind === \"predicate\" ? 0\n : l.hash < r.hash ? -1\n : 1);\n return result;\n};\nexport const unflattenConstraints = (constraints) => {\n const inner = {};\n for (const constraint of constraints) {\n if (constraint.hasOpenIntersection()) {\n inner[constraint.kind] = append(inner[constraint.kind], constraint);\n }\n else {\n if (inner[constraint.kind]) {\n return throwInternalError(`Unexpected intersection of closed refinements of kind ${constraint.kind}`);\n }\n inner[constraint.kind] = constraint;\n }\n }\n return inner;\n};\nexport const throwInvalidOperandError = (...args) => throwParseError(writeInvalidOperandMessage(...args));\nexport const writeInvalidOperandMessage = (kind, expected, actual) => {\n const actualDescription = actual.hasKind(\"morph\") ? \"a morph\"\n : actual.isUnknown() ? \"unknown\"\n : actual.exclude(expected).defaultShortDescription;\n return `${capitalize(kind)} operand must be ${expected.description} (was ${actualDescription})`;\n};\n",
|
|
47
|
+
"import { Callable, flatMorph, snapshot, throwParseError } from \"@ark/util\";\nimport { $ark } from \"./shared/registry.js\";\nimport { arkKind } from \"./shared/utils.js\";\nexport const parseGeneric = (paramDefs, bodyDef, $) => new GenericRoot(paramDefs, bodyDef, $, $, null);\nexport class LazyGenericBody extends Callable {\n}\nexport class GenericRoot extends Callable {\n [arkKind] = \"generic\";\n paramDefs;\n bodyDef;\n $;\n arg$;\n baseInstantiation;\n hkt;\n description;\n constructor(paramDefs, bodyDef, $, arg$, hkt) {\n super((...args) => {\n const argNodes = flatMorph(this.names, (i, name) => {\n const arg = this.arg$.parse(args[i]);\n if (!arg.extends(this.constraints[i])) {\n throwParseError(writeUnsatisfiedParameterConstraintMessage(name, this.constraints[i].expression, arg.expression));\n }\n return [name, arg];\n });\n if (this.defIsLazy()) {\n const def = this.bodyDef(argNodes);\n return this.$.parse(def);\n }\n return this.$.parse(bodyDef, { args: argNodes });\n });\n this.paramDefs = paramDefs;\n this.bodyDef = bodyDef;\n this.$ = $;\n this.arg$ = arg$;\n this.hkt = hkt;\n this.description =\n hkt ?\n (new hkt().description ?? `a generic type for ${hkt.constructor.name}`)\n : \"a generic type\";\n this.baseInstantiation = this(...this.constraints);\n }\n defIsLazy() {\n return this.bodyDef instanceof LazyGenericBody;\n }\n cacheGetter(name, value) {\n Object.defineProperty(this, name, { value });\n return value;\n }\n get json() {\n return this.cacheGetter(\"json\", {\n params: this.params.map(param => param[1].isUnknown() ? param[0] : [param[0], param[1].json]),\n body: snapshot(this.bodyDef)\n });\n }\n get params() {\n return this.cacheGetter(\"params\", this.paramDefs.map(param => typeof param === \"string\" ?\n [param, $ark.intrinsic.unknown]\n : [param[0], this.$.parse(param[1])]));\n }\n get names() {\n return this.cacheGetter(\"names\", this.params.map(e => e[0]));\n }\n get constraints() {\n return this.cacheGetter(\"constraints\", this.params.map(e => e[1]));\n }\n get internal() {\n return this;\n }\n get referencesById() {\n return this.baseInstantiation.internal.referencesById;\n }\n get references() {\n return this.baseInstantiation.internal.references;\n }\n}\nexport const writeUnsatisfiedParameterConstraintMessage = (name, constraint, arg) => `${name} must be assignable to ${constraint} (was ${arg})`;\n",
|
|
48
|
+
"import { BaseConstraint } from \"./constraint.js\";\nimport { compileObjectLiteral, implementNode } from \"./shared/implement.js\";\nimport { registeredReference } from \"./shared/registry.js\";\nconst implementation = implementNode({\n kind: \"predicate\",\n hasAssociatedError: true,\n collapsibleKey: \"predicate\",\n keys: {\n predicate: {}\n },\n normalize: schema => typeof schema === \"function\" ? { predicate: schema } : schema,\n defaults: {\n description: node => `valid according to ${node.predicate.name || \"an anonymous predicate\"}`\n },\n intersectionIsOpen: true,\n intersections: {\n // as long as the narrows in l and r are individually safe to check\n // in the order they're specified, checking them in the order\n // resulting from this intersection should also be safe.\n predicate: () => null\n }\n});\nexport class PredicateNode extends BaseConstraint {\n serializedPredicate = registeredReference(this.predicate);\n compiledCondition = `${this.serializedPredicate}(data, ctx)`;\n compiledNegation = `!${this.compiledCondition}`;\n impliedBasis = null;\n expression = this.serializedPredicate;\n traverseAllows = this.predicate;\n errorContext = {\n code: \"predicate\",\n description: this.description,\n meta: this.meta\n };\n compiledErrorContext = compileObjectLiteral(this.errorContext);\n traverseApply = (data, ctx) => {\n const errorCount = ctx.currentErrorCount;\n if (!this.predicate(data, ctx.external) &&\n ctx.currentErrorCount === errorCount)\n ctx.errorFromNodeContext(this.errorContext);\n };\n compile(js) {\n if (js.traversalKind === \"Allows\") {\n js.return(this.compiledCondition);\n return;\n }\n js.initializeErrorCount();\n js.if(\n // only add the default error if the predicate didn't add one itself\n `${this.compiledNegation} && ctx.currentErrorCount === errorCount`, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`));\n }\n reduceJsonSchema(base, ctx) {\n return ctx.fallback.predicate({\n code: \"predicate\",\n base,\n predicate: this.predicate\n });\n }\n}\nexport const Predicate = {\n implementation,\n Node: PredicateNode\n};\n",
|
|
49
|
+
"import { throwParseError } from \"@ark/util\";\nimport { InternalPrimitiveConstraint, writeInvalidOperandMessage } from \"../constraint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nconst implementation = implementNode({\n kind: \"divisor\",\n collapsibleKey: \"rule\",\n keys: {\n rule: {\n parse: divisor => Number.isInteger(divisor) ? divisor : (throwParseError(writeNonIntegerDivisorMessage(divisor)))\n }\n },\n normalize: schema => typeof schema === \"number\" ? { rule: schema } : schema,\n hasAssociatedError: true,\n defaults: {\n description: node => node.rule === 1 ? \"an integer\"\n : node.rule === 2 ? \"even\"\n : `a multiple of ${node.rule}`\n },\n intersections: {\n divisor: (l, r, ctx) => ctx.$.node(\"divisor\", {\n rule: Math.abs((l.rule * r.rule) / greatestCommonDivisor(l.rule, r.rule))\n })\n },\n obviatesBasisDescription: true\n});\nexport class DivisorNode extends InternalPrimitiveConstraint {\n traverseAllows = data => data % this.rule === 0;\n compiledCondition = `data % ${this.rule} === 0`;\n compiledNegation = `data % ${this.rule} !== 0`;\n impliedBasis = $ark.intrinsic.number.internal;\n expression = `% ${this.rule}`;\n reduceJsonSchema(schema) {\n schema.type = \"integer\";\n if (this.rule === 1)\n return schema;\n schema.multipleOf = this.rule;\n return schema;\n }\n}\nexport const Divisor = {\n implementation,\n Node: DivisorNode\n};\nexport const writeIndivisibleMessage = (t) => writeInvalidOperandMessage(\"divisor\", $ark.intrinsic.number, t);\nexport const writeNonIntegerDivisorMessage = (divisor) => `divisor must be an integer (was ${divisor})`;\n// https://en.wikipedia.org/wiki/Euclidean_algorithm\nconst greatestCommonDivisor = (l, r) => {\n let previous;\n let greatestCommonDivisor = l;\n let current = r;\n while (current !== 0) {\n previous = current;\n current = greatestCommonDivisor % current;\n greatestCommonDivisor = previous;\n }\n return greatestCommonDivisor;\n};\n",
|
|
50
|
+
"import { isKeyOf, throwParseError } from \"@ark/util\";\nimport { InternalPrimitiveConstraint } from \"../constraint.js\";\nexport class BaseRange extends InternalPrimitiveConstraint {\n boundOperandKind = operandKindsByBoundKind[this.kind];\n compiledActual = this.boundOperandKind === \"value\" ? `data`\n : this.boundOperandKind === \"length\" ? `data.length`\n : `data.valueOf()`;\n comparator = compileComparator(this.kind, this.exclusive);\n numericLimit = this.rule.valueOf();\n expression = `${this.comparator} ${this.rule}`;\n compiledCondition = `${this.compiledActual} ${this.comparator} ${this.numericLimit}`;\n compiledNegation = `${this.compiledActual} ${negatedComparators[this.comparator]} ${this.numericLimit}`;\n // we need to compute stringLimit before errorContext, which references it\n // transitively through description for date bounds\n stringLimit = this.boundOperandKind === \"date\" ?\n dateLimitToString(this.numericLimit)\n : `${this.numericLimit}`;\n limitKind = this.comparator[\"0\"] === \"<\" ? \"upper\" : \"lower\";\n isStricterThan(r) {\n const thisLimitIsStricter = this.limitKind === \"upper\" ?\n this.numericLimit < r.numericLimit\n : this.numericLimit > r.numericLimit;\n return (thisLimitIsStricter ||\n (this.numericLimit === r.numericLimit &&\n this.exclusive === true &&\n !r.exclusive));\n }\n overlapsRange(r) {\n if (this.isStricterThan(r))\n return false;\n if (this.numericLimit === r.numericLimit && (this.exclusive || r.exclusive))\n return false;\n return true;\n }\n overlapIsUnit(r) {\n return (this.numericLimit === r.numericLimit && !this.exclusive && !r.exclusive);\n }\n}\nconst negatedComparators = {\n \"<\": \">=\",\n \"<=\": \">\",\n \">\": \"<=\",\n \">=\": \"<\"\n};\nexport const boundKindPairsByLower = {\n min: \"max\",\n minLength: \"maxLength\",\n after: \"before\"\n};\nexport const parseExclusiveKey = {\n // omit key with value false since it is the default\n parse: (flag) => flag || undefined\n};\nexport const createLengthSchemaNormalizer = (kind) => (schema) => {\n if (typeof schema === \"number\")\n return { rule: schema };\n const { exclusive, ...normalized } = schema;\n return exclusive ?\n {\n ...normalized,\n rule: kind === \"minLength\" ? normalized.rule + 1 : normalized.rule - 1\n }\n : normalized;\n};\nexport const createDateSchemaNormalizer = (kind) => (schema) => {\n if (typeof schema === \"number\" ||\n typeof schema === \"string\" ||\n schema instanceof Date)\n return { rule: schema };\n const { exclusive, ...normalized } = schema;\n if (!exclusive)\n return normalized;\n const numericLimit = typeof normalized.rule === \"number\" ? normalized.rule\n : typeof normalized.rule === \"string\" ?\n new Date(normalized.rule).valueOf()\n : normalized.rule.valueOf();\n return exclusive ?\n {\n ...normalized,\n rule: kind === \"after\" ? numericLimit + 1 : numericLimit - 1\n }\n : normalized;\n};\nexport const parseDateLimit = (limit) => typeof limit === \"string\" || typeof limit === \"number\" ?\n new Date(limit)\n : limit;\nexport const writeInvalidLengthBoundMessage = (kind, limit) => `${kind} bound must be a positive integer (was ${limit})`;\nexport const createLengthRuleParser = (kind) => (limit) => {\n if (!Number.isInteger(limit) || limit < 0)\n throwParseError(writeInvalidLengthBoundMessage(kind, limit));\n return limit;\n};\nconst operandKindsByBoundKind = {\n min: \"value\",\n max: \"value\",\n minLength: \"length\",\n maxLength: \"length\",\n after: \"date\",\n before: \"date\"\n};\nexport const compileComparator = (kind, exclusive) => `${isKeyOf(kind, boundKindPairsByLower) ? \">\" : \"<\"}${exclusive ? \"\" : \"=\"}`;\nexport const dateLimitToString = (limit) => typeof limit === \"string\" ? limit : new Date(limit).toLocaleString();\nexport const writeUnboundableMessage = (root) => `Bounded expression ${root} must be exactly one of number, string, Array, or Date`;\n",
|
|
51
|
+
"import { describeCollapsibleDate } from \"@ark/util\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { BaseRange, createDateSchemaNormalizer, parseDateLimit } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"after\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {\n parse: parseDateLimit,\n serialize: schema => schema.toISOString()\n }\n },\n normalize: createDateSchemaNormalizer(\"after\"),\n defaults: {\n description: node => `${node.collapsibleLimitString} or later`,\n actual: describeCollapsibleDate\n },\n intersections: {\n after: (l, r) => (l.isStricterThan(r) ? l : r)\n }\n});\nexport class AfterNode extends BaseRange {\n impliedBasis = $ark.intrinsic.Date.internal;\n collapsibleLimitString = describeCollapsibleDate(this.rule);\n traverseAllows = data => data >= this.rule;\n reduceJsonSchema(base, ctx) {\n return ctx.fallback.date({ code: \"date\", base, after: this.rule });\n }\n}\nexport const After = {\n implementation,\n Node: AfterNode\n};\n",
|
|
52
|
+
"import { describeCollapsibleDate } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { BaseRange, createDateSchemaNormalizer, parseDateLimit } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"before\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {\n parse: parseDateLimit,\n serialize: schema => schema.toISOString()\n }\n },\n normalize: createDateSchemaNormalizer(\"before\"),\n defaults: {\n description: node => `${node.collapsibleLimitString} or earlier`,\n actual: describeCollapsibleDate\n },\n intersections: {\n before: (l, r) => (l.isStricterThan(r) ? l : r),\n after: (before, after, ctx) => before.overlapsRange(after) ?\n before.overlapIsUnit(after) ?\n ctx.$.node(\"unit\", { unit: before.rule })\n : null\n : Disjoint.init(\"range\", before, after)\n }\n});\nexport class BeforeNode extends BaseRange {\n collapsibleLimitString = describeCollapsibleDate(this.rule);\n traverseAllows = data => data <= this.rule;\n impliedBasis = $ark.intrinsic.Date.internal;\n reduceJsonSchema(base, ctx) {\n return ctx.fallback.date({ code: \"date\", base, before: this.rule });\n }\n}\nexport const Before = {\n implementation,\n Node: BeforeNode\n};\n",
|
|
53
|
+
"import { InternalPrimitiveConstraint } from \"../constraint.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { ToJsonSchema } from \"../shared/toJsonSchema.js\";\nimport { createLengthRuleParser } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"exactLength\",\n collapsibleKey: \"rule\",\n keys: {\n rule: {\n parse: createLengthRuleParser(\"exactLength\")\n }\n },\n normalize: schema => typeof schema === \"number\" ? { rule: schema } : schema,\n hasAssociatedError: true,\n defaults: {\n description: node => `exactly length ${node.rule}`,\n actual: data => `${data.length}`\n },\n intersections: {\n exactLength: (l, r, ctx) => Disjoint.init(\"unit\", ctx.$.node(\"unit\", { unit: l.rule }), ctx.$.node(\"unit\", { unit: r.rule }), { path: [\"length\"] }),\n minLength: (exactLength, minLength) => exactLength.rule >= minLength.rule ?\n exactLength\n : Disjoint.init(\"range\", exactLength, minLength),\n maxLength: (exactLength, maxLength) => exactLength.rule <= maxLength.rule ?\n exactLength\n : Disjoint.init(\"range\", exactLength, maxLength)\n }\n});\nexport class ExactLengthNode extends InternalPrimitiveConstraint {\n traverseAllows = data => data.length === this.rule;\n compiledCondition = `data.length === ${this.rule}`;\n compiledNegation = `data.length !== ${this.rule}`;\n impliedBasis = $ark.intrinsic.lengthBoundable.internal;\n expression = `== ${this.rule}`;\n reduceJsonSchema(schema) {\n switch (schema.type) {\n case \"string\":\n schema.minLength = this.rule;\n schema.maxLength = this.rule;\n return schema;\n case \"array\":\n schema.minItems = this.rule;\n schema.maxItems = this.rule;\n return schema;\n default:\n return ToJsonSchema.throwInternalOperandError(\"exactLength\", schema);\n }\n }\n}\nexport const ExactLength = {\n implementation,\n Node: ExactLengthNode\n};\n",
|
|
54
|
+
"import { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { BaseRange, parseExclusiveKey } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"max\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {},\n exclusive: parseExclusiveKey\n },\n normalize: schema => typeof schema === \"number\" ? { rule: schema } : schema,\n defaults: {\n description: node => {\n if (node.rule === 0)\n return node.exclusive ? \"negative\" : \"non-positive\";\n return `${node.exclusive ? \"less than\" : \"at most\"} ${node.rule}`;\n }\n },\n intersections: {\n max: (l, r) => (l.isStricterThan(r) ? l : r),\n min: (max, min, ctx) => max.overlapsRange(min) ?\n max.overlapIsUnit(min) ?\n ctx.$.node(\"unit\", { unit: max.rule })\n : null\n : Disjoint.init(\"range\", max, min)\n },\n obviatesBasisDescription: true\n});\nexport class MaxNode extends BaseRange {\n impliedBasis = $ark.intrinsic.number.internal;\n traverseAllows = this.exclusive ? data => data < this.rule : data => data <= this.rule;\n reduceJsonSchema(schema) {\n if (this.exclusive)\n schema.exclusiveMaximum = this.rule;\n else\n schema.maximum = this.rule;\n return schema;\n }\n}\nexport const Max = {\n implementation,\n Node: MaxNode\n};\n",
|
|
55
|
+
"import { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { ToJsonSchema } from \"../shared/toJsonSchema.js\";\nimport { BaseRange, createLengthRuleParser, createLengthSchemaNormalizer } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"maxLength\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {\n parse: createLengthRuleParser(\"maxLength\")\n }\n },\n reduce: (inner, $) => inner.rule === 0 ? $.node(\"exactLength\", inner) : undefined,\n normalize: createLengthSchemaNormalizer(\"maxLength\"),\n defaults: {\n description: node => `at most length ${node.rule}`,\n actual: data => `${data.length}`\n },\n intersections: {\n maxLength: (l, r) => (l.isStricterThan(r) ? l : r),\n minLength: (max, min, ctx) => max.overlapsRange(min) ?\n max.overlapIsUnit(min) ?\n ctx.$.node(\"exactLength\", { rule: max.rule })\n : null\n : Disjoint.init(\"range\", max, min)\n }\n});\nexport class MaxLengthNode extends BaseRange {\n impliedBasis = $ark.intrinsic.lengthBoundable.internal;\n traverseAllows = data => data.length <= this.rule;\n reduceJsonSchema(schema) {\n switch (schema.type) {\n case \"string\":\n schema.maxLength = this.rule;\n return schema;\n case \"array\":\n schema.maxItems = this.rule;\n return schema;\n default:\n return ToJsonSchema.throwInternalOperandError(\"maxLength\", schema);\n }\n }\n}\nexport const MaxLength = {\n implementation,\n Node: MaxLengthNode\n};\n",
|
|
56
|
+
"import { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { BaseRange, parseExclusiveKey } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"min\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {},\n exclusive: parseExclusiveKey\n },\n normalize: schema => typeof schema === \"number\" ? { rule: schema } : schema,\n defaults: {\n description: node => {\n if (node.rule === 0)\n return node.exclusive ? \"positive\" : \"non-negative\";\n return `${node.exclusive ? \"more than\" : \"at least\"} ${node.rule}`;\n }\n },\n intersections: {\n min: (l, r) => (l.isStricterThan(r) ? l : r)\n },\n obviatesBasisDescription: true\n});\nexport class MinNode extends BaseRange {\n impliedBasis = $ark.intrinsic.number.internal;\n traverseAllows = this.exclusive ? data => data > this.rule : data => data >= this.rule;\n reduceJsonSchema(schema) {\n if (this.exclusive)\n schema.exclusiveMinimum = this.rule;\n else\n schema.minimum = this.rule;\n return schema;\n }\n}\nexport const Min = {\n implementation,\n Node: MinNode\n};\n",
|
|
57
|
+
"import { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { ToJsonSchema } from \"../shared/toJsonSchema.js\";\nimport { BaseRange, createLengthRuleParser, createLengthSchemaNormalizer } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"minLength\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {\n parse: createLengthRuleParser(\"minLength\")\n }\n },\n reduce: inner => inner.rule === 0 ?\n // a minimum length of zero is trivially satisfied\n $ark.intrinsic.unknown\n : undefined,\n normalize: createLengthSchemaNormalizer(\"minLength\"),\n defaults: {\n description: node => node.rule === 1 ? \"non-empty\" : `at least length ${node.rule}`,\n // avoid default message like \"must be non-empty (was 0)\"\n actual: data => (data.length === 0 ? \"\" : `${data.length}`)\n },\n intersections: {\n minLength: (l, r) => (l.isStricterThan(r) ? l : r)\n }\n});\nexport class MinLengthNode extends BaseRange {\n impliedBasis = $ark.intrinsic.lengthBoundable.internal;\n traverseAllows = data => data.length >= this.rule;\n reduceJsonSchema(schema) {\n switch (schema.type) {\n case \"string\":\n schema.minLength = this.rule;\n return schema;\n case \"array\":\n schema.minItems = this.rule;\n return schema;\n default:\n return ToJsonSchema.throwInternalOperandError(\"minLength\", schema);\n }\n }\n}\nexport const MinLength = {\n implementation,\n Node: MinLengthNode\n};\n",
|
|
58
|
+
"import { After } from \"./after.js\";\nimport { Before } from \"./before.js\";\nimport { ExactLength } from \"./exactLength.js\";\nimport { Max } from \"./max.js\";\nimport { MaxLength } from \"./maxLength.js\";\nimport { Min } from \"./min.js\";\nimport { MinLength } from \"./minLength.js\";\nexport const boundImplementationsByKind = {\n min: Min.implementation,\n max: Max.implementation,\n minLength: MinLength.implementation,\n maxLength: MaxLength.implementation,\n exactLength: ExactLength.implementation,\n after: After.implementation,\n before: Before.implementation\n};\nexport const boundClassesByKind = {\n min: Min.Node,\n max: Max.Node,\n minLength: MinLength.Node,\n maxLength: MaxLength.Node,\n exactLength: ExactLength.Node,\n after: After.Node,\n before: Before.Node\n};\n",
|
|
59
|
+
"import { InternalPrimitiveConstraint } from \"../constraint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nconst implementation = implementNode({\n kind: \"pattern\",\n collapsibleKey: \"rule\",\n keys: {\n rule: {},\n flags: {}\n },\n normalize: schema => typeof schema === \"string\" ? { rule: schema }\n : schema instanceof RegExp ?\n schema.flags ?\n { rule: schema.source, flags: schema.flags }\n : { rule: schema.source }\n : schema,\n obviatesBasisDescription: true,\n obviatesBasisExpression: true,\n hasAssociatedError: true,\n intersectionIsOpen: true,\n defaults: {\n description: node => `matched by ${node.rule}`\n },\n intersections: {\n // for now, non-equal regex are naively intersected:\n // https://github.com/arktypeio/arktype/issues/853\n pattern: () => null\n }\n});\nexport class PatternNode extends InternalPrimitiveConstraint {\n instance = new RegExp(this.rule, this.flags);\n expression = `${this.instance}`;\n traverseAllows = this.instance.test.bind(this.instance);\n compiledCondition = `${this.expression}.test(data)`;\n compiledNegation = `!${this.compiledCondition}`;\n impliedBasis = $ark.intrinsic.string.internal;\n reduceJsonSchema(base, ctx) {\n if (base.pattern) {\n return ctx.fallback.patternIntersection({\n code: \"patternIntersection\",\n base: base,\n pattern: this.rule\n });\n }\n base.pattern = this.rule;\n return base;\n }\n}\nexport const Pattern = {\n implementation,\n Node: PatternNode\n};\n",
|
|
60
|
+
"import { domainDescriptions, entriesOf, flatMorph, hasDomain, isArray, isEmptyObject, printable, throwInternalError, throwParseError, unset } from \"@ark/util\";\nimport { nodeClassesByKind, nodeImplementationsByKind } from \"./kinds.js\";\nimport { Disjoint } from \"./shared/disjoint.js\";\nimport { constraintKeys, defaultValueSerializer, isNodeKind, precedenceOfKind } from \"./shared/implement.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { hasArkKind, isNode } from \"./shared/utils.js\";\nexport const schemaKindOf = (schema, allowedKinds) => {\n const kind = discriminateRootKind(schema);\n if (allowedKinds && !allowedKinds.includes(kind)) {\n return throwParseError(`Root of kind ${kind} should be one of ${allowedKinds}`);\n }\n return kind;\n};\nconst discriminateRootKind = (schema) => {\n if (hasArkKind(schema, \"root\"))\n return schema.kind;\n if (typeof schema === \"string\") {\n return (schema[0] === \"$\" ? \"alias\"\n : schema in domainDescriptions ? \"domain\"\n : \"proto\");\n }\n if (typeof schema === \"function\")\n return \"proto\";\n // throw at end of function\n if (typeof schema !== \"object\" || schema === null)\n return throwParseError(writeInvalidSchemaMessage(schema));\n if (\"morphs\" in schema)\n return \"morph\";\n if (\"branches\" in schema || isArray(schema))\n return \"union\";\n if (\"unit\" in schema)\n return \"unit\";\n if (\"reference\" in schema)\n return \"alias\";\n const schemaKeys = Object.keys(schema);\n if (schemaKeys.length === 0 || schemaKeys.some(k => k in constraintKeys))\n return \"intersection\";\n if (\"proto\" in schema)\n return \"proto\";\n if (\"domain\" in schema)\n return \"domain\";\n return throwParseError(writeInvalidSchemaMessage(schema));\n};\nexport const writeInvalidSchemaMessage = (schema) => `${printable(schema)} is not a valid type schema`;\nconst nodeCountsByPrefix = {};\nconst serializeListableChild = (listableNode) => isArray(listableNode) ?\n listableNode.map(node => node.collapsibleJson)\n : listableNode.collapsibleJson;\nexport const nodesByRegisteredId = {};\n$ark.nodesByRegisteredId = nodesByRegisteredId;\nexport const registerNodeId = (prefix) => {\n nodeCountsByPrefix[prefix] ??= 0;\n return `${prefix}${++nodeCountsByPrefix[prefix]}`;\n};\nexport const parseNode = (ctx) => {\n const impl = nodeImplementationsByKind[ctx.kind];\n const configuredSchema = impl.applyConfig?.(ctx.def, ctx.$.resolvedConfig) ?? ctx.def;\n const inner = {};\n const { meta: metaSchema, ...innerSchema } = configuredSchema;\n const meta = metaSchema === undefined ? {}\n : typeof metaSchema === \"string\" ? { description: metaSchema }\n : metaSchema;\n // ensure node entries are parsed in order of precedence, with non-children\n // parsed first\n const innerSchemaEntries = entriesOf(innerSchema)\n .sort(([lKey], [rKey]) => isNodeKind(lKey) ?\n isNodeKind(rKey) ? precedenceOfKind(lKey) - precedenceOfKind(rKey)\n : 1\n : isNodeKind(rKey) ? -1\n : lKey < rKey ? -1\n : 1)\n .filter(([k, v]) => {\n // move meta. prefixed props to meta, overwriting existing nested\n // props of the same name if they exist\n if (k.startsWith(\"meta.\")) {\n const metaKey = k.slice(5);\n meta[metaKey] = v;\n return false;\n }\n return true;\n });\n for (const entry of innerSchemaEntries) {\n const k = entry[0];\n const keyImpl = impl.keys[k];\n if (!keyImpl)\n return throwParseError(`Key ${k} is not valid on ${ctx.kind} schema`);\n const v = keyImpl.parse ? keyImpl.parse(entry[1], ctx) : entry[1];\n if (v !== unset && (v !== undefined || keyImpl.preserveUndefined))\n inner[k] = v;\n }\n if (impl.reduce && !ctx.prereduced) {\n const reduced = impl.reduce(inner, ctx.$);\n if (reduced) {\n if (reduced instanceof Disjoint)\n return reduced.throw();\n // we can't cache this reduction for now in case the reduction involved\n // impliedSiblings\n return withMeta(reduced, meta);\n }\n }\n const node = createNode({\n id: ctx.id,\n kind: ctx.kind,\n inner,\n meta,\n $: ctx.$\n });\n return node;\n};\nexport const createNode = ({ id, kind, inner, meta, $, ignoreCache }) => {\n const impl = nodeImplementationsByKind[kind];\n const innerEntries = entriesOf(inner);\n const children = [];\n let innerJson = {};\n for (const [k, v] of innerEntries) {\n const keyImpl = impl.keys[k];\n const serialize = keyImpl.serialize ??\n (keyImpl.child ? serializeListableChild : defaultValueSerializer);\n innerJson[k] = serialize(v);\n if (keyImpl.child === true) {\n const listableNode = v;\n if (isArray(listableNode))\n children.push(...listableNode);\n else\n children.push(listableNode);\n }\n else if (typeof keyImpl.child === \"function\")\n children.push(...keyImpl.child(v));\n }\n if (impl.finalizeInnerJson)\n innerJson = impl.finalizeInnerJson(innerJson);\n let json = { ...innerJson };\n let metaJson = {};\n if (!isEmptyObject(meta)) {\n metaJson = flatMorph(meta, (k, v) => [\n k,\n k === \"examples\" ? v : defaultValueSerializer(v)\n ]);\n json.meta = possiblyCollapse(metaJson, \"description\", true);\n }\n innerJson = possiblyCollapse(innerJson, impl.collapsibleKey, false);\n const innerHash = JSON.stringify({ kind, ...innerJson });\n json = possiblyCollapse(json, impl.collapsibleKey, false);\n const collapsibleJson = possiblyCollapse(json, impl.collapsibleKey, true);\n const hash = JSON.stringify({ kind, ...json });\n // we have to wait until after reduction to return a cached entry,\n // since reduction can add impliedSiblings\n if ($.nodesByHash[hash] && !ignoreCache)\n return $.nodesByHash[hash];\n const attachments = {\n id,\n kind,\n impl,\n inner,\n innerEntries,\n innerJson,\n innerHash,\n meta,\n metaJson,\n json,\n hash,\n collapsibleJson: collapsibleJson,\n children\n };\n if (kind !== \"intersection\") {\n for (const k in inner)\n if (k !== \"in\" && k !== \"out\")\n attachments[k] = inner[k];\n }\n const node = new nodeClassesByKind[kind](attachments, $);\n return ($.nodesByHash[hash] = node);\n};\nexport const withId = (node, id) => {\n if (node.id === id)\n return node;\n if (isNode(nodesByRegisteredId[id]))\n throwInternalError(`Unexpected attempt to overwrite node id ${id}`);\n // have to ignore cache to force creation of new potentially cyclic id\n return createNode({\n id,\n kind: node.kind,\n inner: node.inner,\n meta: node.meta,\n $: node.$,\n ignoreCache: true\n });\n};\nexport const withMeta = (node, meta, id) => {\n if (id && isNode(nodesByRegisteredId[id]))\n throwInternalError(`Unexpected attempt to overwrite node id ${id}`);\n return createNode({\n id: id ?? registerNodeId(meta.alias ?? node.kind),\n kind: node.kind,\n inner: node.inner,\n meta,\n $: node.$\n });\n};\nconst possiblyCollapse = (json, toKey, allowPrimitive) => {\n const collapsibleKeys = Object.keys(json);\n if (collapsibleKeys.length === 1 && collapsibleKeys[0] === toKey) {\n const collapsed = json[toKey];\n if (allowPrimitive)\n return collapsed;\n if (\n // if the collapsed value is still an object\n hasDomain(collapsed, \"object\") &&\n // and the JSON did not include any implied keys\n (Object.keys(collapsed).length === 1 || Array.isArray(collapsed))) {\n // we can replace it with its collapsed value\n return collapsed;\n }\n }\n return json;\n};\n",
|
|
61
|
+
"import { append, printable, throwParseError, unset } from \"@ark/util\";\nimport { BaseConstraint } from \"../constraint.js\";\nimport { flatRef } from \"../node.js\";\nimport { compileSerializedValue } from \"../shared/compile.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nexport const intersectProps = (l, r, ctx) => {\n if (l.key !== r.key)\n return null;\n const key = l.key;\n let value = intersectOrPipeNodes(l.value, r.value, ctx);\n const kind = l.required || r.required ? \"required\" : \"optional\";\n if (value instanceof Disjoint) {\n if (kind === \"optional\")\n value = $ark.intrinsic.never.internal;\n else {\n // if either operand was optional, the Disjoint has to be treated as optional\n return value.withPrefixKey(l.key, l.required && r.required ? \"required\" : \"optional\");\n }\n }\n if (kind === \"required\") {\n return ctx.$.node(\"required\", {\n key,\n value\n });\n }\n const defaultIntersection = l.hasDefault() ?\n r.hasDefault() ?\n l.default === r.default ?\n l.default\n : throwParseError(writeDefaultIntersectionMessage(l.default, r.default))\n : l.default\n : r.hasDefault() ? r.default\n : unset;\n return ctx.$.node(\"optional\", {\n key,\n value,\n // unset is stripped during parsing\n default: defaultIntersection\n });\n};\nexport class BaseProp extends BaseConstraint {\n required = this.kind === \"required\";\n optional = this.kind === \"optional\";\n impliedBasis = $ark.intrinsic.object.internal;\n serializedKey = compileSerializedValue(this.key);\n compiledKey = typeof this.key === \"string\" ? this.key : this.serializedKey;\n flatRefs = append(this.value.flatRefs.map(ref => flatRef([this.key, ...ref.path], ref.node)), flatRef([this.key], this.value));\n _transform(mapper, ctx) {\n ctx.path.push(this.key);\n const result = super._transform(mapper, ctx);\n ctx.path.pop();\n return result;\n }\n hasDefault() {\n return \"default\" in this.inner;\n }\n traverseAllows = (data, ctx) => {\n if (this.key in data) {\n // ctx will be undefined if this node isn't context-dependent\n return traverseKey(this.key, () => this.value.traverseAllows(data[this.key], ctx), ctx);\n }\n return this.optional;\n };\n traverseApply = (data, ctx) => {\n if (this.key in data) {\n traverseKey(this.key, () => this.value.traverseApply(data[this.key], ctx), ctx);\n }\n else if (this.hasKind(\"required\"))\n ctx.errorFromNodeContext(this.errorContext);\n };\n compile(js) {\n js.if(`${this.serializedKey} in data`, () => js.traverseKey(this.serializedKey, `data${js.prop(this.key)}`, this.value));\n if (this.hasKind(\"required\")) {\n js.else(() => js.traversalKind === \"Apply\" ?\n js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)\n : js.return(false));\n }\n if (js.traversalKind === \"Allows\")\n js.return(true);\n }\n}\nexport const writeDefaultIntersectionMessage = (lValue, rValue) => `Invalid intersection of default values ${printable(lValue)} & ${printable(rValue)}`;\n",
|
|
62
|
+
"import { hasDomain, isThunk, omit, printable, throwParseError } from \"@ark/util\";\nimport { intrinsic } from \"../intrinsic.js\";\nimport { compileSerializedValue } from \"../shared/compile.js\";\nimport { ArkErrors } from \"../shared/errors.js\";\nimport { defaultValueSerializer, implementNode } from \"../shared/implement.js\";\nimport { registeredReference } from \"../shared/registry.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nimport { BaseProp, intersectProps } from \"./prop.js\";\nconst implementation = implementNode({\n kind: \"optional\",\n hasAssociatedError: false,\n intersectionIsOpen: true,\n keys: {\n key: {},\n value: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema)\n },\n default: {\n preserveUndefined: true\n }\n },\n normalize: schema => schema,\n reduce: (inner, $) => {\n if ($.resolvedConfig.exactOptionalPropertyTypes === false) {\n if (!inner.value.allows(undefined)) {\n return $.node(\"optional\", { ...inner, value: inner.value.or(intrinsic.undefined) }, { prereduced: true });\n }\n }\n },\n defaults: {\n description: node => `${node.compiledKey}?: ${node.value.description}`\n },\n intersections: {\n optional: intersectProps\n }\n});\nexport class OptionalNode extends BaseProp {\n constructor(...args) {\n super(...args);\n if (\"default\" in this.inner)\n assertDefaultValueAssignability(this.value, this.inner.default, this.key);\n }\n get rawIn() {\n const baseIn = super.rawIn;\n if (!this.hasDefault())\n return baseIn;\n return this.$.node(\"optional\", omit(baseIn.inner, { default: true }), {\n prereduced: true\n });\n }\n get outProp() {\n if (!this.hasDefault())\n return this;\n const { default: defaultValue, ...requiredInner } = this.inner;\n return this.cacheGetter(\"outProp\", this.$.node(\"required\", requiredInner, { prereduced: true }));\n }\n expression = this.hasDefault() ?\n `${this.compiledKey}: ${this.value.expression} = ${printable(this.inner.default)}`\n : `${this.compiledKey}?: ${this.value.expression}`;\n defaultValueMorph = getDefaultableMorph(this);\n defaultValueMorphRef = this.defaultValueMorph && registeredReference(this.defaultValueMorph);\n}\nexport const Optional = {\n implementation,\n Node: OptionalNode\n};\nconst defaultableMorphCache = {};\nconst getDefaultableMorph = (node) => {\n if (!node.hasDefault())\n return;\n const cacheKey = `{${node.compiledKey}: ${node.value.id} = ${defaultValueSerializer(node.default)}}`;\n return (defaultableMorphCache[cacheKey] ??= computeDefaultValueMorph(node.key, node.value, node.default));\n};\nexport const computeDefaultValueMorph = (key, value, defaultInput) => {\n if (typeof defaultInput === \"function\") {\n // if the value has a morph, pipe context through it\n return value.includesTransform ?\n (data, ctx) => {\n traverseKey(key, () => value((data[key] = defaultInput()), ctx), ctx);\n return data;\n }\n : data => {\n data[key] = defaultInput();\n return data;\n };\n }\n // non-functional defaults can be safely cached as long as the morph is\n // guaranteed to be pure and the output is primitive\n const precomputedMorphedDefault = value.includesTransform ? value.assert(defaultInput) : defaultInput;\n return hasDomain(precomputedMorphedDefault, \"object\") ?\n // the type signature only allows this if the value was morphed\n (data, ctx) => {\n traverseKey(key, () => value((data[key] = defaultInput), ctx), ctx);\n return data;\n }\n : data => {\n data[key] = precomputedMorphedDefault;\n return data;\n };\n};\nexport const assertDefaultValueAssignability = (node, value, key) => {\n const wrapped = isThunk(value);\n if (hasDomain(value, \"object\") && !wrapped)\n throwParseError(writeNonPrimitiveNonFunctionDefaultValueMessage(key));\n // if the node has a default value, finalize it and apply JIT optimizations\n // if applicable to ensure behavior + error logging is externally consistent\n // (using .in here insead of .rawIn triggers finalization)\n const out = node.in(wrapped ? value() : value);\n if (out instanceof ArkErrors) {\n if (key === null) {\n // e.g. \"Default must be assignable to number (was string)\"\n throwParseError(`Default ${out.summary}`);\n }\n const atPath = out.transform(e => e.transform(input => ({ ...input, prefixPath: [key] })));\n // e.g. \"Default for bar must be assignable to number (was string)\"\n // e.g. \"Default for value at [0] must be assignable to number (was string)\"\n throwParseError(`Default for ${atPath.summary}`);\n }\n return value;\n};\nexport const writeNonPrimitiveNonFunctionDefaultValueMessage = (key) => {\n const keyDescription = key === null ? \"\"\n : typeof key === \"number\" ? `for value at [${key}] `\n : `for ${compileSerializedValue(key)} `;\n return `Non-primitive default ${keyDescription}must be specified as a function like () => ({my: 'object'})`;\n};\n",
|
|
63
|
+
"import { arrayEquals, flatMorph, includes, inferred, omit, throwInternalError, throwParseError } from \"@ark/util\";\nimport { mergeToJsonSchemaConfigs } from \"../config.js\";\nimport { throwInvalidOperandError } from \"../constraint.js\";\nimport { BaseNode } from \"../node.js\";\nimport { Disjoint, writeUnsatisfiableExpressionError } from \"../shared/disjoint.js\";\nimport { ArkErrors } from \"../shared/errors.js\";\nimport { structuralKinds } from \"../shared/implement.js\";\nimport { intersectNodesRoot, pipeNodesRoot } from \"../shared/intersections.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { arkKind, hasArkKind } from \"../shared/utils.js\";\nimport { assertDefaultValueAssignability } from \"../structure/optional.js\";\nexport class BaseRoot extends BaseNode {\n constructor(attachments, $) {\n super(attachments, $);\n // define as a getter to avoid it being enumerable/spreadable\n Object.defineProperty(this, arkKind, { value: \"root\", enumerable: false });\n }\n // doesn't seem possible to override this at a type-level (e.g. via declare)\n // without TS complaining about getters\n get rawIn() {\n return super.rawIn;\n }\n get rawOut() {\n return super.rawOut;\n }\n get internal() {\n return this;\n }\n get \"~standard\"() {\n return {\n vendor: \"arktype\",\n version: 1,\n validate: input => {\n const out = this(input);\n if (out instanceof ArkErrors)\n return out;\n return { value: out };\n },\n jsonSchema: {\n input: opts => this.rawIn.toJsonSchema({\n target: validateStandardJsonSchemaTarget(opts.target),\n ...opts.libraryOptions\n }),\n output: opts => this.rawOut.toJsonSchema({\n target: validateStandardJsonSchemaTarget(opts.target),\n ...opts.libraryOptions\n })\n }\n };\n }\n as() {\n return this;\n }\n brand(name) {\n if (name === \"\")\n return throwParseError(emptyBrandNameMessage);\n return this;\n }\n readonly() {\n return this;\n }\n branches = this.hasKind(\"union\") ? this.inner.branches : [this];\n distribute(mapBranch, reduceMapped) {\n const mappedBranches = this.branches.map(mapBranch);\n return reduceMapped?.(mappedBranches) ?? mappedBranches;\n }\n get shortDescription() {\n return this.meta.description ?? this.defaultShortDescription;\n }\n toJsonSchema(opts = {}) {\n const ctx = mergeToJsonSchemaConfigs(this.$.resolvedConfig.toJsonSchema, opts);\n ctx.useRefs ||= this.isCyclic;\n // ensure $schema is the first key if present\n const schema = typeof ctx.dialect === \"string\" ? { $schema: ctx.dialect } : {};\n Object.assign(schema, this.toJsonSchemaRecurse(ctx));\n if (ctx.useRefs) {\n const defs = flatMorph(this.references, (i, ref) => ref.isRoot() && !ref.alwaysExpandJsonSchema ?\n [ref.id, ref.toResolvedJsonSchema(ctx)]\n : []);\n // draft-2020-12 uses $defs, draft-07 uses definitions\n if (ctx.target === \"draft-07\")\n Object.assign(schema, { definitions: defs });\n else\n schema.$defs = defs;\n }\n return schema;\n }\n toJsonSchemaRecurse(ctx) {\n if (ctx.useRefs && !this.alwaysExpandJsonSchema) {\n // draft-2020-12 uses $defs, draft-07 uses definitions\n const defsKey = ctx.target === \"draft-07\" ? \"definitions\" : \"$defs\";\n return { $ref: `#/${defsKey}/${this.id}` };\n }\n return this.toResolvedJsonSchema(ctx);\n }\n get alwaysExpandJsonSchema() {\n return (this.isBasis() ||\n this.kind === \"alias\" ||\n (this.hasKind(\"union\") && this.isBoolean));\n }\n toResolvedJsonSchema(ctx) {\n const result = this.innerToJsonSchema(ctx);\n return Object.assign(result, this.metaJson);\n }\n intersect(r) {\n const rNode = this.$.parseDefinition(r);\n const result = this.rawIntersect(rNode);\n if (result instanceof Disjoint)\n return result;\n return this.$.finalize(result);\n }\n rawIntersect(r) {\n return intersectNodesRoot(this, r, this.$);\n }\n toNeverIfDisjoint() {\n return this;\n }\n and(r) {\n const result = this.intersect(r);\n return result instanceof Disjoint ? result.throw() : result;\n }\n rawAnd(r) {\n const result = this.rawIntersect(r);\n return result instanceof Disjoint ? result.throw() : result;\n }\n or(r) {\n const rNode = this.$.parseDefinition(r);\n return this.$.finalize(this.rawOr(rNode));\n }\n rawOr(r) {\n const branches = [...this.branches, ...r.branches];\n return this.$.node(\"union\", branches);\n }\n map(flatMapEntry) {\n return this.$.schema(this.applyStructuralOperation(\"map\", [flatMapEntry]));\n }\n pick(...keys) {\n return this.$.schema(this.applyStructuralOperation(\"pick\", keys));\n }\n omit(...keys) {\n return this.$.schema(this.applyStructuralOperation(\"omit\", keys));\n }\n required() {\n return this.$.schema(this.applyStructuralOperation(\"required\", []));\n }\n partial() {\n return this.$.schema(this.applyStructuralOperation(\"partial\", []));\n }\n _keyof;\n keyof() {\n if (this._keyof)\n return this._keyof;\n const result = this.applyStructuralOperation(\"keyof\", []).reduce((result, branch) => result.intersect(branch).toNeverIfDisjoint(), $ark.intrinsic.unknown.internal);\n if (result.branches.length === 0) {\n throwParseError(writeUnsatisfiableExpressionError(`keyof ${this.expression}`));\n }\n return (this._keyof = this.$.finalize(result));\n }\n get props() {\n if (this.branches.length !== 1)\n return throwParseError(writeLiteralUnionEntriesMessage(this.expression));\n return [...this.applyStructuralOperation(\"props\", [])[0]];\n }\n merge(r) {\n const rNode = this.$.parseDefinition(r);\n return this.$.schema(rNode.distribute(branch => this.applyStructuralOperation(\"merge\", [\n structureOf(branch) ??\n throwParseError(writeNonStructuralOperandMessage(\"merge\", branch.expression))\n ])));\n }\n applyStructuralOperation(operation, args) {\n return this.distribute(branch => {\n if (branch.equals($ark.intrinsic.object) && operation !== \"merge\")\n // ideally this wouldn't be a special case, but for now it\n // allows us to bypass `assertHasKeys` checks on base\n // instantiations of generics like Pick and Omit. Could\n // potentially be removed once constraints can reference each other:\n // https://github.com/arktypeio/arktype/issues/1053\n return branch;\n const structure = structureOf(branch);\n if (!structure) {\n throwParseError(writeNonStructuralOperandMessage(operation, branch.expression));\n }\n if (operation === \"keyof\")\n return structure.keyof();\n if (operation === \"get\")\n return structure.get(...args);\n if (operation === \"props\")\n return structure.props;\n const structuralMethodName = operation === \"required\" ? \"require\"\n : operation === \"partial\" ? \"optionalize\"\n : operation;\n return this.$.node(\"intersection\", {\n domain: \"object\",\n structure: structure[structuralMethodName](...args)\n });\n });\n }\n get(...path) {\n if (path[0] === undefined)\n return this;\n return this.$.schema(this.applyStructuralOperation(\"get\", path));\n }\n extract(r) {\n const rNode = this.$.parseDefinition(r);\n return this.$.schema(this.branches.filter(branch => branch.extends(rNode)));\n }\n exclude(r) {\n const rNode = this.$.parseDefinition(r);\n return this.$.schema(this.branches.filter(branch => !branch.extends(rNode)));\n }\n array() {\n return this.$.schema(this.isUnknown() ?\n { proto: Array }\n : {\n proto: Array,\n sequence: this\n }, { prereduced: true });\n }\n overlaps(r) {\n const intersection = this.intersect(r);\n return !(intersection instanceof Disjoint);\n }\n extends(r) {\n if (this.isNever())\n return true;\n const intersection = this.intersect(r);\n return (!(intersection instanceof Disjoint) && this.equals(intersection));\n }\n ifExtends(r) {\n return this.extends(r) ? this : undefined;\n }\n subsumes(r) {\n const rNode = this.$.parseDefinition(r);\n return rNode.extends(this);\n }\n configure(meta, selector = \"shallow\") {\n return this.configureReferences(meta, selector);\n }\n describe(description, selector = \"shallow\") {\n return this.configure({ description }, selector);\n }\n // these should ideally be implemented in arktype since they use its syntax\n // https://github.com/arktypeio/arktype/issues/1223\n optional() {\n return [this, \"?\"];\n }\n // these should ideally be implemented in arktype since they use its syntax\n // https://github.com/arktypeio/arktype/issues/1223\n default(thunkableValue) {\n assertDefaultValueAssignability(this, thunkableValue, null);\n return [this, \"=\", thunkableValue];\n }\n from(input) {\n // ideally we might not validate here but for now we need to do determine\n // which morphs to apply\n return this.assert(input);\n }\n _pipe(...morphs) {\n const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(morph), this);\n return this.$.finalize(result);\n }\n tryPipe(...morphs) {\n const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(hasArkKind(morph, \"root\") ? morph : ((In, ctx) => {\n try {\n return morph(In, ctx);\n }\n catch (e) {\n return ctx.error({\n code: \"predicate\",\n predicate: morph,\n actual: `aborted due to error:\\n ${e}\\n`\n });\n }\n })), this);\n return this.$.finalize(result);\n }\n pipe = Object.assign(this._pipe.bind(this), {\n try: this.tryPipe.bind(this)\n });\n to(def) {\n return this.$.finalize(this.toNode(this.$.parseDefinition(def)));\n }\n toNode(root) {\n const result = pipeNodesRoot(this, root, this.$);\n if (result instanceof Disjoint)\n return result.throw();\n return result;\n }\n rawPipeOnce(morph) {\n if (hasArkKind(morph, \"root\"))\n return this.toNode(morph);\n return this.distribute(branch => branch.hasKind(\"morph\") ?\n this.$.node(\"morph\", {\n in: branch.inner.in,\n morphs: [...branch.morphs, morph]\n })\n : this.$.node(\"morph\", {\n in: branch,\n morphs: [morph]\n }), this.$.parseSchema);\n }\n narrow(predicate) {\n return this.constrainOut(\"predicate\", predicate);\n }\n constrain(kind, schema) {\n return this._constrain(\"root\", kind, schema);\n }\n constrainIn(kind, schema) {\n return this._constrain(\"in\", kind, schema);\n }\n constrainOut(kind, schema) {\n return this._constrain(\"out\", kind, schema);\n }\n _constrain(io, kind, schema) {\n const constraint = this.$.node(kind, schema);\n if (constraint.isRoot()) {\n // if the node reduces to `unknown`, nothing to do (e.g. minLength: 0)\n return constraint.isUnknown() ? this : (throwInternalError(`Unexpected constraint node ${constraint}`));\n }\n const operand = io === \"root\" ? this\n : io === \"in\" ? this.rawIn\n : this.rawOut;\n if (operand.hasKind(\"morph\") ||\n (constraint.impliedBasis && !operand.extends(constraint.impliedBasis))) {\n return throwInvalidOperandError(kind, constraint.impliedBasis, this);\n }\n const partialIntersection = this.$.node(\"intersection\", {\n // important this is constraint.kind instead of kind in case\n // the node was reduced during parsing\n [constraint.kind]: constraint\n });\n const result = io === \"out\" ?\n pipeNodesRoot(this, partialIntersection, this.$)\n : intersectNodesRoot(this, partialIntersection, this.$);\n if (result instanceof Disjoint)\n result.throw();\n return this.$.finalize(result);\n }\n onUndeclaredKey(cfg) {\n const rule = typeof cfg === \"string\" ? cfg : cfg.rule;\n const deep = typeof cfg === \"string\" ? false : cfg.deep;\n return this.$.finalize(this.transform((kind, inner) => kind === \"structure\" ?\n rule === \"ignore\" ?\n omit(inner, { undeclared: 1 })\n : { ...inner, undeclared: rule }\n : inner, deep ? undefined : ({ shouldTransform: node => !includes(structuralKinds, node.kind) })));\n }\n hasEqualMorphs(r) {\n if (!this.includesTransform && !r.includesTransform)\n return true;\n if (!arrayEquals(this.shallowMorphs, r.shallowMorphs))\n return false;\n if (!arrayEquals(this.flatMorphs, r.flatMorphs, {\n isEqual: (l, r) => l.propString === r.propString &&\n (l.node.hasKind(\"morph\") && r.node.hasKind(\"morph\") ?\n l.node.hasEqualMorphs(r.node)\n : l.node.hasKind(\"intersection\") && r.node.hasKind(\"intersection\") ?\n l.node.structure?.structuralMorphRef ===\n r.node.structure?.structuralMorphRef\n : false)\n }))\n return false;\n return true;\n }\n onDeepUndeclaredKey(behavior) {\n return this.onUndeclaredKey({ rule: behavior, deep: true });\n }\n filter(predicate) {\n return this.constrainIn(\"predicate\", predicate);\n }\n divisibleBy(schema) {\n return this.constrain(\"divisor\", schema);\n }\n matching(schema) {\n return this.constrain(\"pattern\", schema);\n }\n atLeast(schema) {\n return this.constrain(\"min\", schema);\n }\n atMost(schema) {\n return this.constrain(\"max\", schema);\n }\n moreThan(schema) {\n return this.constrain(\"min\", exclusivizeRangeSchema(schema));\n }\n lessThan(schema) {\n return this.constrain(\"max\", exclusivizeRangeSchema(schema));\n }\n atLeastLength(schema) {\n return this.constrain(\"minLength\", schema);\n }\n atMostLength(schema) {\n return this.constrain(\"maxLength\", schema);\n }\n moreThanLength(schema) {\n return this.constrain(\"minLength\", exclusivizeRangeSchema(schema));\n }\n lessThanLength(schema) {\n return this.constrain(\"maxLength\", exclusivizeRangeSchema(schema));\n }\n exactlyLength(schema) {\n return this.constrain(\"exactLength\", schema);\n }\n atOrAfter(schema) {\n return this.constrain(\"after\", schema);\n }\n atOrBefore(schema) {\n return this.constrain(\"before\", schema);\n }\n laterThan(schema) {\n return this.constrain(\"after\", exclusivizeRangeSchema(schema));\n }\n earlierThan(schema) {\n return this.constrain(\"before\", exclusivizeRangeSchema(schema));\n }\n}\nexport const emptyBrandNameMessage = `Expected a non-empty brand name after #`;\nconst supportedJsonSchemaTargets = [\n \"draft-2020-12\",\n \"draft-07\"\n];\nexport const writeInvalidJsonSchemaTargetMessage = (target) => `JSONSchema target '${target}' is not supported (must be ${supportedJsonSchemaTargets.map(t => `\"${t}\"`).join(\" or \")})`;\nconst validateStandardJsonSchemaTarget = (target) => {\n if (!includes(supportedJsonSchemaTargets, target))\n throwParseError(writeInvalidJsonSchemaTargetMessage(target));\n return target;\n};\nexport const exclusivizeRangeSchema = (schema) => (typeof schema === \"object\" && !(schema instanceof Date) ?\n { ...schema, exclusive: true }\n : {\n rule: schema,\n exclusive: true\n });\nexport const typeOrTermExtends = (t, base) => hasArkKind(base, \"root\") ?\n hasArkKind(t, \"root\") ? t.extends(base)\n : base.allows(t)\n : hasArkKind(t, \"root\") ? t.hasUnit(base)\n : base === t;\nconst structureOf = (branch) => {\n if (branch.hasKind(\"morph\"))\n return null;\n if (branch.hasKind(\"intersection\")) {\n return (branch.inner.structure ??\n (branch.basis?.domain === \"object\" ?\n branch.$.bindReference($ark.intrinsic.emptyStructure)\n : null));\n }\n if (branch.isBasis() && branch.domain === \"object\")\n return branch.$.bindReference($ark.intrinsic.emptyStructure);\n return null;\n};\nexport const writeLiteralUnionEntriesMessage = (expression) => `Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:\n${expression}`;\nexport const writeNonStructuralOperandMessage = (operation, operand) => `${operation} operand must be an object (was ${operand})`;\n",
|
|
64
|
+
"import { flatMorph } from \"@ark/util\";\nimport { schemaKindsRightOf } from \"../shared/implement.js\";\nexport const defineRightwardIntersections = (kind, implementation) => flatMorph(schemaKindsRightOf(kind), (i, kind) => [\n kind,\n implementation\n]);\n",
|
|
65
|
+
"import { append, domainDescriptions, printable, throwInternalError, throwParseError } from \"@ark/util\";\nimport { nodesByRegisteredId } from \"../parse.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { hasArkKind } from \"../shared/utils.js\";\nimport { BaseRoot } from \"./root.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nexport const normalizeAliasSchema = (schema) => typeof schema === \"string\" ? { reference: schema } : schema;\nconst neverIfDisjoint = (result) => result instanceof Disjoint ? $ark.intrinsic.never.internal : result;\nconst implementation = implementNode({\n kind: \"alias\",\n hasAssociatedError: false,\n collapsibleKey: \"reference\",\n keys: {\n reference: {\n serialize: s => (s.startsWith(\"$\") ? s : `$ark.${s}`)\n },\n resolve: {}\n },\n normalize: normalizeAliasSchema,\n defaults: {\n description: node => node.reference\n },\n intersections: {\n alias: (l, r, ctx) => ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r.resolution, ctx)), `${l.reference}${ctx.pipe ? \"=>\" : \"&\"}${r.reference}`),\n ...defineRightwardIntersections(\"alias\", (l, r, ctx) => {\n if (r.isUnknown())\n return l;\n if (r.isNever())\n return r;\n if (r.isBasis() && !r.overlaps($ark.intrinsic.object)) {\n // can be more robust as part of https://github.com/arktypeio/arktype/issues/1026\n return Disjoint.init(\"assignability\", $ark.intrinsic.object, r);\n }\n return ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r, ctx)), `${l.reference}${ctx.pipe ? \"=>\" : \"&\"}${r.id}`);\n })\n }\n});\nexport class AliasNode extends BaseRoot {\n expression = this.reference;\n structure = undefined;\n get resolution() {\n const result = this._resolve();\n return (nodesByRegisteredId[this.id] = result);\n }\n _resolve() {\n if (this.resolve)\n return this.resolve();\n if (this.reference[0] === \"$\")\n return this.$.resolveRoot(this.reference.slice(1));\n const id = this.reference;\n let resolution = nodesByRegisteredId[id];\n const seen = [];\n while (hasArkKind(resolution, \"context\")) {\n if (seen.includes(resolution.id)) {\n return throwParseError(writeShallowCycleErrorMessage(resolution.id, seen));\n }\n seen.push(resolution.id);\n resolution = nodesByRegisteredId[resolution.id];\n }\n if (!hasArkKind(resolution, \"root\")) {\n return throwInternalError(`Unexpected resolution for reference ${this.reference}\nSeen: [${seen.join(\"->\")}] \nResolution: ${printable(resolution)}`);\n }\n return resolution;\n }\n get resolutionId() {\n if (this.reference.includes(\"&\") || this.reference.includes(\"=>\"))\n return this.resolution.id;\n if (this.reference[0] !== \"$\")\n return this.reference;\n const alias = this.reference.slice(1);\n const resolution = this.$.resolutions[alias];\n if (typeof resolution === \"string\")\n return resolution;\n if (hasArkKind(resolution, \"root\"))\n return resolution.id;\n return throwInternalError(`Unexpected resolution for reference ${this.reference}: ${printable(resolution)}`);\n }\n get defaultShortDescription() {\n return domainDescriptions.object;\n }\n innerToJsonSchema(ctx) {\n return this.resolution.toJsonSchemaRecurse(ctx);\n }\n traverseAllows = (data, ctx) => {\n const seen = ctx.seen[this.reference];\n if (seen?.includes(data))\n return true;\n ctx.seen[this.reference] = append(seen, data);\n return this.resolution.traverseAllows(data, ctx);\n };\n traverseApply = (data, ctx) => {\n const seen = ctx.seen[this.reference];\n if (seen?.includes(data))\n return;\n ctx.seen[this.reference] = append(seen, data);\n this.resolution.traverseApply(data, ctx);\n };\n compile(js) {\n const id = this.resolutionId;\n js.if(`ctx.seen.${id} && ctx.seen.${id}.includes(data)`, () => js.return(true));\n js.if(`!ctx.seen.${id}`, () => js.line(`ctx.seen.${id} = []`));\n js.line(`ctx.seen.${id}.push(data)`);\n js.return(js.invoke(id));\n }\n}\nexport const writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join(\"->\")}`;\nexport const Alias = {\n implementation,\n Node: AliasNode\n};\n",
|
|
66
|
+
"import { compileObjectLiteral } from \"../shared/implement.js\";\nimport { BaseRoot } from \"./root.js\";\nexport class InternalBasis extends BaseRoot {\n traverseApply = (data, ctx) => {\n if (!this.traverseAllows(data, ctx))\n ctx.errorFromNodeContext(this.errorContext);\n };\n get errorContext() {\n return {\n code: this.kind,\n description: this.description,\n meta: this.meta,\n ...this.inner\n };\n }\n get compiledErrorContext() {\n return compileObjectLiteral(this.errorContext);\n }\n compile(js) {\n if (js.traversalKind === \"Allows\")\n js.return(this.compiledCondition);\n else {\n js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`));\n }\n }\n}\n",
|
|
67
|
+
"import { domainDescriptions, domainOf, hasKey, throwParseError } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { InternalBasis } from \"./basis.js\";\nconst implementation = implementNode({\n kind: \"domain\",\n hasAssociatedError: true,\n collapsibleKey: \"domain\",\n keys: {\n domain: {},\n numberAllowsNaN: {}\n },\n normalize: schema => typeof schema === \"string\" ? { domain: schema }\n : hasKey(schema, \"numberAllowsNaN\") && schema.domain !== \"number\" ?\n throwParseError(Domain.writeBadAllowNanMessage(schema.domain))\n : schema,\n applyConfig: (schema, config) => (schema.numberAllowsNaN === undefined &&\n schema.domain === \"number\" &&\n config.numberAllowsNaN) ?\n { ...schema, numberAllowsNaN: true }\n : schema,\n defaults: {\n description: node => domainDescriptions[node.domain],\n actual: data => Number.isNaN(data) ? \"NaN\" : domainDescriptions[domainOf(data)]\n },\n intersections: {\n domain: (l, r) => \n // since l === r is handled by default, remaining cases are disjoint\n // outside those including options like numberAllowsNaN\n l.domain === \"number\" && r.domain === \"number\" ?\n l.numberAllowsNaN ?\n r\n : l\n : Disjoint.init(\"domain\", l, r)\n }\n});\nexport class DomainNode extends InternalBasis {\n requiresNaNCheck = this.domain === \"number\" && !this.numberAllowsNaN;\n traverseAllows = this.requiresNaNCheck ?\n data => typeof data === \"number\" && !Number.isNaN(data)\n : data => domainOf(data) === this.domain;\n compiledCondition = this.domain === \"object\" ?\n `((typeof data === \"object\" && data !== null) || typeof data === \"function\")`\n : `typeof data === \"${this.domain}\"${this.requiresNaNCheck ? \" && !Number.isNaN(data)\" : \"\"}`;\n compiledNegation = this.domain === \"object\" ?\n `((typeof data !== \"object\" || data === null) && typeof data !== \"function\")`\n : `typeof data !== \"${this.domain}\"${this.requiresNaNCheck ? \" || Number.isNaN(data)\" : \"\"}`;\n expression = this.numberAllowsNaN ? \"number | NaN\" : this.domain;\n get nestableExpression() {\n return this.numberAllowsNaN ? `(${this.expression})` : this.expression;\n }\n get defaultShortDescription() {\n return domainDescriptions[this.domain];\n }\n innerToJsonSchema(ctx) {\n if (this.domain === \"bigint\" || this.domain === \"symbol\") {\n return ctx.fallback.domain({\n code: \"domain\",\n base: {},\n domain: this.domain\n });\n }\n return {\n type: this.domain\n };\n }\n}\nexport const Domain = {\n implementation,\n Node: DomainNode,\n writeBadAllowNanMessage: (actual) => `numberAllowsNaN may only be specified with domain \"number\" (was ${actual})`\n};\n",
|
|
68
|
+
"import { flatMorph, hasDomain, includes, isEmptyObject, isKeyOf, throwParseError } from \"@ark/util\";\nimport { constraintKeyParser, flattenConstraints, intersectConstraints } from \"../constraint.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode, prestructuralKinds, structureKeys } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { hasArkKind, isNode } from \"../shared/utils.js\";\nimport { BaseRoot } from \"./root.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nconst implementation = implementNode({\n kind: \"intersection\",\n hasAssociatedError: true,\n normalize: rawSchema => {\n if (isNode(rawSchema))\n return rawSchema;\n const { structure, ...schema } = rawSchema;\n const hasRootStructureKey = !!structure;\n const normalizedStructure = structure ?? {};\n const normalized = flatMorph(schema, (k, v) => {\n if (isKeyOf(k, structureKeys)) {\n if (hasRootStructureKey) {\n throwParseError(`Flattened structure key ${k} cannot be specified alongside a root 'structure' key.`);\n }\n normalizedStructure[k] = v;\n return [];\n }\n return [k, v];\n });\n if (hasArkKind(normalizedStructure, \"constraint\") ||\n !isEmptyObject(normalizedStructure))\n normalized.structure = normalizedStructure;\n return normalized;\n },\n finalizeInnerJson: ({ structure, ...rest }) => hasDomain(structure, \"object\") ? { ...structure, ...rest } : rest,\n keys: {\n domain: {\n child: true,\n parse: (schema, ctx) => ctx.$.node(\"domain\", schema)\n },\n proto: {\n child: true,\n parse: (schema, ctx) => ctx.$.node(\"proto\", schema)\n },\n structure: {\n child: true,\n parse: (schema, ctx) => ctx.$.node(\"structure\", schema),\n serialize: node => {\n if (!node.sequence?.minLength)\n return node.collapsibleJson;\n const { sequence, ...structureJson } = node.collapsibleJson;\n const { minVariadicLength, ...sequenceJson } = sequence;\n const collapsibleSequenceJson = sequenceJson.variadic && Object.keys(sequenceJson).length === 1 ?\n sequenceJson.variadic\n : sequenceJson;\n return { ...structureJson, sequence: collapsibleSequenceJson };\n }\n },\n divisor: {\n child: true,\n parse: constraintKeyParser(\"divisor\")\n },\n max: {\n child: true,\n parse: constraintKeyParser(\"max\")\n },\n min: {\n child: true,\n parse: constraintKeyParser(\"min\")\n },\n maxLength: {\n child: true,\n parse: constraintKeyParser(\"maxLength\")\n },\n minLength: {\n child: true,\n parse: constraintKeyParser(\"minLength\")\n },\n exactLength: {\n child: true,\n parse: constraintKeyParser(\"exactLength\")\n },\n before: {\n child: true,\n parse: constraintKeyParser(\"before\")\n },\n after: {\n child: true,\n parse: constraintKeyParser(\"after\")\n },\n pattern: {\n child: true,\n parse: constraintKeyParser(\"pattern\")\n },\n predicate: {\n child: true,\n parse: constraintKeyParser(\"predicate\")\n }\n },\n // leverage reduction logic from intersection and identity to ensure initial\n // parse result is reduced\n reduce: (inner, $) => \n // we cast union out of the result here since that only occurs when intersecting two sequences\n // that cannot occur when reducing a single intersection schema using unknown\n intersectIntersections({}, inner, {\n $,\n invert: false,\n pipe: false\n }),\n defaults: {\n description: node => {\n if (node.children.length === 0)\n return \"unknown\";\n if (node.structure)\n return node.structure.description;\n const childDescriptions = [];\n if (node.basis &&\n !node.prestructurals.some(r => r.impl.obviatesBasisDescription))\n childDescriptions.push(node.basis.description);\n if (node.prestructurals.length) {\n const sortedRefinementDescriptions = node.prestructurals\n .slice()\n // override alphabetization to describe min before max\n .sort((l, r) => (l.kind === \"min\" && r.kind === \"max\" ? -1 : 0))\n .map(r => r.description);\n childDescriptions.push(...sortedRefinementDescriptions);\n }\n if (node.inner.predicate) {\n childDescriptions.push(...node.inner.predicate.map(p => p.description));\n }\n return childDescriptions.join(\" and \");\n },\n expected: source => ` ◦ ${source.errors.map(e => e.expected).join(\"\\n ◦ \")}`,\n problem: ctx => `(${ctx.actual}) must be...\\n${ctx.expected}`\n },\n intersections: {\n intersection: (l, r, ctx) => intersectIntersections(l.inner, r.inner, ctx),\n ...defineRightwardIntersections(\"intersection\", (l, r, ctx) => {\n // if l is unknown, return r\n if (l.children.length === 0)\n return r;\n const { domain, proto, ...lInnerConstraints } = l.inner;\n const lBasis = proto ?? domain;\n const basis = lBasis ? intersectOrPipeNodes(lBasis, r, ctx) : r;\n return (basis instanceof Disjoint ? basis\n : l?.basis?.equals(basis) ?\n // if the basis doesn't change, return the original intesection\n l\n // given we've already precluded l being unknown, the result must\n // be an intersection with the new basis result integrated\n : l.$.node(\"intersection\", { ...lInnerConstraints, [basis.kind]: basis }, { prereduced: true }));\n })\n }\n});\nexport class IntersectionNode extends BaseRoot {\n basis = this.inner.domain ?? this.inner.proto ?? null;\n prestructurals = [];\n refinements = this.children.filter((node) => {\n if (!node.isRefinement())\n return false;\n if (includes(prestructuralKinds, node.kind))\n // mutation is fine during initialization\n this.prestructurals.push(node);\n return true;\n });\n structure = this.inner.structure;\n expression = writeIntersectionExpression(this);\n get shallowMorphs() {\n return this.inner.structure?.structuralMorph ?\n [this.inner.structure.structuralMorph]\n : [];\n }\n get defaultShortDescription() {\n return this.basis?.defaultShortDescription ?? \"present\";\n }\n innerToJsonSchema(ctx) {\n return this.children.reduce(\n // cast is required since TS doesn't know children have compatible schema prerequisites\n (schema, child) => child.isBasis() ?\n child.toJsonSchemaRecurse(ctx)\n : child.reduceJsonSchema(schema, ctx), {});\n }\n traverseAllows = (data, ctx) => this.children.every(child => child.traverseAllows(data, ctx));\n traverseApply = (data, ctx) => {\n const errorCount = ctx.currentErrorCount;\n if (this.basis) {\n this.basis.traverseApply(data, ctx);\n if (ctx.currentErrorCount > errorCount)\n return;\n }\n if (this.prestructurals.length) {\n for (let i = 0; i < this.prestructurals.length - 1; i++) {\n this.prestructurals[i].traverseApply(data, ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return;\n }\n this.prestructurals[this.prestructurals.length - 1].traverseApply(data, ctx);\n if (ctx.currentErrorCount > errorCount)\n return;\n }\n if (this.structure) {\n this.structure.traverseApply(data, ctx);\n if (ctx.currentErrorCount > errorCount)\n return;\n }\n if (this.inner.predicate) {\n for (let i = 0; i < this.inner.predicate.length - 1; i++) {\n this.inner.predicate[i].traverseApply(data, ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return;\n }\n this.inner.predicate[this.inner.predicate.length - 1].traverseApply(data, ctx);\n }\n };\n compile(js) {\n if (js.traversalKind === \"Allows\") {\n for (const child of this.children)\n js.check(child);\n js.return(true);\n return;\n }\n js.initializeErrorCount();\n if (this.basis) {\n js.check(this.basis);\n // we only have to return conditionally if this is not the last check\n if (this.children.length > 1)\n js.returnIfFail();\n }\n if (this.prestructurals.length) {\n for (let i = 0; i < this.prestructurals.length - 1; i++) {\n js.check(this.prestructurals[i]);\n js.returnIfFailFast();\n }\n js.check(this.prestructurals[this.prestructurals.length - 1]);\n if (this.structure || this.inner.predicate)\n js.returnIfFail();\n }\n if (this.structure) {\n js.check(this.structure);\n if (this.inner.predicate)\n js.returnIfFail();\n }\n if (this.inner.predicate) {\n for (let i = 0; i < this.inner.predicate.length - 1; i++) {\n js.check(this.inner.predicate[i]);\n // since predicates can be chained, we have to fail immediately\n // if one fails\n js.returnIfFail();\n }\n js.check(this.inner.predicate[this.inner.predicate.length - 1]);\n }\n }\n}\nexport const Intersection = {\n implementation,\n Node: IntersectionNode\n};\nconst writeIntersectionExpression = (node) => {\n if (node.structure?.expression)\n return node.structure.expression;\n const basisExpression = (node.basis &&\n !node.prestructurals.some(n => n.impl.obviatesBasisExpression)) ?\n node.basis.nestableExpression\n : \"\";\n const refinementsExpression = node.prestructurals\n .map(n => n.expression)\n .join(\" & \");\n const fullExpression = `${basisExpression}${basisExpression ? \" \" : \"\"}${refinementsExpression}`;\n if (fullExpression === \"Array == 0\")\n return \"[]\";\n return fullExpression || \"unknown\";\n};\nconst intersectIntersections = (l, r, ctx) => {\n const baseInner = {};\n const lBasis = l.proto ?? l.domain;\n const rBasis = r.proto ?? r.domain;\n const basisResult = lBasis ?\n rBasis ?\n intersectOrPipeNodes(lBasis, rBasis, ctx)\n : lBasis\n : rBasis;\n if (basisResult instanceof Disjoint)\n return basisResult;\n if (basisResult)\n baseInner[basisResult.kind] = basisResult;\n return intersectConstraints({\n kind: \"intersection\",\n baseInner,\n l: flattenConstraints(l),\n r: flattenConstraints(r),\n roots: [],\n ctx\n });\n};\n",
|
|
69
|
+
"import { arrayEquals, liftArray, throwParseError } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark, registeredReference } from \"../shared/registry.js\";\nimport { hasArkKind } from \"../shared/utils.js\";\nimport { BaseRoot } from \"./root.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nconst implementation = implementNode({\n kind: \"morph\",\n hasAssociatedError: false,\n keys: {\n in: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema)\n },\n morphs: {\n parse: liftArray,\n serialize: morphs => morphs.map(m => hasArkKind(m, \"root\") ? m.json : registeredReference(m))\n },\n declaredIn: {\n child: false,\n serialize: node => node.json\n },\n declaredOut: {\n child: false,\n serialize: node => node.json\n }\n },\n normalize: schema => schema,\n defaults: {\n description: node => `a morph from ${node.rawIn.description} to ${node.rawOut?.description ?? \"unknown\"}`\n },\n intersections: {\n morph: (l, r, ctx) => {\n if (!l.hasEqualMorphs(r)) {\n return throwParseError(writeMorphIntersectionMessage(l.expression, r.expression));\n }\n const inTersection = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx);\n if (inTersection instanceof Disjoint)\n return inTersection;\n const baseInner = {\n morphs: l.morphs\n };\n if (l.declaredIn || r.declaredIn) {\n const declaredIn = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx);\n // we can't treat this as a normal Disjoint since it's just declared\n // it should only happen if someone's essentially trying to create a broken type\n if (declaredIn instanceof Disjoint)\n return declaredIn.throw();\n else\n baseInner.declaredIn = declaredIn;\n }\n if (l.declaredOut || r.declaredOut) {\n const declaredOut = intersectOrPipeNodes(l.rawOut, r.rawOut, ctx);\n if (declaredOut instanceof Disjoint)\n return declaredOut.throw();\n else\n baseInner.declaredOut = declaredOut;\n }\n // in case from is a union, we need to distribute the branches\n // to can be a union as any schema is allowed\n return inTersection.distribute(inBranch => ctx.$.node(\"morph\", {\n ...baseInner,\n in: inBranch\n }), ctx.$.parseSchema);\n },\n ...defineRightwardIntersections(\"morph\", (l, r, ctx) => {\n const inTersection = l.inner.in ? intersectOrPipeNodes(l.inner.in, r, ctx) : r;\n return (inTersection instanceof Disjoint ? inTersection\n : inTersection.equals(l.inner.in) ? l\n : ctx.$.node(\"morph\", {\n ...l.inner,\n in: inTersection\n }));\n })\n }\n});\nexport class MorphNode extends BaseRoot {\n serializedMorphs = this.morphs.map(registeredReference);\n compiledMorphs = `[${this.serializedMorphs}]`;\n lastMorph = this.inner.morphs[this.inner.morphs.length - 1];\n lastMorphIfNode = hasArkKind(this.lastMorph, \"root\") ? this.lastMorph : undefined;\n introspectableIn = this.inner.in;\n introspectableOut = this.lastMorphIfNode ?\n Object.assign(this.referencesById, this.lastMorphIfNode.referencesById) &&\n this.lastMorphIfNode.rawOut\n : undefined;\n get shallowMorphs() {\n // if the morph input is a union, it should not contain any other shallow morphs\n return Array.isArray(this.inner.in?.shallowMorphs) ?\n [...this.inner.in.shallowMorphs, ...this.morphs]\n : this.morphs;\n }\n get rawIn() {\n return (this.declaredIn ?? this.inner.in?.rawIn ?? $ark.intrinsic.unknown.internal);\n }\n get rawOut() {\n return (this.declaredOut ??\n this.introspectableOut ??\n $ark.intrinsic.unknown.internal);\n }\n declareIn(declaredIn) {\n return this.$.node(\"morph\", {\n ...this.inner,\n declaredIn\n });\n }\n declareOut(declaredOut) {\n return this.$.node(\"morph\", {\n ...this.inner,\n declaredOut\n });\n }\n expression = `(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode ? \"To\" : \"Out\"}<${this.rawOut.expression}>`;\n get defaultShortDescription() {\n return this.rawIn.meta.description ?? this.rawIn.defaultShortDescription;\n }\n innerToJsonSchema(ctx) {\n return ctx.fallback.morph({\n code: \"morph\",\n base: this.rawIn.toJsonSchemaRecurse(ctx),\n out: this.introspectableOut?.toJsonSchemaRecurse(ctx) ?? null\n });\n }\n compile(js) {\n if (js.traversalKind === \"Allows\") {\n if (!this.introspectableIn)\n return;\n js.return(js.invoke(this.introspectableIn));\n return;\n }\n if (this.introspectableIn)\n js.line(js.invoke(this.introspectableIn));\n js.line(`ctx.queueMorphs(${this.compiledMorphs})`);\n }\n traverseAllows = (data, ctx) => !this.introspectableIn || this.introspectableIn.traverseAllows(data, ctx);\n traverseApply = (data, ctx) => {\n if (this.introspectableIn)\n this.introspectableIn.traverseApply(data, ctx);\n ctx.queueMorphs(this.morphs);\n };\n /** Check if the morphs of r are equal to those of this node */\n hasEqualMorphs(r) {\n return arrayEquals(this.morphs, r.morphs, {\n isEqual: (lMorph, rMorph) => lMorph === rMorph ||\n (hasArkKind(lMorph, \"root\") &&\n hasArkKind(rMorph, \"root\") &&\n lMorph.equals(rMorph))\n });\n }\n}\nexport const Morph = {\n implementation,\n Node: MorphNode\n};\nexport const writeMorphIntersectionMessage = (lDescription, rDescription) => `The intersection of distinct morphs at a single path is indeterminate:\nLeft: ${lDescription}\nRight: ${rDescription}`;\n",
|
|
70
|
+
"import { builtinConstructors, constructorExtends, domainOf, getBuiltinNameOfConstructor, hasKey, objectKindDescriptions, objectKindOrDomainOf, throwParseError } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { defaultValueSerializer, implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { isNode } from \"../shared/utils.js\";\nimport { InternalBasis } from \"./basis.js\";\nconst implementation = implementNode({\n kind: \"proto\",\n hasAssociatedError: true,\n collapsibleKey: \"proto\",\n keys: {\n proto: {\n serialize: ctor => getBuiltinNameOfConstructor(ctor) ?? defaultValueSerializer(ctor)\n },\n dateAllowsInvalid: {}\n },\n normalize: schema => {\n const normalized = typeof schema === \"string\" ? { proto: builtinConstructors[schema] }\n : typeof schema === \"function\" ?\n isNode(schema) ? schema\n : { proto: schema }\n : typeof schema.proto === \"string\" ?\n { ...schema, proto: builtinConstructors[schema.proto] }\n : schema;\n if (typeof normalized.proto !== \"function\")\n throwParseError(Proto.writeInvalidSchemaMessage(normalized.proto));\n if (hasKey(normalized, \"dateAllowsInvalid\") && normalized.proto !== Date)\n throwParseError(Proto.writeBadInvalidDateMessage(normalized.proto));\n return normalized;\n },\n applyConfig: (schema, config) => {\n if (schema.dateAllowsInvalid === undefined &&\n schema.proto === Date &&\n config.dateAllowsInvalid)\n return { ...schema, dateAllowsInvalid: true };\n return schema;\n },\n defaults: {\n description: node => node.builtinName ?\n objectKindDescriptions[node.builtinName]\n : `an instance of ${node.proto.name}`,\n actual: data => data instanceof Date && data.toString() === \"Invalid Date\" ?\n \"an invalid Date\"\n : objectKindOrDomainOf(data)\n },\n intersections: {\n proto: (l, r) => l.proto === Date && r.proto === Date ?\n // since l === r is handled by default,\n // exactly one of l or r must have allow invalid dates\n l.dateAllowsInvalid ?\n r\n : l\n : constructorExtends(l.proto, r.proto) ? l\n : constructorExtends(r.proto, l.proto) ? r\n : Disjoint.init(\"proto\", l, r),\n domain: (proto, domain) => domain.domain === \"object\" ?\n proto\n : Disjoint.init(\"domain\", $ark.intrinsic.object.internal, domain)\n }\n});\nexport class ProtoNode extends InternalBasis {\n builtinName = getBuiltinNameOfConstructor(this.proto);\n serializedConstructor = this.json.proto;\n requiresInvalidDateCheck = this.proto === Date && !this.dateAllowsInvalid;\n traverseAllows = this.requiresInvalidDateCheck ?\n data => data instanceof Date && data.toString() !== \"Invalid Date\"\n : data => data instanceof this.proto;\n compiledCondition = `data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck ? ` && data.toString() !== \"Invalid Date\"` : \"\"}`;\n compiledNegation = `!(${this.compiledCondition})`;\n innerToJsonSchema(ctx) {\n switch (this.builtinName) {\n case \"Array\":\n return {\n type: \"array\"\n };\n case \"Date\":\n return (ctx.fallback.date?.({ code: \"date\", base: {} }) ??\n ctx.fallback.proto({ code: \"proto\", base: {}, proto: this.proto }));\n default:\n return ctx.fallback.proto({\n code: \"proto\",\n base: {},\n proto: this.proto\n });\n }\n }\n expression = this.dateAllowsInvalid ? \"Date | InvalidDate\" : this.proto.name;\n get nestableExpression() {\n return this.dateAllowsInvalid ? `(${this.expression})` : this.expression;\n }\n domain = \"object\";\n get defaultShortDescription() {\n return this.description;\n }\n}\nexport const Proto = {\n implementation,\n Node: ProtoNode,\n writeBadInvalidDateMessage: (actual) => `dateAllowsInvalid may only be specified with constructor Date (was ${actual.name})`,\n writeInvalidSchemaMessage: (actual) => `instanceOf operand must be a function (was ${domainOf(actual)})`\n};\n",
|
|
71
|
+
"import { appendUnique, arrayEquals, domainDescriptions, flatMorph, groupBy, hasKey, isArray, jsTypeOfDescriptions, printable, range, throwParseError, unset } from \"@ark/util\";\nimport { compileLiteralPropAccess, compileSerializedValue } from \"../shared/compile.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectNodesRoot, intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark, registeredReference } from \"../shared/registry.js\";\nimport { Traversal } from \"../shared/traversal.js\";\nimport { hasArkKind } from \"../shared/utils.js\";\nimport { BaseRoot } from \"./root.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nconst implementation = implementNode({\n kind: \"union\",\n hasAssociatedError: true,\n collapsibleKey: \"branches\",\n keys: {\n ordered: {},\n branches: {\n child: true,\n parse: (schema, ctx) => {\n const branches = [];\n for (const branchSchema of schema) {\n const branchNodes = hasArkKind(branchSchema, \"root\") ?\n branchSchema.branches\n : ctx.$.parseSchema(branchSchema).branches;\n for (const node of branchNodes) {\n if (node.hasKind(\"morph\")) {\n const matchingMorphIndex = branches.findIndex(matching => matching.hasKind(\"morph\") && matching.hasEqualMorphs(node));\n if (matchingMorphIndex === -1)\n branches.push(node);\n else {\n const matchingMorph = branches[matchingMorphIndex];\n branches[matchingMorphIndex] = ctx.$.node(\"morph\", {\n ...matchingMorph.inner,\n in: matchingMorph.rawIn.rawOr(node.rawIn)\n });\n }\n }\n else\n branches.push(node);\n }\n }\n if (!ctx.def.ordered)\n branches.sort((l, r) => (l.hash < r.hash ? -1 : 1));\n return branches;\n }\n }\n },\n normalize: schema => (isArray(schema) ? { branches: schema } : schema),\n reduce: (inner, $) => {\n const reducedBranches = reduceBranches(inner);\n if (reducedBranches.length === 1)\n return reducedBranches[0];\n if (reducedBranches.length === inner.branches.length)\n return;\n return $.node(\"union\", {\n ...inner,\n branches: reducedBranches\n }, { prereduced: true });\n },\n defaults: {\n description: node => node.distribute(branch => branch.description, describeBranches),\n expected: ctx => {\n const byPath = groupBy(ctx.errors, \"propString\");\n const pathDescriptions = Object.entries(byPath).map(([path, errors]) => {\n const branchesAtPath = [];\n for (const errorAtPath of errors)\n appendUnique(branchesAtPath, errorAtPath.expected);\n const expected = describeBranches(branchesAtPath);\n // if there are multiple actual descriptions that differ,\n // just fall back to printable, which is the most specific\n const actual = errors.every(e => e.actual === errors[0].actual) ?\n errors[0].actual\n : printable(errors[0].data);\n return `${path && `${path} `}must be ${expected}${actual && ` (was ${actual})`}`;\n });\n return describeBranches(pathDescriptions);\n },\n problem: ctx => ctx.expected,\n message: ctx => {\n if (ctx.problem[0] === \"[\") {\n // clarify paths like [1], [0][1], and [\"key!\"] that could be confusing\n return `value at ${ctx.problem}`;\n }\n return ctx.problem;\n }\n },\n intersections: {\n union: (l, r, ctx) => {\n if (l.isNever !== r.isNever) {\n // if exactly one operand is never, we can use it to discriminate based on presence\n return Disjoint.init(\"presence\", l, r);\n }\n let resultBranches;\n if (l.ordered) {\n if (r.ordered) {\n throwParseError(writeOrderedIntersectionMessage(l.expression, r.expression));\n }\n resultBranches = intersectBranches(r.branches, l.branches, ctx);\n if (resultBranches instanceof Disjoint)\n resultBranches.invert();\n }\n else\n resultBranches = intersectBranches(l.branches, r.branches, ctx);\n if (resultBranches instanceof Disjoint)\n return resultBranches;\n return ctx.$.parseSchema(l.ordered || r.ordered ?\n {\n branches: resultBranches,\n ordered: true\n }\n : { branches: resultBranches });\n },\n ...defineRightwardIntersections(\"union\", (l, r, ctx) => {\n const branches = intersectBranches(l.branches, [r], ctx);\n if (branches instanceof Disjoint)\n return branches;\n if (branches.length === 1)\n return branches[0];\n return ctx.$.parseSchema(l.ordered ? { branches, ordered: true } : { branches });\n })\n }\n});\nexport class UnionNode extends BaseRoot {\n isBoolean = this.branches.length === 2 &&\n this.branches[0].hasUnit(false) &&\n this.branches[1].hasUnit(true);\n get branchGroups() {\n const branchGroups = [];\n let firstBooleanIndex = -1;\n for (const branch of this.branches) {\n if (branch.hasKind(\"unit\") && branch.domain === \"boolean\") {\n if (firstBooleanIndex === -1) {\n firstBooleanIndex = branchGroups.length;\n branchGroups.push(branch);\n }\n else\n branchGroups[firstBooleanIndex] = $ark.intrinsic.boolean;\n continue;\n }\n branchGroups.push(branch);\n }\n return branchGroups;\n }\n unitBranches = this.branches.filter((n) => n.rawIn.hasKind(\"unit\"));\n discriminant = this.discriminate();\n discriminantJson = this.discriminant ? discriminantToJson(this.discriminant) : null;\n expression = this.distribute(n => n.nestableExpression, expressBranches);\n createBranchedOptimisticRootApply() {\n return (data, onFail) => {\n const optimisticResult = this.traverseOptimistic(data);\n if (optimisticResult !== unset)\n return optimisticResult;\n const ctx = new Traversal(data, this.$.resolvedConfig);\n this.traverseApply(data, ctx);\n return ctx.finalize(onFail);\n };\n }\n get shallowMorphs() {\n return this.branches.reduce((morphs, branch) => appendUnique(morphs, branch.shallowMorphs), []);\n }\n get defaultShortDescription() {\n return this.distribute(branch => branch.defaultShortDescription, describeBranches);\n }\n innerToJsonSchema(ctx) {\n // special case to simplify { const: true } | { const: false }\n // to the canonical JSON Schema representation { type: \"boolean\" }\n if (this.branchGroups.length === 1 &&\n this.branchGroups[0].equals($ark.intrinsic.boolean))\n return { type: \"boolean\" };\n const jsonSchemaBranches = this.branchGroups.map(group => group.toJsonSchemaRecurse(ctx));\n if (jsonSchemaBranches.every((branch) => \n // iff all branches are pure unit values with no metadata,\n // we can simplify the representation to an enum\n Object.keys(branch).length === 1 && hasKey(branch, \"const\"))) {\n return {\n enum: jsonSchemaBranches.map(branch => branch.const)\n };\n }\n return {\n anyOf: jsonSchemaBranches\n };\n }\n traverseAllows = (data, ctx) => this.branches.some(b => b.traverseAllows(data, ctx));\n traverseApply = (data, ctx) => {\n const errors = [];\n for (let i = 0; i < this.branches.length; i++) {\n ctx.pushBranch();\n this.branches[i].traverseApply(data, ctx);\n if (!ctx.hasError()) {\n if (this.branches[i].includesTransform)\n return ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs);\n return ctx.popBranch();\n }\n errors.push(ctx.popBranch().error);\n }\n ctx.errorFromNodeContext({ code: \"union\", errors, meta: this.meta });\n };\n traverseOptimistic = (data) => {\n for (let i = 0; i < this.branches.length; i++) {\n const branch = this.branches[i];\n if (branch.traverseAllows(data)) {\n if (branch.contextFreeMorph)\n return branch.contextFreeMorph(data);\n // if we're calling this function and the matching branch didn't have\n // a context-free morph, it shouldn't have morphs at all\n return data;\n }\n }\n return unset;\n };\n compile(js) {\n if (!this.discriminant ||\n // if we have a union of two units like `boolean`, the\n // undiscriminated compilation will be just as fast\n (this.unitBranches.length === this.branches.length &&\n this.branches.length === 2))\n return this.compileIndiscriminable(js);\n // we need to access the path as optional so we don't throw if it isn't present\n let condition = this.discriminant.optionallyChainedPropString;\n if (this.discriminant.kind === \"domain\")\n condition = `typeof ${condition} === \"object\" ? ${condition} === null ? \"null\" : \"object\" : typeof ${condition} === \"function\" ? \"object\" : typeof ${condition}`;\n const cases = this.discriminant.cases;\n const caseKeys = Object.keys(cases);\n const { optimistic } = js;\n // only the first layer can be optimistic\n js.optimistic = false;\n js.block(`switch(${condition})`, () => {\n for (const k in cases) {\n const v = cases[k];\n const caseCondition = k === \"default\" ? k : `case ${k}`;\n let caseResult;\n if (v === true)\n caseResult = optimistic ? \"data\" : \"true\";\n else if (optimistic) {\n if (v.rootApplyStrategy === \"branchedOptimistic\")\n caseResult = js.invoke(v, { kind: \"Optimistic\" });\n else if (v.contextFreeMorph)\n caseResult = `${js.invoke(v)} ? ${registeredReference(v.contextFreeMorph)}(data) : \"${unset}\"`;\n else\n caseResult = `${js.invoke(v)} ? data : \"${unset}\"`;\n }\n else\n caseResult = js.invoke(v);\n js.line(`${caseCondition}: return ${caseResult}`);\n }\n return js;\n });\n if (js.traversalKind === \"Allows\") {\n js.return(optimistic ? `\"${unset}\"` : false);\n return;\n }\n const expected = describeBranches(this.discriminant.kind === \"domain\" ?\n caseKeys.map(k => {\n const jsTypeOf = k.slice(1, -1);\n return jsTypeOf === \"function\" ?\n domainDescriptions.object\n : domainDescriptions[jsTypeOf];\n })\n : caseKeys);\n const serializedPathSegments = this.discriminant.path.map(k => typeof k === \"symbol\" ? registeredReference(k) : JSON.stringify(k));\n const serializedExpected = JSON.stringify(expected);\n const serializedActual = this.discriminant.kind === \"domain\" ?\n `${serializedTypeOfDescriptions}[${condition}]`\n : `${serializedPrintable}(${condition})`;\n js.line(`ctx.errorFromNodeContext({\n\tcode: \"predicate\",\n\texpected: ${serializedExpected},\n\tactual: ${serializedActual},\n\trelativePath: [${serializedPathSegments}],\n\tmeta: ${this.compiledMeta}\n})`);\n }\n compileIndiscriminable(js) {\n if (js.traversalKind === \"Apply\") {\n js.const(\"errors\", \"[]\");\n for (const branch of this.branches) {\n js.line(\"ctx.pushBranch()\")\n .line(js.invoke(branch))\n .if(\"!ctx.hasError()\", () => js.return(branch.includesTransform ?\n \"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)\"\n : \"ctx.popBranch()\"))\n .line(\"errors.push(ctx.popBranch().error)\");\n }\n js.line(`ctx.errorFromNodeContext({ code: \"union\", errors, meta: ${this.compiledMeta} })`);\n }\n else {\n const { optimistic } = js;\n // only the first layer can be optimistic\n js.optimistic = false;\n for (const branch of this.branches) {\n js.if(`${js.invoke(branch)}`, () => js.return(optimistic ?\n branch.contextFreeMorph ?\n `${registeredReference(branch.contextFreeMorph)}(data)`\n : \"data\"\n : true));\n }\n js.return(optimistic ? `\"${unset}\"` : false);\n }\n }\n get nestableExpression() {\n // avoid adding unnecessary parentheses around boolean since it's\n // already collapsed to a single keyword\n return this.isBoolean ? \"boolean\" : `(${this.expression})`;\n }\n discriminate() {\n if (this.branches.length < 2 || this.isCyclic)\n return null;\n if (this.unitBranches.length === this.branches.length) {\n const cases = flatMorph(this.unitBranches, (i, n) => [\n `${n.rawIn.serializedValue}`,\n n.hasKind(\"morph\") ? n : true\n ]);\n return {\n kind: \"unit\",\n path: [],\n optionallyChainedPropString: \"data\",\n cases\n };\n }\n const candidates = [];\n for (let lIndex = 0; lIndex < this.branches.length - 1; lIndex++) {\n const l = this.branches[lIndex];\n for (let rIndex = lIndex + 1; rIndex < this.branches.length; rIndex++) {\n const r = this.branches[rIndex];\n const result = intersectNodesRoot(l.rawIn, r.rawIn, l.$);\n if (!(result instanceof Disjoint))\n continue;\n for (const entry of result) {\n if (!entry.kind || entry.optional)\n continue;\n let lSerialized;\n let rSerialized;\n if (entry.kind === \"domain\") {\n const lValue = entry.l;\n const rValue = entry.r;\n lSerialized = `\"${typeof lValue === \"string\" ? lValue : lValue.domain}\"`;\n rSerialized = `\"${typeof rValue === \"string\" ? rValue : rValue.domain}\"`;\n }\n else if (entry.kind === \"unit\") {\n lSerialized = entry.l.serializedValue;\n rSerialized = entry.r.serializedValue;\n }\n else\n continue;\n const matching = candidates.find(d => arrayEquals(d.path, entry.path) && d.kind === entry.kind);\n if (!matching) {\n candidates.push({\n kind: entry.kind,\n cases: {\n [lSerialized]: {\n branchIndices: [lIndex],\n condition: entry.l\n },\n [rSerialized]: {\n branchIndices: [rIndex],\n condition: entry.r\n }\n },\n path: entry.path\n });\n }\n else {\n if (matching.cases[lSerialized]) {\n matching.cases[lSerialized].branchIndices = appendUnique(matching.cases[lSerialized].branchIndices, lIndex);\n }\n else {\n matching.cases[lSerialized] ??= {\n branchIndices: [lIndex],\n condition: entry.l\n };\n }\n if (matching.cases[rSerialized]) {\n matching.cases[rSerialized].branchIndices = appendUnique(matching.cases[rSerialized].branchIndices, rIndex);\n }\n else {\n matching.cases[rSerialized] ??= {\n branchIndices: [rIndex],\n condition: entry.r\n };\n }\n }\n }\n }\n }\n const viableCandidates = this.ordered ?\n viableOrderedCandidates(candidates, this.branches)\n : candidates;\n if (!viableCandidates.length)\n return null;\n const ctx = createCaseResolutionContext(viableCandidates, this);\n const cases = {};\n for (const k in ctx.best.cases) {\n const resolution = resolveCase(ctx, k);\n if (resolution === null) {\n cases[k] = true;\n continue;\n }\n // if all the branches ended up back in pruned, we'd loop if we continued\n // so just bail out- nothing left to discriminate\n if (resolution.length === this.branches.length)\n return null;\n if (this.ordered) {\n // ensure the original order of the pruned branches is preserved\n resolution.sort((l, r) => l.originalIndex - r.originalIndex);\n }\n const branches = resolution.map(entry => entry.branch);\n const caseNode = branches.length === 1 ?\n branches[0]\n : this.$.node(\"union\", this.ordered ? { branches, ordered: true } : branches);\n Object.assign(this.referencesById, caseNode.referencesById);\n cases[k] = caseNode;\n }\n if (ctx.defaultEntries.length) {\n // we don't have to worry about order here as it is always preserved\n // within defaultEntries\n const branches = ctx.defaultEntries.map(entry => entry.branch);\n cases.default = this.$.node(\"union\", this.ordered ? { branches, ordered: true } : branches, {\n prereduced: true\n });\n Object.assign(this.referencesById, cases.default.referencesById);\n }\n return Object.assign(ctx.location, {\n cases\n });\n }\n}\nconst createCaseResolutionContext = (viableCandidates, node) => {\n const ordered = viableCandidates.sort((l, r) => l.path.length === r.path.length ?\n Object.keys(r.cases).length - Object.keys(l.cases).length\n // prefer shorter paths first\n : l.path.length - r.path.length);\n const best = ordered[0];\n const location = {\n kind: best.kind,\n path: best.path,\n optionallyChainedPropString: optionallyChainPropString(best.path)\n };\n const defaultEntries = node.branches.map((branch, originalIndex) => ({\n originalIndex,\n branch\n }));\n return {\n best,\n location,\n defaultEntries,\n node\n };\n};\nconst resolveCase = (ctx, key) => {\n const caseCtx = ctx.best.cases[key];\n const discriminantNode = discriminantCaseToNode(caseCtx.condition, ctx.location.path, ctx.node.$);\n let resolvedEntries = [];\n const nextDefaults = [];\n for (let i = 0; i < ctx.defaultEntries.length; i++) {\n const entry = ctx.defaultEntries[i];\n if (caseCtx.branchIndices.includes(entry.originalIndex)) {\n const pruned = pruneDiscriminant(ctx.node.branches[entry.originalIndex], ctx.location);\n if (pruned === null) {\n // if any branch of the union has no constraints (i.e. is\n // unknown), the others won't affect the resolution type, but could still\n // remove additional cases from defaultEntries\n resolvedEntries = null;\n }\n else {\n resolvedEntries?.push({\n originalIndex: entry.originalIndex,\n branch: pruned\n });\n }\n }\n else if (\n // we shouldn't need a special case for alias to avoid the below\n // once alias resolution issues are improved:\n // https://github.com/arktypeio/arktype/issues/1026\n entry.branch.hasKind(\"alias\") &&\n discriminantNode.hasKind(\"domain\") &&\n discriminantNode.domain === \"object\")\n resolvedEntries?.push(entry);\n else {\n if (entry.branch.rawIn.overlaps(discriminantNode)) {\n // include cases where an object not including the\n // discriminant path might have that value present as an undeclared key\n const overlapping = pruneDiscriminant(entry.branch, ctx.location);\n resolvedEntries?.push({\n originalIndex: entry.originalIndex,\n branch: overlapping\n });\n }\n nextDefaults.push(entry);\n }\n }\n ctx.defaultEntries = nextDefaults;\n return resolvedEntries;\n};\nconst viableOrderedCandidates = (candidates, originalBranches) => {\n const viableCandidates = candidates.filter(candidate => {\n const caseGroups = Object.values(candidate.cases).map(caseCtx => caseCtx.branchIndices);\n // compare each group against all subsequent groups.\n for (let i = 0; i < caseGroups.length - 1; i++) {\n const currentGroup = caseGroups[i];\n for (let j = i + 1; j < caseGroups.length; j++) {\n const nextGroup = caseGroups[j];\n // for each group pair, check for branches whose order was reversed\n for (const currentIndex of currentGroup) {\n for (const nextIndex of nextGroup) {\n if (currentIndex > nextIndex) {\n if (originalBranches[currentIndex].overlaps(originalBranches[nextIndex])) {\n // if the order was not preserved and the branches overlap,\n // this is not a viable discriminant as it cannot guarantee the same behavior\n return false;\n }\n }\n }\n }\n }\n }\n // branch groups preserved order for non-disjoint pairs and is viable\n return true;\n });\n return viableCandidates;\n};\nconst discriminantCaseToNode = (caseDiscriminant, path, $) => {\n let node = caseDiscriminant === \"undefined\" ? $.node(\"unit\", { unit: undefined })\n : caseDiscriminant === \"null\" ? $.node(\"unit\", { unit: null })\n : caseDiscriminant === \"boolean\" ? $.units([true, false])\n : caseDiscriminant;\n for (let i = path.length - 1; i >= 0; i--) {\n const key = path[i];\n node = $.node(\"intersection\", typeof key === \"number\" ?\n {\n proto: \"Array\",\n // create unknown for preceding elements (could be optimized with safe imports)\n sequence: [...range(key).map(_ => ({})), node]\n }\n : {\n domain: \"object\",\n required: [{ key, value: node }]\n });\n }\n return node;\n};\nconst optionallyChainPropString = (path) => path.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), \"data\");\nconst serializedTypeOfDescriptions = registeredReference(jsTypeOfDescriptions);\nconst serializedPrintable = registeredReference(printable);\nexport const Union = {\n implementation,\n Node: UnionNode\n};\nconst discriminantToJson = (discriminant) => ({\n kind: discriminant.kind,\n path: discriminant.path.map(k => typeof k === \"string\" ? k : compileSerializedValue(k)),\n cases: flatMorph(discriminant.cases, (k, node) => [\n k,\n node === true ? node\n : node.hasKind(\"union\") && node.discriminantJson ? node.discriminantJson\n : node.json\n ])\n});\nconst describeExpressionOptions = {\n delimiter: \" | \",\n finalDelimiter: \" | \"\n};\nconst expressBranches = (expressions) => describeBranches(expressions, describeExpressionOptions);\nexport const describeBranches = (descriptions, opts) => {\n const delimiter = opts?.delimiter ?? \", \";\n const finalDelimiter = opts?.finalDelimiter ?? \" or \";\n if (descriptions.length === 0)\n return \"never\";\n if (descriptions.length === 1)\n return descriptions[0];\n if ((descriptions.length === 2 &&\n descriptions[0] === \"false\" &&\n descriptions[1] === \"true\") ||\n (descriptions[0] === \"true\" && descriptions[1] === \"false\"))\n return \"boolean\";\n // keep track of seen descriptions to avoid duplication\n const seen = {};\n const unique = descriptions.filter(s => (seen[s] ? false : (seen[s] = true)));\n const last = unique.pop();\n return `${unique.join(delimiter)}${unique.length ? finalDelimiter : \"\"}${last}`;\n};\nexport const intersectBranches = (l, r, ctx) => {\n // If the corresponding r branch is identified as a subtype of an l branch, the\n // value at rIndex is set to null so we can avoid including previous/future\n // intersections in the reduced result.\n const batchesByR = r.map(() => []);\n for (let lIndex = 0; lIndex < l.length; lIndex++) {\n let candidatesByR = {};\n for (let rIndex = 0; rIndex < r.length; rIndex++) {\n if (batchesByR[rIndex] === null) {\n // rBranch is a subtype of an lBranch and\n // will not yield any distinct intersection\n continue;\n }\n if (l[lIndex].equals(r[rIndex])) {\n // Combination of subtype and supertype cases\n batchesByR[rIndex] = null;\n candidatesByR = {};\n break;\n }\n const branchIntersection = intersectOrPipeNodes(l[lIndex], r[rIndex], ctx);\n if (branchIntersection instanceof Disjoint) {\n // Doesn't tell us anything useful about their relationships\n // with other branches\n continue;\n }\n if (branchIntersection.equals(l[lIndex])) {\n // If the current l branch is a subtype of r, intersections\n // with previous and remaining branches of r won't lead to\n // distinct intersections.\n batchesByR[rIndex].push(l[lIndex]);\n candidatesByR = {};\n break;\n }\n if (branchIntersection.equals(r[rIndex])) {\n // If the current r branch is a subtype of l, set its batch to\n // null, removing any previous intersections and preventing any\n // of its remaining intersections from being computed.\n batchesByR[rIndex] = null;\n }\n else {\n // If neither l nor r is a subtype of the other, add their\n // intersection as a candidate (could still be removed if it is\n // determined l or r is a subtype of a remaining branch).\n candidatesByR[rIndex] = branchIntersection;\n }\n }\n for (const rIndex in candidatesByR) {\n // batchesByR at rIndex should never be null if it is in candidatesByR\n batchesByR[rIndex][lIndex] = candidatesByR[rIndex];\n }\n }\n // Compile the reduced intersection result, including:\n // \t\t1. Remaining candidates resulting from distinct intersections or strict subtypes of r\n // \t\t2. Original r branches corresponding to indices with a null batch (subtypes of l)\n const resultBranches = batchesByR.flatMap(\n // ensure unions returned from branchable intersections like sequence are flattened\n (batch, i) => batch?.flatMap(branch => branch.branches) ?? r[i]);\n return resultBranches.length === 0 ?\n Disjoint.init(\"union\", l, r)\n : resultBranches;\n};\nexport const reduceBranches = ({ branches, ordered }) => {\n if (branches.length < 2)\n return branches;\n const uniquenessByIndex = branches.map(() => true);\n for (let i = 0; i < branches.length; i++) {\n for (let j = i + 1; j < branches.length && uniquenessByIndex[i] && uniquenessByIndex[j]; j++) {\n if (branches[i].equals(branches[j])) {\n // if the two branches are equal, only \"j\" is marked as\n // redundant so at least one copy could still be included in\n // the final set of branches.\n uniquenessByIndex[j] = false;\n continue;\n }\n const intersection = intersectNodesRoot(branches[i].rawIn, branches[j].rawIn, branches[0].$);\n if (intersection instanceof Disjoint)\n continue;\n if (!ordered)\n assertDeterminateOverlap(branches[i], branches[j]);\n if (intersection.equals(branches[i].rawIn)) {\n // preserve ordered branches that are a subtype of a subsequent branch\n uniquenessByIndex[i] = !!ordered;\n }\n else if (intersection.equals(branches[j].rawIn))\n uniquenessByIndex[j] = false;\n }\n }\n return branches.filter((_, i) => uniquenessByIndex[i]);\n};\nconst assertDeterminateOverlap = (l, r) => {\n if (!l.includesTransform && !r.includesTransform)\n return;\n if (!arrayEquals(l.shallowMorphs, r.shallowMorphs)) {\n throwParseError(writeIndiscriminableMorphMessage(l.expression, r.expression));\n }\n if (!arrayEquals(l.flatMorphs, r.flatMorphs, {\n isEqual: (l, r) => l.propString === r.propString &&\n (l.node.hasKind(\"morph\") && r.node.hasKind(\"morph\") ?\n l.node.hasEqualMorphs(r.node)\n : l.node.hasKind(\"intersection\") && r.node.hasKind(\"intersection\") ?\n l.node.structure?.structuralMorphRef ===\n r.node.structure?.structuralMorphRef\n : false)\n })) {\n throwParseError(writeIndiscriminableMorphMessage(l.expression, r.expression));\n }\n};\nexport const pruneDiscriminant = (discriminantBranch, discriminantCtx) => discriminantBranch.transform((nodeKind, inner) => {\n if (nodeKind === \"domain\" || nodeKind === \"unit\")\n return null;\n return inner;\n}, {\n shouldTransform: (node, ctx) => {\n // safe to cast here as index nodes are never discriminants\n const propString = optionallyChainPropString(ctx.path);\n if (!discriminantCtx.optionallyChainedPropString.startsWith(propString))\n return false;\n if (node.hasKind(\"domain\") && node.domain === \"object\")\n // if we've already checked a path at least as long as the current one,\n // we don't need to revalidate that we're in an object\n return true;\n if ((node.hasKind(\"domain\") || discriminantCtx.kind === \"unit\") &&\n propString === discriminantCtx.optionallyChainedPropString)\n // if the discriminant has already checked the domain at the current path\n // (or a unit literal, implying a domain), we don't need to recheck it\n return true;\n // we don't need to recurse into index nodes as they will never\n // have a required path therefore can't be used to discriminate\n return node.children.length !== 0 && node.kind !== \"index\";\n }\n});\nexport const writeIndiscriminableMorphMessage = (lDescription, rDescription) => `An unordered union of a type including a morph and a type with overlapping input is indeterminate:\nLeft: ${lDescription}\nRight: ${rDescription}`;\nexport const writeOrderedIntersectionMessage = (lDescription, rDescription) => `The intersection of two ordered unions is indeterminate:\nLeft: ${lDescription}\nRight: ${rDescription}`;\n",
|
|
72
|
+
"import { domainDescriptions, domainOf, printable } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { defaultValueSerializer, implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { InternalBasis } from \"./basis.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nconst implementation = implementNode({\n kind: \"unit\",\n hasAssociatedError: true,\n keys: {\n unit: {\n preserveUndefined: true,\n serialize: schema => schema instanceof Date ?\n schema.toISOString()\n : defaultValueSerializer(schema)\n }\n },\n normalize: schema => schema,\n defaults: {\n description: node => printable(node.unit),\n problem: ({ expected, actual }) => `${expected === actual ? `must be reference equal to ${expected} (serialized to the same value)` : `must be ${expected} (was ${actual})`}`\n },\n intersections: {\n unit: (l, r) => Disjoint.init(\"unit\", l, r),\n ...defineRightwardIntersections(\"unit\", (l, r) => {\n if (r.allows(l.unit))\n return l;\n // will always be a disjoint at this point, but we try to use\n // a domain Disjoint if possible since it's better for discrimination\n const rBasis = r.hasKind(\"intersection\") ? r.basis : r;\n if (rBasis) {\n const rDomain = rBasis.hasKind(\"domain\") ? rBasis : $ark.intrinsic.object;\n if (l.domain !== rDomain.domain) {\n const lDomainDisjointValue = (l.domain === \"undefined\" ||\n l.domain === \"null\" ||\n l.domain === \"boolean\") ?\n l.domain\n : $ark.intrinsic[l.domain];\n return Disjoint.init(\"domain\", lDomainDisjointValue, rDomain);\n }\n }\n return Disjoint.init(\"assignability\", l, r.hasKind(\"intersection\") ?\n r.children.find(rConstraint => !rConstraint.allows(l.unit))\n : r);\n })\n }\n});\nexport class UnitNode extends InternalBasis {\n compiledValue = this.json.unit;\n serializedValue = typeof this.unit === \"string\" || this.unit instanceof Date ?\n JSON.stringify(this.compiledValue)\n : `${this.compiledValue}`;\n compiledCondition = compileEqualityCheck(this.unit, this.serializedValue);\n compiledNegation = compileEqualityCheck(this.unit, this.serializedValue, \"negated\");\n expression = printable(this.unit);\n domain = domainOf(this.unit);\n get defaultShortDescription() {\n return this.domain === \"object\" ?\n domainDescriptions.object\n : this.description;\n }\n innerToJsonSchema(ctx) {\n return (\n // this is the more standard JSON schema representation, especially for Open API\n this.unit === null ? { type: \"null\" }\n : $ark.intrinsic.jsonPrimitive.allows(this.unit) ? { const: this.unit }\n : ctx.fallback.unit({ code: \"unit\", base: {}, unit: this.unit }));\n }\n traverseAllows = this.unit instanceof Date ?\n data => data instanceof Date && data.toISOString() === this.compiledValue\n : Number.isNaN(this.unit) ? data => Number.isNaN(data)\n : data => data === this.unit;\n}\nexport const Unit = {\n implementation,\n Node: UnitNode\n};\nconst compileEqualityCheck = (unit, serializedValue, negated) => {\n if (unit instanceof Date) {\n const condition = `data instanceof Date && data.toISOString() === ${serializedValue}`;\n return negated ? `!(${condition})` : condition;\n }\n if (Number.isNaN(unit))\n return `${negated ? \"!\" : \"\"}Number.isNaN(data)`;\n return `data ${negated ? \"!\" : \"=\"}== ${serializedValue}`;\n};\n",
|
|
73
|
+
"import { append, printable, stringAndSymbolicEntriesOf, throwParseError } from \"@ark/util\";\nimport { BaseConstraint } from \"../constraint.js\";\nimport { flatRef } from \"../node.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nconst implementation = implementNode({\n kind: \"index\",\n hasAssociatedError: false,\n intersectionIsOpen: true,\n keys: {\n signature: {\n child: true,\n parse: (schema, ctx) => {\n const key = ctx.$.parseSchema(schema);\n if (!key.extends($ark.intrinsic.key)) {\n return throwParseError(writeInvalidPropertyKeyMessage(key.expression));\n }\n const enumerableBranches = key.branches.filter(b => b.hasKind(\"unit\"));\n if (enumerableBranches.length) {\n return throwParseError(writeEnumerableIndexBranches(enumerableBranches.map(b => printable(b.unit))));\n }\n return key;\n }\n },\n value: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema)\n }\n },\n normalize: schema => schema,\n defaults: {\n description: node => `[${node.signature.expression}]: ${node.value.description}`\n },\n intersections: {\n index: (l, r, ctx) => {\n if (l.signature.equals(r.signature)) {\n const valueIntersection = intersectOrPipeNodes(l.value, r.value, ctx);\n const value = valueIntersection instanceof Disjoint ?\n $ark.intrinsic.never.internal\n : valueIntersection;\n return ctx.$.node(\"index\", { signature: l.signature, value });\n }\n // if r constrains all of l's keys to a subtype of l's value, r is a subtype of l\n if (l.signature.extends(r.signature) && l.value.subsumes(r.value))\n return r;\n // if l constrains all of r's keys to a subtype of r's value, l is a subtype of r\n if (r.signature.extends(l.signature) && r.value.subsumes(l.value))\n return l;\n // other relationships between index signatures can't be generally reduced\n return null;\n }\n }\n});\nexport class IndexNode extends BaseConstraint {\n impliedBasis = $ark.intrinsic.object.internal;\n expression = `[${this.signature.expression}]: ${this.value.expression}`;\n flatRefs = append(this.value.flatRefs.map(ref => flatRef([this.signature, ...ref.path], ref.node)), flatRef([this.signature], this.value));\n traverseAllows = (data, ctx) => stringAndSymbolicEntriesOf(data).every(entry => {\n if (this.signature.traverseAllows(entry[0], ctx)) {\n return traverseKey(entry[0], () => this.value.traverseAllows(entry[1], ctx), ctx);\n }\n return true;\n });\n traverseApply = (data, ctx) => {\n for (const entry of stringAndSymbolicEntriesOf(data)) {\n if (this.signature.traverseAllows(entry[0], ctx)) {\n traverseKey(entry[0], () => this.value.traverseApply(entry[1], ctx), ctx);\n }\n }\n };\n _transform(mapper, ctx) {\n ctx.path.push(this.signature);\n const result = super._transform(mapper, ctx);\n ctx.path.pop();\n return result;\n }\n compile() {\n // this is currently handled by StructureNode\n }\n}\nexport const Index = {\n implementation,\n Node: IndexNode\n};\nexport const writeEnumerableIndexBranches = (keys) => `Index keys ${keys.join(\", \")} should be specified as named props.`;\nexport const writeInvalidPropertyKeyMessage = (indexSchema) => `Indexed key definition '${indexSchema}' must be a string or symbol`;\n",
|
|
74
|
+
"import { compileObjectLiteral, implementNode } from \"../shared/implement.js\";\nimport { BaseProp, intersectProps } from \"./prop.js\";\nconst implementation = implementNode({\n kind: \"required\",\n hasAssociatedError: true,\n intersectionIsOpen: true,\n keys: {\n key: {},\n value: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema)\n }\n },\n normalize: schema => schema,\n defaults: {\n description: node => `${node.compiledKey}: ${node.value.description}`,\n expected: ctx => ctx.missingValueDescription,\n actual: () => \"missing\"\n },\n intersections: {\n required: intersectProps,\n optional: intersectProps\n }\n});\nexport class RequiredNode extends BaseProp {\n expression = `${this.compiledKey}: ${this.value.expression}`;\n errorContext = Object.freeze({\n code: \"required\",\n missingValueDescription: this.value.defaultShortDescription,\n relativePath: [this.key],\n meta: this.meta\n });\n compiledErrorContext = compileObjectLiteral(this.errorContext);\n}\nexport const Required = {\n implementation,\n Node: RequiredNode\n};\n",
|
|
75
|
+
"import { append, conflatenate, printable, throwInternalError, throwParseError } from \"@ark/util\";\nimport { BaseConstraint } from \"../constraint.js\";\nimport { appendUniqueFlatRefs, flatRef } from \"../node.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { defaultValueSerializer, implementNode } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark, registeredReference } from \"../shared/registry.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nimport { assertDefaultValueAssignability, computeDefaultValueMorph } from \"./optional.js\";\nimport { writeDefaultIntersectionMessage } from \"./prop.js\";\nconst implementation = implementNode({\n kind: \"sequence\",\n hasAssociatedError: false,\n collapsibleKey: \"variadic\",\n keys: {\n prefix: {\n child: true,\n parse: (schema, ctx) => {\n // empty affixes are omitted. an empty array should therefore\n // be specified as `{ proto: Array, length: 0 }`\n if (schema.length === 0)\n return undefined;\n return schema.map(element => ctx.$.parseSchema(element));\n }\n },\n optionals: {\n child: true,\n parse: (schema, ctx) => {\n if (schema.length === 0)\n return undefined;\n return schema.map(element => ctx.$.parseSchema(element));\n }\n },\n defaultables: {\n child: defaultables => defaultables.map(element => element[0]),\n parse: (defaultables, ctx) => {\n if (defaultables.length === 0)\n return undefined;\n return defaultables.map(element => {\n const node = ctx.$.parseSchema(element[0]);\n assertDefaultValueAssignability(node, element[1], null);\n return [node, element[1]];\n });\n },\n serialize: defaults => defaults.map(element => [\n element[0].collapsibleJson,\n defaultValueSerializer(element[1])\n ]),\n reduceIo: (ioKind, inner, defaultables) => {\n if (ioKind === \"in\") {\n inner.optionals = defaultables.map(d => d[0].rawIn);\n return;\n }\n inner.prefix = defaultables.map(d => d[0].rawOut);\n return;\n }\n },\n variadic: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema, ctx)\n },\n minVariadicLength: {\n // minVariadicLength is reflected in the id of this node,\n // but not its IntersectionNode parent since it is superceded by the minLength\n // node it implies\n parse: min => (min === 0 ? undefined : min)\n },\n postfix: {\n child: true,\n parse: (schema, ctx) => {\n if (schema.length === 0)\n return undefined;\n return schema.map(element => ctx.$.parseSchema(element));\n }\n }\n },\n normalize: schema => {\n if (typeof schema === \"string\")\n return { variadic: schema };\n if (\"variadic\" in schema ||\n \"prefix\" in schema ||\n \"defaultables\" in schema ||\n \"optionals\" in schema ||\n \"postfix\" in schema ||\n \"minVariadicLength\" in schema) {\n if (schema.postfix?.length) {\n if (!schema.variadic)\n return throwParseError(postfixWithoutVariadicMessage);\n if (schema.optionals?.length || schema.defaultables?.length)\n return throwParseError(postfixAfterOptionalOrDefaultableMessage);\n }\n if (schema.minVariadicLength && !schema.variadic) {\n return throwParseError(\"minVariadicLength may not be specified without a variadic element\");\n }\n return schema;\n }\n return { variadic: schema };\n },\n reduce: (raw, $) => {\n let minVariadicLength = raw.minVariadicLength ?? 0;\n const prefix = raw.prefix?.slice() ?? [];\n const defaultables = raw.defaultables?.slice() ?? [];\n const optionals = raw.optionals?.slice() ?? [];\n const postfix = raw.postfix?.slice() ?? [];\n if (raw.variadic) {\n // optional elements equivalent to the variadic parameter are redundant\n while (optionals[optionals.length - 1]?.equals(raw.variadic))\n optionals.pop();\n if (optionals.length === 0 && defaultables.length === 0) {\n // If there are no optional, normalize prefix\n // elements adjacent and equivalent to variadic:\n // \t\t{ variadic: number, prefix: [string, number] }\n // reduces to:\n // \t\t{ variadic: number, prefix: [string], minVariadicLength: 1 }\n while (prefix[prefix.length - 1]?.equals(raw.variadic)) {\n prefix.pop();\n minVariadicLength++;\n }\n }\n // Normalize postfix elements adjacent and equivalent to variadic:\n // \t\t{ variadic: number, postfix: [number, number, 5] }\n // reduces to:\n // \t\t{ variadic: number, postfix: [5], minVariadicLength: 2 }\n while (postfix[0]?.equals(raw.variadic)) {\n postfix.shift();\n minVariadicLength++;\n }\n }\n else if (optionals.length === 0 && defaultables.length === 0) {\n // if there's no variadic, optional or defaultable elements,\n // postfix can just be appended to prefix\n prefix.push(...postfix.splice(0));\n }\n if (\n // if any variadic adjacent elements were moved to minVariadicLength\n minVariadicLength !== raw.minVariadicLength ||\n // or any postfix elements were moved to prefix\n (raw.prefix && raw.prefix.length !== prefix.length)) {\n // reparse the reduced def\n return $.node(\"sequence\", {\n ...raw,\n // empty lists will be omitted during parsing\n prefix,\n defaultables,\n optionals,\n postfix,\n minVariadicLength\n }, { prereduced: true });\n }\n },\n defaults: {\n description: node => {\n if (node.isVariadicOnly)\n return `${node.variadic.nestableExpression}[]`;\n const innerDescription = node.tuple\n .map(element => element.kind === \"defaultables\" ?\n `${element.node.nestableExpression} = ${printable(element.default)}`\n : element.kind === \"optionals\" ?\n `${element.node.nestableExpression}?`\n : element.kind === \"variadic\" ?\n `...${element.node.nestableExpression}[]`\n : element.node.expression)\n .join(\", \");\n return `[${innerDescription}]`;\n }\n },\n intersections: {\n sequence: (l, r, ctx) => {\n const rootState = _intersectSequences({\n l: l.tuple,\n r: r.tuple,\n disjoint: new Disjoint(),\n result: [],\n fixedVariants: [],\n ctx\n });\n const viableBranches = rootState.disjoint.length === 0 ?\n [rootState, ...rootState.fixedVariants]\n : rootState.fixedVariants;\n return (viableBranches.length === 0 ? rootState.disjoint\n : viableBranches.length === 1 ?\n ctx.$.node(\"sequence\", sequenceTupleToInner(viableBranches[0].result))\n : ctx.$.node(\"union\", viableBranches.map(state => ({\n proto: Array,\n sequence: sequenceTupleToInner(state.result)\n }))));\n }\n // exactLength, minLength, and maxLength don't need to be defined\n // here since impliedSiblings guarantees they will be added\n // directly to the IntersectionNode parent of the SequenceNode\n // they exist on\n }\n});\nexport class SequenceNode extends BaseConstraint {\n impliedBasis = $ark.intrinsic.Array.internal;\n tuple = sequenceInnerToTuple(this.inner);\n prefixLength = this.prefix?.length ?? 0;\n defaultablesLength = this.defaultables?.length ?? 0;\n optionalsLength = this.optionals?.length ?? 0;\n postfixLength = this.postfix?.length ?? 0;\n defaultablesAndOptionals = [];\n prevariadic = this.tuple.filter((el) => {\n if (el.kind === \"defaultables\" || el.kind === \"optionals\") {\n // populate defaultablesAndOptionals while filtering prevariadic\n this.defaultablesAndOptionals.push(el.node);\n return true;\n }\n return el.kind === \"prefix\";\n });\n variadicOrPostfix = conflatenate(this.variadic && [this.variadic], this.postfix);\n // have to wait until prevariadic and variadicOrPostfix are set to calculate\n flatRefs = this.addFlatRefs();\n addFlatRefs() {\n appendUniqueFlatRefs(this.flatRefs, this.prevariadic.flatMap((element, i) => append(element.node.flatRefs.map(ref => flatRef([`${i}`, ...ref.path], ref.node)), flatRef([`${i}`], element.node))));\n appendUniqueFlatRefs(this.flatRefs, this.variadicOrPostfix.flatMap(element => \n // a postfix index can't be directly represented as a type\n // key, so we just use the same matcher for variadic\n append(element.flatRefs.map(ref => flatRef([$ark.intrinsic.nonNegativeIntegerString.internal, ...ref.path], ref.node)), flatRef([$ark.intrinsic.nonNegativeIntegerString.internal], element))));\n return this.flatRefs;\n }\n isVariadicOnly = this.prevariadic.length + this.postfixLength === 0;\n minVariadicLength = this.inner.minVariadicLength ?? 0;\n minLength = this.prefixLength + this.minVariadicLength + this.postfixLength;\n minLengthNode = this.minLength === 0 ?\n null\n // cast is safe here as the only time this would not be a\n // MinLengthNode would be when minLength is 0\n : this.$.node(\"minLength\", this.minLength);\n maxLength = this.variadic ? null : this.tuple.length;\n maxLengthNode = this.maxLength === null ? null : this.$.node(\"maxLength\", this.maxLength);\n impliedSiblings = this.minLengthNode ?\n this.maxLengthNode ?\n [this.minLengthNode, this.maxLengthNode]\n : [this.minLengthNode]\n : this.maxLengthNode ? [this.maxLengthNode]\n : [];\n defaultValueMorphs = getDefaultableMorphs(this);\n defaultValueMorphsReference = this.defaultValueMorphs.length ?\n registeredReference(this.defaultValueMorphs)\n : undefined;\n elementAtIndex(data, index) {\n if (index < this.prevariadic.length)\n return this.tuple[index];\n const firstPostfixIndex = data.length - this.postfixLength;\n if (index >= firstPostfixIndex)\n return { kind: \"postfix\", node: this.postfix[index - firstPostfixIndex] };\n return {\n kind: \"variadic\",\n node: this.variadic ??\n throwInternalError(`Unexpected attempt to access index ${index} on ${this}`)\n };\n }\n // minLength/maxLength should be checked by Intersection before either traversal\n traverseAllows = (data, ctx) => {\n for (let i = 0; i < data.length; i++) {\n if (!this.elementAtIndex(data, i).node.traverseAllows(data[i], ctx))\n return false;\n }\n return true;\n };\n traverseApply = (data, ctx) => {\n let i = 0;\n for (; i < data.length; i++) {\n traverseKey(i, () => this.elementAtIndex(data, i).node.traverseApply(data[i], ctx), ctx);\n }\n };\n get element() {\n return this.cacheGetter(\"element\", this.$.node(\"union\", this.children));\n }\n // minLength/maxLength compilation should be handled by Intersection\n compile(js) {\n if (this.prefix) {\n for (const [i, node] of this.prefix.entries())\n js.traverseKey(`${i}`, `data[${i}]`, node);\n }\n for (const [i, node] of this.defaultablesAndOptionals.entries()) {\n const dataIndex = `${i + this.prefixLength}`;\n js.if(`${dataIndex} >= data.length`, () => js.traversalKind === \"Allows\" ? js.return(true) : js.return());\n js.traverseKey(dataIndex, `data[${dataIndex}]`, node);\n }\n if (this.variadic) {\n if (this.postfix) {\n js.const(\"firstPostfixIndex\", `data.length${this.postfix ? `- ${this.postfix.length}` : \"\"}`);\n }\n js.for(`i < ${this.postfix ? \"firstPostfixIndex\" : \"data.length\"}`, () => js.traverseKey(\"i\", \"data[i]\", this.variadic), this.prevariadic.length);\n if (this.postfix) {\n for (const [i, node] of this.postfix.entries()) {\n const keyExpression = `firstPostfixIndex + ${i}`;\n js.traverseKey(keyExpression, `data[${keyExpression}]`, node);\n }\n }\n }\n if (js.traversalKind === \"Allows\")\n js.return(true);\n }\n _transform(mapper, ctx) {\n ctx.path.push($ark.intrinsic.nonNegativeIntegerString.internal);\n const result = super._transform(mapper, ctx);\n ctx.path.pop();\n return result;\n }\n // this depends on tuple so needs to come after it\n expression = this.description;\n reduceJsonSchema(schema, ctx) {\n const isDraft07 = ctx.target === \"draft-07\";\n if (this.prevariadic.length) {\n const prefixSchemas = this.prevariadic.map(el => {\n const valueSchema = el.node.toJsonSchemaRecurse(ctx);\n if (el.kind === \"defaultables\") {\n const value = typeof el.default === \"function\" ? el.default() : el.default;\n valueSchema.default =\n $ark.intrinsic.jsonData.allows(value) ?\n value\n : ctx.fallback.defaultValue({\n code: \"defaultValue\",\n base: valueSchema,\n value\n });\n }\n return valueSchema;\n });\n // draft-07 uses items as array, draft-2020-12 uses prefixItems\n if (isDraft07)\n schema.items = prefixSchemas;\n else\n schema.prefixItems = prefixSchemas;\n }\n // by default JSON schema prefixElements are optional\n // add minLength here if there are any required prefix elements\n if (this.minLength)\n schema.minItems = this.minLength;\n if (this.variadic) {\n const variadicItemSchema = this.variadic.toJsonSchemaRecurse(ctx);\n // draft-07 uses additionalItems when items is an array (tuple),\n // draft-2020-12 uses items\n if (isDraft07 && this.prevariadic.length)\n schema.additionalItems = variadicItemSchema;\n else\n schema.items = variadicItemSchema;\n // maxLength constraint will be enforced by items: false\n // for non-variadic arrays\n if (this.maxLength)\n schema.maxItems = this.maxLength;\n // postfix can only be present if variadic is present so nesting this is fine\n if (this.postfix) {\n const elements = this.postfix.map(el => el.toJsonSchemaRecurse(ctx));\n schema = ctx.fallback.arrayPostfix({\n code: \"arrayPostfix\",\n base: schema,\n elements\n });\n }\n }\n else {\n // For fixed-length tuples without variadic elements\n // draft-07 uses additionalItems: false, draft-2020-12 uses items: false\n if (isDraft07)\n schema.additionalItems = false;\n else\n schema.items = false;\n // delete maxItems constraint that will have been added by the\n // base intersection node to enforce fixed length\n delete schema.maxItems;\n }\n return schema;\n }\n}\nconst defaultableMorphsCache = {};\nconst getDefaultableMorphs = (node) => {\n if (!node.defaultables)\n return [];\n const morphs = [];\n let cacheKey = \"[\";\n const lastDefaultableIndex = node.prefixLength + node.defaultablesLength - 1;\n for (let i = node.prefixLength; i <= lastDefaultableIndex; i++) {\n const [elementNode, defaultValue] = node.defaultables[i - node.prefixLength];\n morphs.push(computeDefaultValueMorph(i, elementNode, defaultValue));\n cacheKey += `${i}: ${elementNode.id} = ${defaultValueSerializer(defaultValue)}, `;\n }\n cacheKey += \"]\";\n return (defaultableMorphsCache[cacheKey] ??= morphs);\n};\nexport const Sequence = {\n implementation,\n Node: SequenceNode\n};\nconst sequenceInnerToTuple = (inner) => {\n const tuple = [];\n if (inner.prefix)\n for (const node of inner.prefix)\n tuple.push({ kind: \"prefix\", node });\n if (inner.defaultables) {\n for (const [node, defaultValue] of inner.defaultables)\n tuple.push({ kind: \"defaultables\", node, default: defaultValue });\n }\n if (inner.optionals)\n for (const node of inner.optionals)\n tuple.push({ kind: \"optionals\", node });\n if (inner.variadic)\n tuple.push({ kind: \"variadic\", node: inner.variadic });\n if (inner.postfix)\n for (const node of inner.postfix)\n tuple.push({ kind: \"postfix\", node });\n return tuple;\n};\nconst sequenceTupleToInner = (tuple) => tuple.reduce((result, element) => {\n if (element.kind === \"variadic\")\n result.variadic = element.node;\n else if (element.kind === \"defaultables\") {\n result.defaultables = append(result.defaultables, [\n [element.node, element.default]\n ]);\n }\n else\n result[element.kind] = append(result[element.kind], element.node);\n return result;\n}, {});\nexport const postfixAfterOptionalOrDefaultableMessage = \"A postfix required element cannot follow an optional or defaultable element\";\nexport const postfixWithoutVariadicMessage = \"A postfix element requires a variadic element\";\nconst _intersectSequences = (s) => {\n const [lHead, ...lTail] = s.l;\n const [rHead, ...rTail] = s.r;\n if (!lHead || !rHead)\n return s;\n const lHasPostfix = lTail[lTail.length - 1]?.kind === \"postfix\";\n const rHasPostfix = rTail[rTail.length - 1]?.kind === \"postfix\";\n const kind = lHead.kind === \"prefix\" || rHead.kind === \"prefix\" ? \"prefix\"\n : lHead.kind === \"postfix\" || rHead.kind === \"postfix\" ? \"postfix\"\n : lHead.kind === \"variadic\" && rHead.kind === \"variadic\" ? \"variadic\"\n // if either operand has postfix elements, the full-length\n // intersection can't include optional elements (though they may\n // exist in some of the fixed length variants)\n : lHasPostfix || rHasPostfix ? \"prefix\"\n : lHead.kind === \"defaultables\" || rHead.kind === \"defaultables\" ?\n \"defaultables\"\n : \"optionals\";\n if (lHead.kind === \"prefix\" && rHead.kind === \"variadic\" && rHasPostfix) {\n const postfixBranchResult = _intersectSequences({\n ...s,\n fixedVariants: [],\n r: rTail.map(element => ({ ...element, kind: \"prefix\" }))\n });\n if (postfixBranchResult.disjoint.length === 0)\n s.fixedVariants.push(postfixBranchResult);\n }\n else if (rHead.kind === \"prefix\" &&\n lHead.kind === \"variadic\" &&\n lHasPostfix) {\n const postfixBranchResult = _intersectSequences({\n ...s,\n fixedVariants: [],\n l: lTail.map(element => ({ ...element, kind: \"prefix\" }))\n });\n if (postfixBranchResult.disjoint.length === 0)\n s.fixedVariants.push(postfixBranchResult);\n }\n const result = intersectOrPipeNodes(lHead.node, rHead.node, s.ctx);\n if (result instanceof Disjoint) {\n if (kind === \"prefix\" || kind === \"postfix\") {\n s.disjoint.push(...result.withPrefixKey(\n // ideally we could handle disjoint paths more precisely here,\n // but not trivial to serialize postfix elements as keys\n kind === \"prefix\" ? s.result.length : `-${lTail.length + 1}`, \n // both operands must be required for the disjoint to be considered required\n elementIsRequired(lHead) && elementIsRequired(rHead) ?\n \"required\"\n : \"optional\"));\n s.result = [...s.result, { kind, node: $ark.intrinsic.never.internal }];\n }\n else if (kind === \"optionals\" || kind === \"defaultables\") {\n // if the element result is optional and unsatisfiable, the\n // intersection can still be satisfied as long as the tuple\n // ends before the disjoint element would occur\n return s;\n }\n else {\n // if the element is variadic and unsatisfiable, the intersection\n // can be satisfied with a fixed length variant including zero\n // variadic elements\n return _intersectSequences({\n ...s,\n fixedVariants: [],\n // if there were any optional elements, there will be no postfix elements\n // so this mapping will never occur (which would be illegal otherwise)\n l: lTail.map(element => ({ ...element, kind: \"prefix\" })),\n r: lTail.map(element => ({ ...element, kind: \"prefix\" }))\n });\n }\n }\n else if (kind === \"defaultables\") {\n if (lHead.kind === \"defaultables\" &&\n rHead.kind === \"defaultables\" &&\n lHead.default !== rHead.default) {\n throwParseError(writeDefaultIntersectionMessage(lHead.default, rHead.default));\n }\n s.result = [\n ...s.result,\n {\n kind,\n node: result,\n default: lHead.kind === \"defaultables\" ? lHead.default\n : rHead.kind === \"defaultables\" ? rHead.default\n : throwInternalError(`Unexpected defaultable intersection from ${lHead.kind} and ${rHead.kind} elements.`)\n }\n ];\n }\n else\n s.result = [...s.result, { kind, node: result }];\n const lRemaining = s.l.length;\n const rRemaining = s.r.length;\n if (lHead.kind !== \"variadic\" ||\n (lRemaining >= rRemaining &&\n (rHead.kind === \"variadic\" || rRemaining === 1)))\n s.l = lTail;\n if (rHead.kind !== \"variadic\" ||\n (rRemaining >= lRemaining &&\n (lHead.kind === \"variadic\" || lRemaining === 1)))\n s.r = rTail;\n return _intersectSequences(s);\n};\nconst elementIsRequired = (el) => el.kind === \"prefix\" || el.kind === \"postfix\";\n",
|
|
76
|
+
"import { append, conflatenate, flatMorph, printable, spliterate, throwInternalError, throwParseError } from \"@ark/util\";\nimport { BaseConstraint, constraintKeyParser, flattenConstraints, intersectConstraints } from \"../constraint.js\";\nimport { intrinsic } from \"../intrinsic.js\";\nimport { typeOrTermExtends } from \"../roots/root.js\";\nimport { compileSerializedValue } from \"../shared/compile.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectNodesRoot } from \"../shared/intersections.js\";\nimport { $ark, registeredReference } from \"../shared/registry.js\";\nimport { ToJsonSchema } from \"../shared/toJsonSchema.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nimport { hasArkKind, isNode, makeRootAndArrayPropertiesMutable } from \"../shared/utils.js\";\nimport { Optional } from \"./optional.js\";\nconst createStructuralWriter = (childStringProp) => (node) => {\n if (node.props.length || node.index) {\n const parts = node.index?.map(index => index[childStringProp]) ?? [];\n for (const prop of node.props)\n parts.push(prop[childStringProp]);\n if (node.undeclared)\n parts.push(`+ (undeclared): ${node.undeclared}`);\n const objectLiteralDescription = `{ ${parts.join(\", \")} }`;\n return node.sequence ?\n `${objectLiteralDescription} & ${node.sequence.description}`\n : objectLiteralDescription;\n }\n return node.sequence?.description ?? \"{}\";\n};\nconst structuralDescription = createStructuralWriter(\"description\");\nconst structuralExpression = createStructuralWriter(\"expression\");\nconst intersectPropsAndIndex = (l, r, $) => {\n const kind = l.required ? \"required\" : \"optional\";\n if (!r.signature.allows(l.key))\n return null;\n const value = intersectNodesRoot(l.value, r.value, $);\n if (value instanceof Disjoint) {\n return kind === \"optional\" ?\n $.node(\"optional\", {\n key: l.key,\n value: $ark.intrinsic.never.internal\n })\n : value.withPrefixKey(l.key, l.kind);\n }\n return null;\n};\nconst implementation = implementNode({\n kind: \"structure\",\n hasAssociatedError: false,\n normalize: schema => schema,\n applyConfig: (schema, config) => {\n if (!schema.undeclared && config.onUndeclaredKey !== \"ignore\") {\n return {\n ...schema,\n undeclared: config.onUndeclaredKey\n };\n }\n return schema;\n },\n keys: {\n required: {\n child: true,\n parse: constraintKeyParser(\"required\"),\n reduceIo: (ioKind, inner, nodes) => {\n // ensure we don't overwrite nodes added by optional\n inner.required = append(inner.required, nodes.map(node => (ioKind === \"in\" ? node.rawIn : node.rawOut)));\n return;\n }\n },\n optional: {\n child: true,\n parse: constraintKeyParser(\"optional\"),\n reduceIo: (ioKind, inner, nodes) => {\n if (ioKind === \"in\") {\n inner.optional = nodes.map(node => node.rawIn);\n return;\n }\n for (const node of nodes) {\n inner[node.outProp.kind] = append(inner[node.outProp.kind], node.outProp.rawOut);\n }\n }\n },\n index: {\n child: true,\n parse: constraintKeyParser(\"index\")\n },\n sequence: {\n child: true,\n parse: constraintKeyParser(\"sequence\")\n },\n undeclared: {\n parse: behavior => (behavior === \"ignore\" ? undefined : behavior),\n reduceIo: (ioKind, inner, value) => {\n if (value === \"reject\") {\n inner.undeclared = \"reject\";\n return;\n }\n // if base is \"delete\", undeclared keys are \"ignore\" (i.e. unconstrained)\n // on input and \"reject\" on output\n if (ioKind === \"in\")\n delete inner.undeclared;\n else\n inner.undeclared = \"reject\";\n }\n }\n },\n defaults: {\n description: structuralDescription\n },\n intersections: {\n structure: (l, r, ctx) => {\n const lInner = { ...l.inner };\n const rInner = { ...r.inner };\n const disjointResult = new Disjoint();\n if (l.undeclared) {\n const lKey = l.keyof();\n for (const k of r.requiredKeys) {\n if (!lKey.allows(k)) {\n disjointResult.add(\"presence\", $ark.intrinsic.never.internal, r.propsByKey[k].value, {\n path: [k]\n });\n }\n }\n if (rInner.optional)\n rInner.optional = rInner.optional.filter(n => lKey.allows(n.key));\n if (rInner.index) {\n rInner.index = rInner.index.flatMap(n => {\n if (n.signature.extends(lKey))\n return n;\n const indexOverlap = intersectNodesRoot(lKey, n.signature, ctx.$);\n if (indexOverlap instanceof Disjoint)\n return [];\n const normalized = normalizeIndex(indexOverlap, n.value, ctx.$);\n if (normalized.required) {\n rInner.required = conflatenate(rInner.required, normalized.required);\n }\n if (normalized.optional) {\n rInner.optional = conflatenate(rInner.optional, normalized.optional);\n }\n return normalized.index ?? [];\n });\n }\n }\n if (r.undeclared) {\n const rKey = r.keyof();\n for (const k of l.requiredKeys) {\n if (!rKey.allows(k)) {\n disjointResult.add(\"presence\", l.propsByKey[k].value, $ark.intrinsic.never.internal, {\n path: [k]\n });\n }\n }\n if (lInner.optional)\n lInner.optional = lInner.optional.filter(n => rKey.allows(n.key));\n if (lInner.index) {\n lInner.index = lInner.index.flatMap(n => {\n if (n.signature.extends(rKey))\n return n;\n const indexOverlap = intersectNodesRoot(rKey, n.signature, ctx.$);\n if (indexOverlap instanceof Disjoint)\n return [];\n const normalized = normalizeIndex(indexOverlap, n.value, ctx.$);\n if (normalized.required) {\n lInner.required = conflatenate(lInner.required, normalized.required);\n }\n if (normalized.optional) {\n lInner.optional = conflatenate(lInner.optional, normalized.optional);\n }\n return normalized.index ?? [];\n });\n }\n }\n const baseInner = {};\n if (l.undeclared || r.undeclared) {\n baseInner.undeclared =\n l.undeclared === \"reject\" || r.undeclared === \"reject\" ?\n \"reject\"\n : \"delete\";\n }\n const childIntersectionResult = intersectConstraints({\n kind: \"structure\",\n baseInner,\n l: flattenConstraints(lInner),\n r: flattenConstraints(rInner),\n roots: [],\n ctx\n });\n if (childIntersectionResult instanceof Disjoint)\n disjointResult.push(...childIntersectionResult);\n if (disjointResult.length)\n return disjointResult;\n return childIntersectionResult;\n }\n },\n reduce: (inner, $) => {\n if (!inner.required && !inner.optional)\n return;\n const seen = {};\n let updated = false;\n const newOptionalProps = inner.optional ? [...inner.optional] : [];\n // check required keys for duplicates and handle index intersections\n if (inner.required) {\n for (let i = 0; i < inner.required.length; i++) {\n const requiredProp = inner.required[i];\n if (requiredProp.key in seen)\n throwParseError(writeDuplicateKeyMessage(requiredProp.key));\n seen[requiredProp.key] = true;\n if (inner.index) {\n for (const index of inner.index) {\n const intersection = intersectPropsAndIndex(requiredProp, index, $);\n if (intersection instanceof Disjoint)\n return intersection;\n }\n }\n }\n }\n // check optional keys for duplicates and handle index intersections\n if (inner.optional) {\n for (let i = 0; i < inner.optional.length; i++) {\n const optionalProp = inner.optional[i];\n if (optionalProp.key in seen)\n throwParseError(writeDuplicateKeyMessage(optionalProp.key));\n seen[optionalProp.key] = true;\n if (inner.index) {\n for (const index of inner.index) {\n const intersection = intersectPropsAndIndex(optionalProp, index, $);\n if (intersection instanceof Disjoint)\n return intersection;\n if (intersection !== null) {\n newOptionalProps[i] = intersection;\n updated = true;\n }\n }\n }\n }\n }\n if (updated) {\n return $.node(\"structure\", { ...inner, optional: newOptionalProps }, { prereduced: true });\n }\n }\n});\nexport class StructureNode extends BaseConstraint {\n impliedBasis = $ark.intrinsic.object.internal;\n impliedSiblings = this.children.flatMap(n => n.impliedSiblings ?? []);\n props = conflatenate(this.required, this.optional);\n propsByKey = flatMorph(this.props, (i, node) => [node.key, node]);\n propsByKeyReference = registeredReference(this.propsByKey);\n expression = structuralExpression(this);\n requiredKeys = this.required?.map(node => node.key) ?? [];\n optionalKeys = this.optional?.map(node => node.key) ?? [];\n literalKeys = [...this.requiredKeys, ...this.optionalKeys];\n _keyof;\n keyof() {\n if (this._keyof)\n return this._keyof;\n let branches = this.$.units(this.literalKeys).branches;\n if (this.index) {\n for (const { signature } of this.index)\n branches = branches.concat(signature.branches);\n }\n return (this._keyof = this.$.node(\"union\", branches));\n }\n map(flatMapProp) {\n return this.$.node(\"structure\", this.props\n .flatMap(flatMapProp)\n .reduce((structureInner, mapped) => {\n const originalProp = this.propsByKey[mapped.key];\n if (isNode(mapped)) {\n if (mapped.kind !== \"required\" && mapped.kind !== \"optional\") {\n return throwParseError(`Map result must have kind \"required\" or \"optional\" (was ${mapped.kind})`);\n }\n structureInner[mapped.kind] = append(structureInner[mapped.kind], mapped);\n return structureInner;\n }\n const mappedKind = mapped.kind ?? originalProp?.kind ?? \"required\";\n // extract the inner keys from the map result in case a node was spread,\n // which would otherwise lead to invalid keys\n const mappedPropInner = flatMorph(mapped, (k, v) => (k in Optional.implementation.keys ? [k, v] : []));\n structureInner[mappedKind] = append(structureInner[mappedKind], this.$.node(mappedKind, mappedPropInner));\n return structureInner;\n }, {}));\n }\n assertHasKeys(keys) {\n const invalidKeys = keys.filter(k => !typeOrTermExtends(k, this.keyof()));\n if (invalidKeys.length) {\n return throwParseError(writeInvalidKeysMessage(this.expression, invalidKeys));\n }\n }\n get(indexer, ...path) {\n let value;\n let required = false;\n const key = indexerToKey(indexer);\n if ((typeof key === \"string\" || typeof key === \"symbol\") &&\n this.propsByKey[key]) {\n value = this.propsByKey[key].value;\n required = this.propsByKey[key].required;\n }\n if (this.index) {\n for (const n of this.index) {\n if (typeOrTermExtends(key, n.signature))\n value = value?.and(n.value) ?? n.value;\n }\n }\n if (this.sequence &&\n typeOrTermExtends(key, $ark.intrinsic.nonNegativeIntegerString)) {\n if (hasArkKind(key, \"root\")) {\n if (this.sequence.variadic)\n // if there is a variadic element and we're accessing an index, return a union\n // of all possible elements. If there is no variadic expression, we're in a tuple\n // so this access wouldn't be safe based on the array indices\n value = value?.and(this.sequence.element) ?? this.sequence.element;\n }\n else {\n const index = Number.parseInt(key);\n if (index < this.sequence.prevariadic.length) {\n const fixedElement = this.sequence.prevariadic[index].node;\n value = value?.and(fixedElement) ?? fixedElement;\n required ||= index < this.sequence.prefixLength;\n }\n else if (this.sequence.variadic) {\n // ideally we could return something more specific for postfix\n // but there is no way to represent it using an index alone\n const nonFixedElement = this.$.node(\"union\", this.sequence.variadicOrPostfix);\n value = value?.and(nonFixedElement) ?? nonFixedElement;\n }\n }\n }\n if (!value) {\n if (this.sequence?.variadic &&\n hasArkKind(key, \"root\") &&\n key.extends($ark.intrinsic.number)) {\n return throwParseError(writeNumberIndexMessage(key.expression, this.sequence.expression));\n }\n return throwParseError(writeInvalidKeysMessage(this.expression, [key]));\n }\n const result = value.get(...path);\n return required ? result : result.or($ark.intrinsic.undefined);\n }\n pick(...keys) {\n this.assertHasKeys(keys);\n return this.$.node(\"structure\", this.filterKeys(\"pick\", keys));\n }\n omit(...keys) {\n this.assertHasKeys(keys);\n return this.$.node(\"structure\", this.filterKeys(\"omit\", keys));\n }\n optionalize() {\n const { required, ...inner } = this.inner;\n return this.$.node(\"structure\", {\n ...inner,\n optional: this.props.map(prop => prop.hasKind(\"required\") ? this.$.node(\"optional\", prop.inner) : prop)\n });\n }\n require() {\n const { optional, ...inner } = this.inner;\n return this.$.node(\"structure\", {\n ...inner,\n required: this.props.map(prop => prop.hasKind(\"optional\") ?\n {\n key: prop.key,\n value: prop.value\n }\n : prop)\n });\n }\n merge(r) {\n const inner = this.filterKeys(\"omit\", [r.keyof()]);\n if (r.required)\n inner.required = append(inner.required, r.required);\n if (r.optional)\n inner.optional = append(inner.optional, r.optional);\n if (r.index)\n inner.index = append(inner.index, r.index);\n if (r.sequence)\n inner.sequence = r.sequence;\n if (r.undeclared)\n inner.undeclared = r.undeclared;\n else\n delete inner.undeclared;\n return this.$.node(\"structure\", inner);\n }\n filterKeys(operation, keys) {\n const result = makeRootAndArrayPropertiesMutable(this.inner);\n const shouldKeep = (key) => {\n const matchesKey = keys.some(k => typeOrTermExtends(key, k));\n return operation === \"pick\" ? matchesKey : !matchesKey;\n };\n if (result.required)\n result.required = result.required.filter(prop => shouldKeep(prop.key));\n if (result.optional)\n result.optional = result.optional.filter(prop => shouldKeep(prop.key));\n if (result.index)\n result.index = result.index.filter(index => shouldKeep(index.signature));\n return result;\n }\n traverseAllows = (data, ctx) => this._traverse(\"Allows\", data, ctx);\n traverseApply = (data, ctx) => this._traverse(\"Apply\", data, ctx);\n _traverse = (traversalKind, data, ctx) => {\n const errorCount = ctx?.currentErrorCount ?? 0;\n for (let i = 0; i < this.props.length; i++) {\n if (traversalKind === \"Allows\") {\n if (!this.props[i].traverseAllows(data, ctx))\n return false;\n }\n else {\n this.props[i].traverseApply(data, ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return false;\n }\n }\n if (this.sequence) {\n if (traversalKind === \"Allows\") {\n if (!this.sequence.traverseAllows(data, ctx))\n return false;\n }\n else {\n this.sequence.traverseApply(data, ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return false;\n }\n }\n if (this.index || this.undeclared === \"reject\") {\n const keys = Object.keys(data);\n keys.push(...Object.getOwnPropertySymbols(data));\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (this.index) {\n for (const node of this.index) {\n if (node.signature.traverseAllows(k, ctx)) {\n if (traversalKind === \"Allows\") {\n const result = traverseKey(k, () => node.value.traverseAllows(data[k], ctx), ctx);\n if (!result)\n return false;\n }\n else {\n traverseKey(k, () => node.value.traverseApply(data[k], ctx), ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return false;\n }\n }\n }\n }\n if (this.undeclared === \"reject\" && !this.declaresKey(k)) {\n if (traversalKind === \"Allows\")\n return false;\n // this should have its own error code:\n // https://github.com/arktypeio/arktype/issues/1403\n ctx.errorFromNodeContext({\n code: \"predicate\",\n expected: \"removed\",\n actual: \"\",\n relativePath: [k],\n meta: this.meta\n });\n if (ctx.failFast)\n return false;\n }\n }\n }\n // added additional ctx check here to address\n // https://github.com/arktypeio/arktype/issues/1346\n if (this.structuralMorph && ctx && !ctx.hasError())\n ctx.queueMorphs([this.structuralMorph]);\n return true;\n };\n get defaultable() {\n return this.cacheGetter(\"defaultable\", this.optional?.filter(o => o.hasDefault()) ?? []);\n }\n declaresKey = (k) => k in this.propsByKey ||\n this.index?.some(n => n.signature.allows(k)) ||\n (this.sequence !== undefined &&\n $ark.intrinsic.nonNegativeIntegerString.allows(k));\n _compileDeclaresKey(js) {\n const parts = [];\n if (this.props.length)\n parts.push(`k in ${this.propsByKeyReference}`);\n if (this.index) {\n for (const index of this.index)\n parts.push(js.invoke(index.signature, { kind: \"Allows\", arg: \"k\" }));\n }\n if (this.sequence)\n parts.push(\"$ark.intrinsic.nonNegativeIntegerString.allows(k)\");\n // if parts is empty, this is a structure like { \"+\": \"reject\" }\n // that declares no keys, so return false\n return parts.join(\" || \") || \"false\";\n }\n get structuralMorph() {\n return this.cacheGetter(\"structuralMorph\", getPossibleMorph(this));\n }\n structuralMorphRef = this.structuralMorph && registeredReference(this.structuralMorph);\n compile(js) {\n if (js.traversalKind === \"Apply\")\n js.initializeErrorCount();\n for (const prop of this.props) {\n js.check(prop);\n if (js.traversalKind === \"Apply\")\n js.returnIfFailFast();\n }\n if (this.sequence) {\n js.check(this.sequence);\n if (js.traversalKind === \"Apply\")\n js.returnIfFailFast();\n }\n if (this.index || this.undeclared === \"reject\") {\n js.const(\"keys\", \"Object.keys(data)\");\n js.line(\"keys.push(...Object.getOwnPropertySymbols(data))\");\n js.for(\"i < keys.length\", () => this.compileExhaustiveEntry(js));\n }\n if (js.traversalKind === \"Allows\")\n return js.return(true);\n // always queue deleteUndeclared on valid traversal for \"delete\"\n if (this.structuralMorphRef) {\n // added additional ctx check here to address\n // https://github.com/arktypeio/arktype/issues/1346\n js.if(\"ctx && !ctx.hasError()\", () => {\n js.line(`ctx.queueMorphs([`);\n precompileMorphs(js, this);\n return js.line(\"])\");\n });\n }\n }\n compileExhaustiveEntry(js) {\n js.const(\"k\", \"keys[i]\");\n if (this.index) {\n for (const node of this.index) {\n js.if(`${js.invoke(node.signature, { arg: \"k\", kind: \"Allows\" })}`, () => js.traverseKey(\"k\", \"data[k]\", node.value));\n }\n }\n if (this.undeclared === \"reject\") {\n js.if(`!(${this._compileDeclaresKey(js)})`, () => {\n if (js.traversalKind === \"Allows\")\n return js.return(false);\n return js\n .line(`ctx.errorFromNodeContext({ code: \"predicate\", expected: \"removed\", actual: \"\", relativePath: [k], meta: ${this.compiledMeta} })`)\n .if(\"ctx.failFast\", () => js.return());\n });\n }\n return js;\n }\n reduceJsonSchema(schema, ctx) {\n switch (schema.type) {\n case \"object\":\n return this.reduceObjectJsonSchema(schema, ctx);\n case \"array\":\n const arraySchema = this.sequence?.reduceJsonSchema(schema, ctx) ?? schema;\n if (this.props.length || this.index) {\n return ctx.fallback.arrayObject({\n code: \"arrayObject\",\n base: arraySchema,\n object: this.reduceObjectJsonSchema({ type: \"object\" }, ctx)\n });\n }\n return arraySchema;\n default:\n return ToJsonSchema.throwInternalOperandError(\"structure\", schema);\n }\n }\n reduceObjectJsonSchema(schema, ctx) {\n if (this.props.length) {\n schema.properties = {};\n for (const prop of this.props) {\n const valueSchema = prop.value.toJsonSchemaRecurse(ctx);\n if (typeof prop.key === \"symbol\") {\n ctx.fallback.symbolKey({\n code: \"symbolKey\",\n base: schema,\n key: prop.key,\n value: valueSchema,\n optional: prop.optional\n });\n continue;\n }\n if (prop.hasDefault()) {\n const value = typeof prop.default === \"function\" ? prop.default() : prop.default;\n valueSchema.default =\n $ark.intrinsic.jsonData.allows(value) ?\n value\n : ctx.fallback.defaultValue({\n code: \"defaultValue\",\n base: valueSchema,\n value\n });\n }\n schema.properties[prop.key] = valueSchema;\n }\n if (this.requiredKeys.length && schema.properties) {\n schema.required = this.requiredKeys.filter((k) => typeof k === \"string\" && k in schema.properties);\n }\n }\n if (this.index) {\n for (const index of this.index) {\n const valueJsonSchema = index.value.toJsonSchemaRecurse(ctx);\n if (index.signature.equals($ark.intrinsic.string)) {\n schema.additionalProperties = valueJsonSchema;\n continue;\n }\n for (const keyBranch of index.signature.branches) {\n if (!keyBranch.extends($ark.intrinsic.string)) {\n schema = ctx.fallback.symbolKey({\n code: \"symbolKey\",\n base: schema,\n key: null,\n value: valueJsonSchema,\n optional: false\n });\n continue;\n }\n let keySchema = { type: \"string\" };\n if (keyBranch.hasKind(\"morph\")) {\n keySchema = ctx.fallback.morph({\n code: \"morph\",\n base: keyBranch.rawIn.toJsonSchemaRecurse(ctx),\n out: keyBranch.rawOut.toJsonSchemaRecurse(ctx)\n });\n }\n if (!keyBranch.hasKind(\"intersection\")) {\n return throwInternalError(`Unexpected index branch kind ${keyBranch.kind}.`);\n }\n const { pattern } = keyBranch.inner;\n if (pattern) {\n const keySchemaWithPattern = Object.assign(keySchema, {\n pattern: pattern[0].rule\n });\n for (let i = 1; i < pattern.length; i++) {\n keySchema = ctx.fallback.patternIntersection({\n code: \"patternIntersection\",\n base: keySchemaWithPattern,\n pattern: pattern[i].rule\n });\n }\n schema.patternProperties ??= {};\n schema.patternProperties[keySchemaWithPattern.pattern] =\n valueJsonSchema;\n }\n }\n }\n }\n if (this.undeclared && !schema.additionalProperties)\n schema.additionalProperties = false;\n return schema;\n }\n}\nconst defaultableMorphsCache = {};\nconst constructStructuralMorphCacheKey = (node) => {\n let cacheKey = \"\";\n for (let i = 0; i < node.defaultable.length; i++)\n cacheKey += node.defaultable[i].defaultValueMorphRef;\n if (node.sequence?.defaultValueMorphsReference)\n cacheKey += node.sequence?.defaultValueMorphsReference;\n if (node.undeclared === \"delete\") {\n cacheKey += \"delete !(\";\n if (node.required)\n for (const n of node.required)\n cacheKey += n.compiledKey + \" | \";\n if (node.optional)\n for (const n of node.optional)\n cacheKey += n.compiledKey + \" | \";\n if (node.index)\n for (const index of node.index)\n cacheKey += index.signature.id + \" | \";\n if (node.sequence) {\n if (node.sequence.maxLength === null)\n cacheKey += intrinsic.nonNegativeIntegerString.id;\n else {\n for (let i = 0; i < node.sequence.tuple.length; i++)\n cacheKey += i + \" | \";\n }\n }\n cacheKey += \")\";\n }\n return cacheKey;\n};\nconst getPossibleMorph = (node) => {\n const cacheKey = constructStructuralMorphCacheKey(node);\n if (!cacheKey)\n return undefined;\n if (defaultableMorphsCache[cacheKey])\n return defaultableMorphsCache[cacheKey];\n const $arkStructuralMorph = (data, ctx) => {\n for (let i = 0; i < node.defaultable.length; i++) {\n if (!(node.defaultable[i].key in data))\n node.defaultable[i].defaultValueMorph(data, ctx);\n }\n if (node.sequence?.defaultables) {\n for (let i = data.length - node.sequence.prefixLength; i < node.sequence.defaultables.length; i++)\n node.sequence.defaultValueMorphs[i](data, ctx);\n }\n if (node.undeclared === \"delete\")\n for (const k in data)\n if (!node.declaresKey(k))\n delete data[k];\n return data;\n };\n return (defaultableMorphsCache[cacheKey] = $arkStructuralMorph);\n};\nconst precompileMorphs = (js, node) => {\n const requiresContext = node.defaultable.some(node => node.defaultValueMorph.length === 2) ||\n node.sequence?.defaultValueMorphs.some(morph => morph.length === 2);\n const args = `(data${requiresContext ? \", ctx\" : \"\"})`;\n return js.block(`${args} => `, js => {\n for (let i = 0; i < node.defaultable.length; i++) {\n const { serializedKey, defaultValueMorphRef } = node.defaultable[i];\n js.if(`!(${serializedKey} in data)`, js => js.line(`${defaultValueMorphRef}${args}`));\n }\n if (node.sequence?.defaultables) {\n js.for(`i < ${node.sequence.defaultables.length}`, js => js.set(`data[i]`, 5), `data.length - ${node.sequence.prefixLength}`);\n }\n if (node.undeclared === \"delete\") {\n js.forIn(\"data\", js => js.if(`!(${node._compileDeclaresKey(js)})`, js => js.line(`delete data[k]`)));\n }\n return js.return(\"data\");\n });\n};\nexport const Structure = {\n implementation,\n Node: StructureNode\n};\nconst indexerToKey = (indexable) => {\n if (hasArkKind(indexable, \"root\") && indexable.hasKind(\"unit\"))\n indexable = indexable.unit;\n if (typeof indexable === \"number\")\n indexable = `${indexable}`;\n return indexable;\n};\nexport const writeNumberIndexMessage = (indexExpression, sequenceExpression) => `${indexExpression} is not allowed as an array index on ${sequenceExpression}. Use the 'nonNegativeIntegerString' keyword instead.`;\n/** extract enumerable named props from an index signature */\nexport const normalizeIndex = (signature, value, $) => {\n const [enumerableBranches, nonEnumerableBranches] = spliterate(signature.branches, k => k.hasKind(\"unit\"));\n if (!enumerableBranches.length)\n return { index: $.node(\"index\", { signature, value }) };\n const normalized = {};\n for (const n of enumerableBranches) {\n // since required can be reduced to optional if it has a default or\n // optional meta on its value, we have to assign it depending on the\n // compiled kind\n const prop = $.node(\"required\", { key: n.unit, value });\n normalized[prop.kind] = append(normalized[prop.kind], prop);\n }\n if (nonEnumerableBranches.length) {\n normalized.index = $.node(\"index\", {\n signature: nonEnumerableBranches,\n value\n });\n }\n return normalized;\n};\nexport const typeKeyToString = (k) => hasArkKind(k, \"root\") ? k.expression : printable(k);\nexport const writeInvalidKeysMessage = (o, keys) => `Key${keys.length === 1 ? \"\" : \"s\"} ${keys.map(typeKeyToString).join(\", \")} ${keys.length === 1 ? \"does\" : \"do\"} not exist on ${o}`;\nexport const writeDuplicateKeyMessage = (key) => `Duplicate key ${compileSerializedValue(key)}`;\n",
|
|
77
|
+
"import { deepClone, envHasCsp, flatMorph, withAlphabetizedKeys } from \"@ark/util\";\nimport { mergeConfigs } from \"./config.js\";\nimport { Predicate } from \"./predicate.js\";\nimport { Divisor } from \"./refinements/divisor.js\";\nimport { boundClassesByKind, boundImplementationsByKind } from \"./refinements/kinds.js\";\nimport { Pattern } from \"./refinements/pattern.js\";\nimport { Alias } from \"./roots/alias.js\";\nimport { Domain } from \"./roots/domain.js\";\nimport { Intersection } from \"./roots/intersection.js\";\nimport { Morph } from \"./roots/morph.js\";\nimport { Proto } from \"./roots/proto.js\";\nimport { Union } from \"./roots/union.js\";\nimport { Unit } from \"./roots/unit.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { ToJsonSchema } from \"./shared/toJsonSchema.js\";\nimport { Index } from \"./structure/index.js\";\nimport { Optional } from \"./structure/optional.js\";\nimport { Required } from \"./structure/required.js\";\nimport { Sequence } from \"./structure/sequence.js\";\nimport { Structure } from \"./structure/structure.js\";\nexport const nodeImplementationsByKind = {\n ...boundImplementationsByKind,\n alias: Alias.implementation,\n domain: Domain.implementation,\n unit: Unit.implementation,\n proto: Proto.implementation,\n union: Union.implementation,\n morph: Morph.implementation,\n intersection: Intersection.implementation,\n divisor: Divisor.implementation,\n pattern: Pattern.implementation,\n predicate: Predicate.implementation,\n required: Required.implementation,\n optional: Optional.implementation,\n index: Index.implementation,\n sequence: Sequence.implementation,\n structure: Structure.implementation\n};\n$ark.defaultConfig = withAlphabetizedKeys(Object.assign(flatMorph(nodeImplementationsByKind, (kind, implementation) => [\n kind,\n implementation.defaults\n]), {\n jitless: envHasCsp(),\n clone: deepClone,\n onUndeclaredKey: \"ignore\",\n exactOptionalPropertyTypes: true,\n numberAllowsNaN: false,\n dateAllowsInvalid: false,\n onFail: null,\n keywords: {},\n toJsonSchema: ToJsonSchema.defaultConfig\n}));\n$ark.resolvedConfig = mergeConfigs($ark.defaultConfig, $ark.config);\nexport const nodeClassesByKind = {\n ...boundClassesByKind,\n alias: Alias.Node,\n domain: Domain.Node,\n unit: Unit.Node,\n proto: Proto.Node,\n union: Union.Node,\n morph: Morph.Node,\n intersection: Intersection.Node,\n divisor: Divisor.Node,\n pattern: Pattern.Node,\n predicate: Predicate.Node,\n required: Required.Node,\n optional: Optional.Node,\n index: Index.Node,\n sequence: Sequence.Node,\n structure: Structure.Node\n};\n",
|
|
78
|
+
"import { DynamicBase, flatMorph } from \"@ark/util\";\nimport { arkKind, hasArkKind } from \"./shared/utils.js\";\nexport class RootModule extends DynamicBase {\n // ensure `[arkKind]` is non-enumerable so it doesn't get spread on import/export\n get [arkKind]() {\n return \"module\";\n }\n}\nexport const bindModule = (module, $) => new RootModule(flatMorph(module, (alias, value) => [\n alias,\n hasArkKind(value, \"module\") ?\n bindModule(value, $)\n : $.bindReference(value)\n]));\nexport const SchemaModule = RootModule;\n",
|
|
79
|
+
"import { ParseError, flatMorph, hasDomain, isArray, isThunk, printable, throwInternalError, throwParseError } from \"@ark/util\";\nimport { mergeConfigs } from \"./config.js\";\nimport { GenericRoot, LazyGenericBody } from \"./generic.js\";\nimport { nodeImplementationsByKind } from \"./kinds.js\";\nimport { RootModule, bindModule } from \"./module.js\";\nimport { nodesByRegisteredId, parseNode, registerNodeId, schemaKindOf, withId } from \"./parse.js\";\nimport { Alias } from \"./roots/alias.js\";\nimport { CompiledFunction, NodeCompiler } from \"./shared/compile.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { Traversal } from \"./shared/traversal.js\";\nimport { arkKind, hasArkKind, isNode } from \"./shared/utils.js\";\nconst schemaBranchesOf = (schema) => isArray(schema) ? schema\n : \"branches\" in schema && isArray(schema.branches) ? schema.branches\n : undefined;\nconst throwMismatchedNodeRootError = (expected, actual) => throwParseError(`Node of kind ${actual} is not valid as a ${expected} definition`);\nexport const writeDuplicateAliasError = (alias) => `#${alias} duplicates public alias ${alias}`;\nconst scopesByName = {};\n$ark.ambient ??= {};\nlet rawUnknownUnion;\nconst rootScopeFnName = \"function $\";\nconst precompile = (references) => bindPrecompilation(references, precompileReferences(references));\nconst bindPrecompilation = (references, precompiler) => {\n const precompilation = precompiler.write(rootScopeFnName, 4);\n const compiledTraversals = precompiler.compile()();\n for (const node of references) {\n if (node.precompilation) {\n // if node has already been bound to another scope or anonymous type, don't rebind it\n continue;\n }\n node.traverseAllows =\n compiledTraversals[`${node.id}Allows`].bind(compiledTraversals);\n if (node.isRoot() && !node.allowsRequiresContext) {\n // if the reference doesn't require context, we can assign over\n // it directly to avoid having to initialize it\n node.allows = node.traverseAllows;\n }\n node.traverseApply =\n compiledTraversals[`${node.id}Apply`].bind(compiledTraversals);\n if (compiledTraversals[`${node.id}Optimistic`]) {\n ;\n node.traverseOptimistic =\n compiledTraversals[`${node.id}Optimistic`].bind(compiledTraversals);\n }\n node.precompilation = precompilation;\n }\n};\nconst precompileReferences = (references) => new CompiledFunction().return(references.reduce((js, node) => {\n const allowsCompiler = new NodeCompiler({ kind: \"Allows\" }).indent();\n node.compile(allowsCompiler);\n const allowsJs = allowsCompiler.write(`${node.id}Allows`);\n const applyCompiler = new NodeCompiler({ kind: \"Apply\" }).indent();\n node.compile(applyCompiler);\n const applyJs = applyCompiler.write(`${node.id}Apply`);\n const result = `${js}${allowsJs},\\n${applyJs},\\n`;\n if (!node.hasKind(\"union\"))\n return result;\n const optimisticCompiler = new NodeCompiler({\n kind: \"Allows\",\n optimistic: true\n }).indent();\n node.compile(optimisticCompiler);\n const optimisticJs = optimisticCompiler.write(`${node.id}Optimistic`);\n return `${result}${optimisticJs},\\n`;\n}, \"{\\n\") + \"}\");\nexport class BaseScope {\n config;\n resolvedConfig;\n name;\n get [arkKind]() {\n return \"scope\";\n }\n referencesById = {};\n references = [];\n resolutions = {};\n exportedNames = [];\n aliases = {};\n resolved = false;\n nodesByHash = {};\n intrinsic;\n constructor(\n /** The set of names defined at the root-level of the scope mapped to their\n * corresponding definitions.**/\n def, config) {\n this.config = mergeConfigs($ark.config, config);\n this.resolvedConfig = mergeConfigs($ark.resolvedConfig, config);\n this.name =\n this.resolvedConfig.name ??\n `anonymousScope${Object.keys(scopesByName).length}`;\n if (this.name in scopesByName)\n throwParseError(`A Scope already named ${this.name} already exists`);\n scopesByName[this.name] = this;\n const aliasEntries = Object.entries(def).map(entry => this.preparseOwnAliasEntry(...entry));\n for (const [k, v] of aliasEntries) {\n let name = k;\n if (k[0] === \"#\") {\n name = k.slice(1);\n if (name in this.aliases)\n throwParseError(writeDuplicateAliasError(name));\n this.aliases[name] = v;\n }\n else {\n if (name in this.aliases)\n throwParseError(writeDuplicateAliasError(k));\n this.aliases[name] = v;\n this.exportedNames.push(name);\n }\n if (!hasArkKind(v, \"module\") &&\n !hasArkKind(v, \"generic\") &&\n !isThunk(v)) {\n const preparsed = this.preparseOwnDefinitionFormat(v, { alias: name });\n this.resolutions[name] =\n hasArkKind(preparsed, \"root\") ?\n this.bindReference(preparsed)\n : this.createParseContext(preparsed).id;\n }\n }\n // reduce union of all possible values reduces to unknown\n rawUnknownUnion ??= this.node(\"union\", {\n branches: [\n \"string\",\n \"number\",\n \"object\",\n \"bigint\",\n \"symbol\",\n { unit: true },\n { unit: false },\n { unit: undefined },\n { unit: null }\n ]\n }, { prereduced: true });\n this.nodesByHash[rawUnknownUnion.hash] = this.node(\"intersection\", {}, { prereduced: true });\n this.intrinsic =\n $ark.intrinsic ?\n flatMorph($ark.intrinsic, (k, v) => \n // don't include cyclic aliases from JSON scope\n k.startsWith(\"json\") ? [] : [k, this.bindReference(v)])\n // intrinsic won't be available during bootstrapping, so we lie\n // about the type here as an extrnal convenience\n : {};\n }\n cacheGetter(name, value) {\n Object.defineProperty(this, name, { value });\n return value;\n }\n get internal() {\n return this;\n }\n // json is populated when the scope is exported, so ensure it is populated\n // before allowing external access\n _json;\n get json() {\n if (!this._json)\n this.export();\n return this._json;\n }\n defineSchema(def) {\n return def;\n }\n generic = (...params) => {\n const $ = this;\n return (def, possibleHkt) => new GenericRoot(params, possibleHkt ? new LazyGenericBody(def) : def, $, $, possibleHkt ?? null);\n };\n units = (values, opts) => {\n const uniqueValues = [];\n for (const value of values)\n if (!uniqueValues.includes(value))\n uniqueValues.push(value);\n const branches = uniqueValues.map(unit => this.node(\"unit\", { unit }, opts));\n return this.node(\"union\", branches, {\n ...opts,\n prereduced: true\n });\n };\n lazyResolutions = [];\n lazilyResolve(resolve, syntheticAlias) {\n const node = this.node(\"alias\", {\n reference: syntheticAlias ?? \"synthetic\",\n resolve\n }, { prereduced: true });\n if (!this.resolved)\n this.lazyResolutions.push(node);\n return node;\n }\n schema = (schema, opts) => this.finalize(this.parseSchema(schema, opts));\n parseSchema = (schema, opts) => this.node(schemaKindOf(schema), schema, opts);\n preparseNode(kinds, schema, opts) {\n let kind = typeof kinds === \"string\" ? kinds : schemaKindOf(schema, kinds);\n if (isNode(schema) && schema.kind === kind)\n return schema;\n if (kind === \"alias\" && !opts?.prereduced) {\n const { reference } = Alias.implementation.normalize(schema, this);\n if (reference.startsWith(\"$\")) {\n const resolution = this.resolveRoot(reference.slice(1));\n schema = resolution;\n kind = resolution.kind;\n }\n }\n else if (kind === \"union\" && hasDomain(schema, \"object\")) {\n const branches = schemaBranchesOf(schema);\n if (branches?.length === 1) {\n schema = branches[0];\n kind = schemaKindOf(schema);\n }\n }\n if (isNode(schema) && schema.kind === kind)\n return schema;\n const impl = nodeImplementationsByKind[kind];\n const normalizedSchema = impl.normalize?.(schema, this) ?? schema;\n // check again after normalization in case a node is a valid collapsed\n // schema for the kind (e.g. sequence can collapse to element accepting a Node')\n if (isNode(normalizedSchema)) {\n return normalizedSchema.kind === kind ?\n normalizedSchema\n : throwMismatchedNodeRootError(kind, normalizedSchema.kind);\n }\n return {\n ...opts,\n $: this,\n kind,\n def: normalizedSchema,\n prefix: opts.alias ?? kind\n };\n }\n bindReference(reference) {\n let bound;\n if (isNode(reference)) {\n bound =\n reference.$ === this ?\n reference\n : new reference.constructor(reference.attachments, this);\n }\n else {\n bound =\n reference.$ === this ?\n reference\n : new GenericRoot(reference.params, reference.bodyDef, reference.$, this, reference.hkt);\n }\n if (!this.resolved) {\n // we're still parsing the scope itself, so defer compilation but\n // add the node as a reference\n Object.assign(this.referencesById, bound.referencesById);\n }\n return bound;\n }\n resolveRoot(name) {\n return (this.maybeResolveRoot(name) ??\n throwParseError(writeUnresolvableMessage(name)));\n }\n maybeResolveRoot(name) {\n const result = this.maybeResolve(name);\n if (hasArkKind(result, \"generic\"))\n return;\n return result;\n }\n /** If name is a valid reference to a submodule alias, return its resolution */\n maybeResolveSubalias(name) {\n return (maybeResolveSubalias(this.aliases, name) ??\n maybeResolveSubalias(this.ambient, name));\n }\n get ambient() {\n return $ark.ambient;\n }\n maybeResolve(name) {\n const cached = this.resolutions[name];\n if (cached) {\n if (typeof cached !== \"string\")\n return this.bindReference(cached);\n const v = nodesByRegisteredId[cached];\n if (hasArkKind(v, \"root\"))\n return (this.resolutions[name] = v);\n if (hasArkKind(v, \"context\")) {\n if (v.phase === \"resolving\") {\n return this.node(\"alias\", { reference: `$${name}` }, { prereduced: true });\n }\n if (v.phase === \"resolved\") {\n return throwInternalError(`Unexpected resolved context for was uncached by its scope: ${printable(v)}`);\n }\n v.phase = \"resolving\";\n const node = this.bindReference(this.parseOwnDefinitionFormat(v.def, v));\n v.phase = \"resolved\";\n nodesByRegisteredId[node.id] = node;\n nodesByRegisteredId[v.id] = node;\n return (this.resolutions[name] = node);\n }\n return throwInternalError(`Unexpected nodesById entry for ${cached}: ${printable(v)}`);\n }\n let def = this.aliases[name] ?? this.ambient?.[name];\n if (!def)\n return this.maybeResolveSubalias(name);\n def = this.normalizeRootScopeValue(def);\n if (hasArkKind(def, \"generic\"))\n return (this.resolutions[name] = this.bindReference(def));\n if (hasArkKind(def, \"module\")) {\n if (!def.root)\n throwParseError(writeMissingSubmoduleAccessMessage(name));\n return (this.resolutions[name] = this.bindReference(def.root));\n }\n return (this.resolutions[name] = this.parse(def, {\n alias: name\n }));\n }\n createParseContext(input) {\n const id = input.id ?? registerNodeId(input.prefix);\n return (nodesByRegisteredId[id] = Object.assign(input, {\n [arkKind]: \"context\",\n $: this,\n id,\n phase: \"unresolved\"\n }));\n }\n traversal(root) {\n return new Traversal(root, this.resolvedConfig);\n }\n import(...names) {\n return new RootModule(flatMorph(this.export(...names), (alias, value) => [\n `#${alias}`,\n value\n ]));\n }\n precompilation;\n _exportedResolutions;\n _exports;\n export(...names) {\n if (!this._exports) {\n this._exports = {};\n for (const name of this.exportedNames) {\n const def = this.aliases[name];\n this._exports[name] =\n hasArkKind(def, \"module\") ?\n bindModule(def, this)\n : bootstrapAliasReferences(this.maybeResolve(name));\n }\n // force node.resolution getter evaluation\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n for (const node of this.lazyResolutions)\n node.resolution;\n this._exportedResolutions = resolutionsOfModule(this, this._exports);\n this._json = resolutionsToJson(this._exportedResolutions);\n Object.assign(this.resolutions, this._exportedResolutions);\n this.references = Object.values(this.referencesById);\n if (!this.resolvedConfig.jitless) {\n const precompiler = precompileReferences(this.references);\n this.precompilation = precompiler.write(rootScopeFnName, 4);\n bindPrecompilation(this.references, precompiler);\n }\n this.resolved = true;\n }\n const namesToExport = names.length ? names : this.exportedNames;\n return new RootModule(flatMorph(namesToExport, (_, name) => [\n name,\n this._exports[name]\n ]));\n }\n resolve(name) {\n return this.export()[name];\n }\n node = (kinds, nodeSchema, opts = {}) => {\n const ctxOrNode = this.preparseNode(kinds, nodeSchema, opts);\n if (isNode(ctxOrNode))\n return this.bindReference(ctxOrNode);\n const ctx = this.createParseContext(ctxOrNode);\n const node = parseNode(ctx);\n const bound = this.bindReference(node);\n return (nodesByRegisteredId[ctx.id] = bound);\n };\n parse = (def, opts = {}) => this.finalize(this.parseDefinition(def, opts));\n parseDefinition(def, opts = {}) {\n if (hasArkKind(def, \"root\"))\n return this.bindReference(def);\n const ctxInputOrNode = this.preparseOwnDefinitionFormat(def, opts);\n if (hasArkKind(ctxInputOrNode, \"root\"))\n return this.bindReference(ctxInputOrNode);\n const ctx = this.createParseContext(ctxInputOrNode);\n nodesByRegisteredId[ctx.id] = ctx;\n let node = this.bindReference(this.parseOwnDefinitionFormat(def, ctx));\n // if the node is recursive e.g. { box: \"this\" }, we need to make sure it\n // has the original id from context so that its references compile correctly\n if (node.isCyclic)\n node = withId(node, ctx.id);\n nodesByRegisteredId[ctx.id] = node;\n return node;\n }\n finalize(node) {\n bootstrapAliasReferences(node);\n if (!node.precompilation && !this.resolvedConfig.jitless)\n precompile(node.references);\n return node;\n }\n}\nexport class SchemaScope extends BaseScope {\n parseOwnDefinitionFormat(def, ctx) {\n return parseNode(ctx);\n }\n preparseOwnDefinitionFormat(schema, opts) {\n return this.preparseNode(schemaKindOf(schema), schema, opts);\n }\n preparseOwnAliasEntry(k, v) {\n return [k, v];\n }\n normalizeRootScopeValue(v) {\n return v;\n }\n}\nconst bootstrapAliasReferences = (resolution) => {\n const aliases = resolution.references.filter(node => node.hasKind(\"alias\"));\n for (const aliasNode of aliases) {\n Object.assign(aliasNode.referencesById, aliasNode.resolution.referencesById);\n for (const ref of resolution.references) {\n if (aliasNode.id in ref.referencesById)\n Object.assign(ref.referencesById, aliasNode.referencesById);\n }\n }\n return resolution;\n};\nconst resolutionsToJson = (resolutions) => flatMorph(resolutions, (k, v) => [\n k,\n hasArkKind(v, \"root\") || hasArkKind(v, \"generic\") ? v.json\n : hasArkKind(v, \"module\") ? resolutionsToJson(v)\n : throwInternalError(`Unexpected resolution ${printable(v)}`)\n]);\nconst maybeResolveSubalias = (base, name) => {\n const dotIndex = name.indexOf(\".\");\n if (dotIndex === -1)\n return;\n const dotPrefix = name.slice(0, dotIndex);\n const prefixSchema = base[dotPrefix];\n // if the name includes \".\", but the prefix is not an alias, it\n // might be something like a decimal literal, so just fall through to return\n if (prefixSchema === undefined)\n return;\n if (!hasArkKind(prefixSchema, \"module\"))\n return throwParseError(writeNonSubmoduleDotMessage(dotPrefix));\n const subalias = name.slice(dotIndex + 1);\n const resolution = prefixSchema[subalias];\n if (resolution === undefined)\n return maybeResolveSubalias(prefixSchema, subalias);\n if (hasArkKind(resolution, \"root\") || hasArkKind(resolution, \"generic\"))\n return resolution;\n if (hasArkKind(resolution, \"module\")) {\n return (resolution.root ??\n throwParseError(writeMissingSubmoduleAccessMessage(name)));\n }\n throwInternalError(`Unexpected resolution for alias '${name}': ${printable(resolution)}`);\n};\nexport const schemaScope = (aliases, config) => new SchemaScope(aliases, config);\nexport const rootSchemaScope = new SchemaScope({});\nexport const parseAsSchema = (def, opts) => {\n try {\n return rootSchema(def, opts);\n }\n catch (e) {\n if (e instanceof ParseError)\n return e;\n throw e;\n }\n};\nconst resolutionsOfModule = ($, typeSet) => {\n const result = {};\n for (const k in typeSet) {\n const v = typeSet[k];\n if (hasArkKind(v, \"module\")) {\n const innerResolutions = resolutionsOfModule($, v);\n const prefixedResolutions = flatMorph(innerResolutions, (innerK, innerV) => [`${k}.${innerK}`, innerV]);\n Object.assign(result, prefixedResolutions);\n }\n else if (hasArkKind(v, \"root\") || hasArkKind(v, \"generic\"))\n result[k] = v;\n else\n throwInternalError(`Unexpected scope resolution ${printable(v)}`);\n }\n return result;\n};\nexport const writeUnresolvableMessage = (token) => `'${token}' is unresolvable`;\nexport const writeNonSubmoduleDotMessage = (name) => `'${name}' must reference a module to be accessed using dot syntax`;\nexport const writeMissingSubmoduleAccessMessage = (name) => `Reference to submodule '${name}' must specify an alias`;\n// ensure the scope is resolved so JIT will be applied to future types\nrootSchemaScope.export();\nexport const rootSchema = rootSchemaScope.schema;\nexport const node = rootSchemaScope.node;\nexport const defineSchema = rootSchemaScope.defineSchema;\nexport const genericNode = rootSchemaScope.generic;\n",
|
|
80
|
+
"import { registeredReference } from \"../shared/registry.js\";\nexport const arrayIndexSource = `^(?:0|[1-9]\\\\d*)$`;\nexport const arrayIndexMatcher = new RegExp(arrayIndexSource);\nexport const arrayIndexMatcherReference = registeredReference(arrayIndexMatcher);\n",
|
|
81
|
+
"import { node, schemaScope } from \"./scope.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { arrayIndexSource } from \"./structure/shared.js\";\nconst intrinsicBases = schemaScope({\n bigint: \"bigint\",\n // since we know this won't be reduced, it can be safely cast to a union\n boolean: [{ unit: false }, { unit: true }],\n false: { unit: false },\n never: [],\n null: { unit: null },\n number: \"number\",\n object: \"object\",\n string: \"string\",\n symbol: \"symbol\",\n true: { unit: true },\n unknown: {},\n undefined: { unit: undefined },\n Array,\n Date\n}, { prereducedAliases: true }).export();\n$ark.intrinsic = { ...intrinsicBases };\nconst intrinsicRoots = schemaScope({\n integer: {\n domain: \"number\",\n divisor: 1\n },\n lengthBoundable: [\"string\", Array],\n key: [\"string\", \"symbol\"],\n nonNegativeIntegerString: { domain: \"string\", pattern: arrayIndexSource }\n}, { prereducedAliases: true }).export();\n// needed to parse index signatures for JSON\nObject.assign($ark.intrinsic, intrinsicRoots);\nconst intrinsicJson = schemaScope({\n jsonPrimitive: [\n \"string\",\n \"number\",\n { unit: true },\n { unit: false },\n { unit: null }\n ],\n jsonObject: {\n domain: \"object\",\n index: {\n signature: \"string\",\n value: \"$jsonData\"\n }\n },\n jsonData: [\"$jsonPrimitive\", \"$jsonObject\"]\n}, { prereducedAliases: true }).export();\nexport const intrinsic = {\n ...intrinsicBases,\n ...intrinsicRoots,\n ...intrinsicJson,\n emptyStructure: node(\"structure\", {}, { prereduced: true })\n};\n$ark.intrinsic = { ...intrinsic };\n",
|
|
82
|
+
"export const regex = ((src, flags) => new RegExp(src, flags));\nObject.assign(regex, { as: regex });\n",
|
|
83
|
+
"import { throwParseError, tryParseNumber } from \"@ark/util\";\nexport const isDateLiteral = (value) => typeof value === \"string\" &&\n value[0] === \"d\" &&\n (value[1] === \"'\" || value[1] === '\"') &&\n value[value.length - 1] === value[1];\nexport const isValidDate = (d) => d.toString() !== \"Invalid Date\";\nexport const extractDateLiteralSource = (literal) => literal.slice(2, -1);\nexport const writeInvalidDateMessage = (source) => `'${source}' could not be parsed by the Date constructor`;\nexport const tryParseDate = (source, errorOnFail) => maybeParseDate(source, errorOnFail);\nconst maybeParseDate = (source, errorOnFail) => {\n const stringParsedDate = new Date(source);\n if (isValidDate(stringParsedDate))\n return stringParsedDate;\n const epochMillis = tryParseNumber(source);\n if (epochMillis !== undefined) {\n const numberParsedDate = new Date(epochMillis);\n if (isValidDate(numberParsedDate))\n return numberParsedDate;\n }\n return errorOnFail ?\n throwParseError(errorOnFail === true ? writeInvalidDateMessage(source) : errorOnFail)\n : undefined;\n};\n",
|
|
84
|
+
"import { rootSchema } from \"@ark/schema\";\nimport { isKeyOf, throwParseError } from \"@ark/util\";\nimport { tryParseDate, writeInvalidDateMessage } from \"./date.js\";\nconst regexExecArray = rootSchema({\n proto: \"Array\",\n sequence: \"string\",\n required: {\n key: \"groups\",\n value: [\"object\", { unit: undefined }]\n }\n});\nexport const parseEnclosed = (s, enclosing) => {\n const enclosed = s.scanner.shiftUntilEscapable(untilLookaheadIsClosing[enclosingTokens[enclosing]]);\n if (s.scanner.lookahead === \"\")\n return s.error(writeUnterminatedEnclosedMessage(enclosed, enclosing));\n // Shift the scanner one additional time for the second enclosing token\n s.scanner.shift();\n if (enclosing in enclosingRegexTokens) {\n let regex;\n try {\n regex = new RegExp(enclosed);\n }\n catch (e) {\n throwParseError(String(e));\n }\n s.root = s.ctx.$.node(\"intersection\", {\n domain: \"string\",\n pattern: enclosed\n }, { prereduced: true });\n if (enclosing === \"x/\") {\n s.root = s.ctx.$.node(\"morph\", {\n in: s.root,\n morphs: (s) => regex.exec(s),\n declaredOut: regexExecArray\n });\n }\n }\n else if (isKeyOf(enclosing, enclosingQuote))\n s.root = s.ctx.$.node(\"unit\", { unit: enclosed });\n else {\n const date = tryParseDate(enclosed, writeInvalidDateMessage(enclosed));\n s.root = s.ctx.$.node(\"unit\", { meta: enclosed, unit: date });\n }\n};\nexport const enclosingQuote = {\n \"'\": 1,\n '\"': 1\n};\nexport const enclosingChar = {\n \"/\": 1,\n \"'\": 1,\n '\"': 1\n};\nexport const enclosingLiteralTokens = {\n \"d'\": \"'\",\n 'd\"': '\"',\n \"'\": \"'\",\n '\"': '\"'\n};\nexport const enclosingRegexTokens = {\n \"/\": \"/\",\n \"x/\": \"/\"\n};\nexport const enclosingTokens = {\n ...enclosingLiteralTokens,\n ...enclosingRegexTokens\n};\nexport const untilLookaheadIsClosing = {\n \"'\": scanner => scanner.lookahead === `'`,\n '\"': scanner => scanner.lookahead === `\"`,\n \"/\": scanner => scanner.lookahead === `/`\n};\nconst enclosingCharDescriptions = {\n '\"': \"double-quote\",\n \"'\": \"single-quote\",\n \"/\": \"forward slash\"\n};\nexport const writeUnterminatedEnclosedMessage = (fragment, enclosingStart) => `${enclosingStart}${fragment} requires a closing ${enclosingCharDescriptions[enclosingTokens[enclosingStart]]}`;\n",
|
|
85
|
+
"export const writePrefixedPrivateReferenceMessage = (name) => `Private type references should not include '#'. Use '${name}' instead.`;\nexport const shallowOptionalMessage = \"Optional definitions like 'string?' are only valid as properties in an object or tuple\";\nexport const shallowDefaultableMessage = \"Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple\";\n",
|
|
86
|
+
"import { isKeyOf, whitespaceChars } from \"@ark/util\";\nexport const terminatingChars = {\n \"<\": 1,\n \">\": 1,\n \"=\": 1,\n \"|\": 1,\n \"&\": 1,\n \")\": 1,\n \"[\": 1,\n \"%\": 1,\n \",\": 1,\n \":\": 1,\n \"?\": 1,\n \"#\": 1,\n ...whitespaceChars\n};\nexport const finalizingLookaheads = {\n \">\": 1,\n \",\": 1,\n \"\": 1,\n \"=\": 1,\n \"?\": 1\n};\nexport const lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === \">\" ?\n unscanned[0] === \"=\" ?\n // >== would only occur in an expression like Array<number>==5\n // otherwise, >= would only occur as part of a bound like number>=5\n unscanned[1] === \"=\"\n // if > is the end of a generic instantiation, the next token will be\n // an operator or the end of the string\n : unscanned.trimStart() === \"\" ||\n isKeyOf(unscanned.trimStart()[0], terminatingChars)\n // \"=\" is a finalizer on its own (representing a default value),\n // but not with a second \"=\" (an equality comparator)\n : lookahead === \"=\" ? unscanned[0] !== \"=\"\n // \",\" and \"?\" are unambiguously finalizers\n : lookahead === \",\" || lookahead === \"?\";\n",
|
|
87
|
+
"import { writeUnclosedGroupMessage } from \"@ark/util\";\nexport const parseGenericArgs = (name, g, s) => _parseGenericArgs(name, g, s, []);\nconst _parseGenericArgs = (name, g, s, argNodes) => {\n const argState = s.parseUntilFinalizer();\n argNodes.push(argState.root);\n if (argState.finalizer === \">\") {\n if (argNodes.length !== g.params.length) {\n return s.error(writeInvalidGenericArgCountMessage(name, g.names, argNodes.map(arg => arg.expression)));\n }\n return argNodes;\n }\n if (argState.finalizer === \",\")\n return _parseGenericArgs(name, g, s, argNodes);\n return argState.error(writeUnclosedGroupMessage(\">\"));\n};\nexport const writeInvalidGenericArgCountMessage = (name, params, argDefs) => `${name}<${params.join(\", \")}> requires exactly ${params.length} args (got ${argDefs.length}${argDefs.length === 0 ? \"\" : `: ${argDefs.join(\", \")}`})`;\n",
|
|
88
|
+
"import { hasArkKind, writeUnresolvableMessage } from \"@ark/schema\";\nimport { printable, throwParseError, tryParseWellFormedBigint, tryParseWellFormedNumber } from \"@ark/util\";\nimport { writePrefixedPrivateReferenceMessage } from \"../../ast/validate.js\";\nimport { terminatingChars } from \"../tokens.js\";\nimport { parseGenericArgs, writeInvalidGenericArgCountMessage } from \"./genericArgs.js\";\nexport const parseUnenclosed = (s) => {\n const token = s.scanner.shiftUntilLookahead(terminatingChars);\n if (token === \"keyof\")\n s.addPrefix(\"keyof\");\n else\n s.root = unenclosedToNode(s, token);\n};\nexport const parseGenericInstantiation = (name, g, s) => {\n s.scanner.shiftUntilNonWhitespace();\n const lookahead = s.scanner.shift();\n if (lookahead !== \"<\")\n return s.error(writeInvalidGenericArgCountMessage(name, g.names, []));\n const parsedArgs = parseGenericArgs(name, g, s);\n return g(...parsedArgs);\n};\nconst unenclosedToNode = (s, token) => maybeParseReference(s, token) ??\n maybeParseUnenclosedLiteral(s, token) ??\n s.error(token === \"\" ?\n s.scanner.lookahead === \"#\" ?\n writePrefixedPrivateReferenceMessage(s.shiftedBy(1).scanner.shiftUntilLookahead(terminatingChars))\n : writeMissingOperandMessage(s)\n : writeUnresolvableMessage(token));\nconst maybeParseReference = (s, token) => {\n if (s.ctx.args?.[token]) {\n const arg = s.ctx.args[token];\n if (typeof arg !== \"string\")\n return arg;\n return s.ctx.$.node(\"alias\", { reference: arg }, { prereduced: true });\n }\n const resolution = s.ctx.$.maybeResolve(token);\n if (hasArkKind(resolution, \"root\"))\n return resolution;\n if (resolution === undefined)\n return;\n if (hasArkKind(resolution, \"generic\"))\n return parseGenericInstantiation(token, resolution, s);\n return throwParseError(`Unexpected resolution ${printable(resolution)}`);\n};\nconst maybeParseUnenclosedLiteral = (s, token) => {\n const maybeNumber = tryParseWellFormedNumber(token);\n if (maybeNumber !== undefined)\n return s.ctx.$.node(\"unit\", { unit: maybeNumber });\n const maybeBigint = tryParseWellFormedBigint(token);\n if (maybeBigint !== undefined)\n return s.ctx.$.node(\"unit\", { unit: maybeBigint });\n};\nexport const writeMissingOperandMessage = (s) => {\n const operator = s.previousOperator();\n return operator ?\n writeMissingRightOperandMessage(operator, s.scanner.unscanned)\n : writeExpressionExpectedMessage(s.scanner.unscanned);\n};\nexport const writeMissingRightOperandMessage = (token, unscanned = \"\") => `Token '${token}' requires a right operand${unscanned ? ` before '${unscanned}'` : \"\"}`;\nexport const writeExpressionExpectedMessage = (unscanned) => `Expected an expression${unscanned ? ` before '${unscanned}'` : \"\"}`;\n",
|
|
89
|
+
"import { whitespaceChars } from \"@ark/util\";\nimport { enclosingChar, enclosingQuote, parseEnclosed } from \"./enclosed.js\";\nimport { parseUnenclosed, writeMissingOperandMessage } from \"./unenclosed.js\";\nexport const parseOperand = (s) => s.scanner.lookahead === \"\" ? s.error(writeMissingOperandMessage(s))\n : s.scanner.lookahead === \"(\" ? s.shiftedBy(1).reduceGroupOpen()\n : s.scanner.lookaheadIsIn(enclosingChar) ? parseEnclosed(s, s.scanner.shift())\n : s.scanner.lookaheadIsIn(whitespaceChars) ? parseOperand(s.shiftedBy(1))\n : s.scanner.lookahead === \"d\" ?\n s.scanner.nextLookahead in enclosingQuote ?\n parseEnclosed(s, `${s.scanner.shift()}${s.scanner.shift()}`)\n : parseUnenclosed(s)\n : s.scanner.lookahead === \"x\" ?\n s.scanner.nextLookahead === \"/\" ?\n s.shiftedBy(2) && parseEnclosed(s, \"x/\")\n : parseUnenclosed(s)\n : parseUnenclosed(s);\n",
|
|
90
|
+
"export const minComparators = {\n \">\": true,\n \">=\": true\n};\nexport const maxComparators = {\n \"<\": true,\n \"<=\": true\n};\nexport const comparators = {\n \">\": true,\n \">=\": true,\n \"<\": true,\n \"<=\": true,\n \"==\": true\n};\nexport const invertedComparators = {\n \"<\": \">\",\n \">\": \"<\",\n \"<=\": \">=\",\n \">=\": \"<=\",\n \"==\": \"==\"\n};\nexport const writeOpenRangeMessage = (min, comparator) => `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`;\nexport const writeUnpairableComparatorMessage = (comparator) => `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`;\nexport const writeMultipleLeftBoundsMessage = (openLimit, openComparator, limit, comparator) => `An expression may have at most one left bound (parsed ${openLimit}${invertedComparators[openComparator]}, ${limit}${invertedComparators[comparator]})`;\n",
|
|
91
|
+
"import { $ark, writeUnboundableMessage } from \"@ark/schema\";\nimport { isKeyOf, throwParseError } from \"@ark/util\";\nimport { invertedComparators, maxComparators, writeUnpairableComparatorMessage } from \"../../reduce/shared.js\";\nimport { extractDateLiteralSource, isDateLiteral } from \"../operand/date.js\";\nexport const parseBound = (s, start) => {\n const comparator = shiftComparator(s, start);\n if (s.root.hasKind(\"unit\")) {\n if (typeof s.root.unit === \"number\") {\n s.reduceLeftBound(s.root.unit, comparator);\n s.unsetRoot();\n return;\n }\n if (s.root.unit instanceof Date) {\n const literal = `d'${s.root.description ?? s.root.unit.toISOString()}'`;\n s.unsetRoot();\n s.reduceLeftBound(literal, comparator);\n return;\n }\n }\n return parseRightBound(s, comparator);\n};\nexport const comparatorStartChars = {\n \"<\": 1,\n \">\": 1,\n \"=\": 1\n};\nconst shiftComparator = (s, start) => s.scanner.lookaheadIs(\"=\") ?\n `${start}${s.scanner.shift()}`\n : start;\nexport const writeIncompatibleRangeMessage = (l, r) => `Bound kinds ${l} and ${r} are incompatible`;\nexport const getBoundKinds = (comparator, limit, root, boundKind) => {\n if (root.extends($ark.intrinsic.number)) {\n if (typeof limit !== \"number\") {\n return throwParseError(writeInvalidLimitMessage(comparator, limit, boundKind));\n }\n return (comparator === \"==\" ? [\"min\", \"max\"]\n : comparator[0] === \">\" ? [\"min\"]\n : [\"max\"]);\n }\n if (root.extends($ark.intrinsic.lengthBoundable)) {\n if (typeof limit !== \"number\") {\n return throwParseError(writeInvalidLimitMessage(comparator, limit, boundKind));\n }\n return (comparator === \"==\" ? [\"exactLength\"]\n : comparator[0] === \">\" ? [\"minLength\"]\n : [\"maxLength\"]);\n }\n if (root.extends($ark.intrinsic.Date)) {\n // allow either numeric or date limits\n return (comparator === \"==\" ? [\"after\", \"before\"]\n : comparator[0] === \">\" ? [\"after\"]\n : [\"before\"]);\n }\n return throwParseError(writeUnboundableMessage(root.expression));\n};\nconst openLeftBoundToRoot = (leftBound) => ({\n rule: isDateLiteral(leftBound.limit) ?\n extractDateLiteralSource(leftBound.limit)\n : leftBound.limit,\n exclusive: leftBound.comparator.length === 1\n});\nexport const parseRightBound = (s, comparator) => {\n // store the node that will be bounded\n const previousRoot = s.unsetRoot();\n const previousScannerIndex = s.scanner.location;\n s.parseOperand();\n const limitNode = s.unsetRoot();\n // after parsing the next operand, use the locations to get the\n // token from which it was parsed\n const limitToken = s.scanner.sliceChars(previousScannerIndex, s.scanner.location);\n s.root = previousRoot;\n if (!limitNode.hasKind(\"unit\") ||\n (typeof limitNode.unit !== \"number\" && !(limitNode.unit instanceof Date)))\n return s.error(writeInvalidLimitMessage(comparator, limitToken, \"right\"));\n const limit = limitNode.unit;\n // apply the newly-parsed right bound\n const exclusive = comparator.length === 1;\n const boundKinds = getBoundKinds(comparator, typeof limit === \"number\" ? limit : limitToken, previousRoot, \"right\");\n for (const kind of boundKinds) {\n s.constrainRoot(kind, comparator === \"==\" ? { rule: limit } : { rule: limit, exclusive });\n }\n if (!s.branches.leftBound)\n return;\n // if there's an open left bound, perform additional validation and apply it\n if (!isKeyOf(comparator, maxComparators))\n return s.error(writeUnpairableComparatorMessage(comparator));\n const lowerBoundKind = getBoundKinds(s.branches.leftBound.comparator, s.branches.leftBound.limit, previousRoot, \"left\");\n s.constrainRoot(lowerBoundKind[0], openLeftBoundToRoot(s.branches.leftBound));\n s.branches.leftBound = null;\n};\nexport const writeInvalidLimitMessage = (comparator, limit, boundKind) => `Comparator ${boundKind === \"left\" ? invertedComparators[comparator] : comparator} must be ${boundKind === \"left\" ? \"preceded\" : \"followed\"} by a corresponding literal (was ${limit})`;\n",
|
|
92
|
+
"import { terminatingChars } from \"../tokens.js\";\nexport const parseBrand = (s) => {\n s.scanner.shiftUntilNonWhitespace();\n const brandName = s.scanner.shiftUntilLookahead(terminatingChars);\n s.root = s.root.brand(brandName);\n};\n",
|
|
93
|
+
"import { tryParseInteger } from \"@ark/util\";\nimport { terminatingChars } from \"../tokens.js\";\nexport const parseDivisor = (s) => {\n s.scanner.shiftUntilNonWhitespace();\n const divisorToken = s.scanner.shiftUntilLookahead(terminatingChars);\n const divisor = tryParseInteger(divisorToken, {\n errorOnFail: writeInvalidDivisorMessage(divisorToken)\n });\n if (divisor === 0)\n s.error(writeInvalidDivisorMessage(0));\n s.root = s.root.constrain(\"divisor\", divisor);\n};\nexport const writeInvalidDivisorMessage = (divisor) => `% operator must be followed by a non-zero integer literal (was ${divisor})`;\n",
|
|
94
|
+
"import { isKeyOf, whitespaceChars } from \"@ark/util\";\nimport { lookaheadIsFinalizing } from \"../tokens.js\";\nimport { comparatorStartChars, parseBound } from \"./bounds.js\";\nimport { parseBrand } from \"./brand.js\";\nimport { parseDivisor } from \"./divisor.js\";\nexport const parseOperator = (s) => {\n const lookahead = s.scanner.shift();\n return (lookahead === \"\" ? s.finalize(\"\")\n : lookahead === \"[\" ?\n s.scanner.shift() === \"]\" ?\n s.setRoot(s.root.array())\n : s.error(incompleteArrayTokenMessage)\n : lookahead === \"|\" ?\n s.scanner.lookahead === \">\" ?\n s.shiftedBy(1).pushRootToBranch(\"|>\")\n : s.pushRootToBranch(lookahead)\n : lookahead === \"&\" ? s.pushRootToBranch(lookahead)\n : lookahead === \")\" ? s.finalizeGroup()\n : lookaheadIsFinalizing(lookahead, s.scanner.unscanned) ?\n s.finalize(lookahead)\n : isKeyOf(lookahead, comparatorStartChars) ? parseBound(s, lookahead)\n : lookahead === \"%\" ? parseDivisor(s)\n : lookahead === \"#\" ? parseBrand(s)\n : lookahead in whitespaceChars ? parseOperator(s)\n : s.error(writeUnexpectedCharacterMessage(lookahead)));\n};\nexport const writeUnexpectedCharacterMessage = (char, shouldBe = \"\") => `'${char}' is not allowed here${shouldBe && ` (should be ${shouldBe})`}`;\nexport const incompleteArrayTokenMessage = `Missing expected ']'`;\n",
|
|
95
|
+
"export const parseDefault = (s) => {\n // store the node that will be bounded\n const baseNode = s.unsetRoot();\n s.parseOperand();\n const defaultNode = s.unsetRoot();\n // after parsing the next operand, use the locations to get the\n // token from which it was parsed\n if (!defaultNode.hasKind(\"unit\"))\n return s.error(writeNonLiteralDefaultMessage(defaultNode.expression));\n const defaultValue = defaultNode.unit instanceof Date ?\n () => new Date(defaultNode.unit)\n : defaultNode.unit;\n return [baseNode, \"=\", defaultValue];\n};\nexport const writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must be a literal value`;\n",
|
|
96
|
+
"import { Scanner, throwInternalError, throwParseError } from \"@ark/util\";\nimport { RuntimeState } from \"./reduce/dynamic.js\";\nimport { parseDefault } from \"./shift/operator/default.js\";\nimport { writeUnexpectedCharacterMessage } from \"./shift/operator/operator.js\";\nexport const parseString = (def, ctx) => {\n const aliasResolution = ctx.$.maybeResolveRoot(def);\n if (aliasResolution)\n return aliasResolution;\n if (def.endsWith(\"[]\")) {\n const possibleElementResolution = ctx.$.maybeResolveRoot(def.slice(0, -2));\n if (possibleElementResolution)\n return possibleElementResolution.array();\n }\n const s = new RuntimeState(new Scanner(def), ctx);\n const node = fullStringParse(s);\n if (s.finalizer === \">\")\n throwParseError(writeUnexpectedCharacterMessage(\">\"));\n return node;\n};\nexport const fullStringParse = (s) => {\n s.parseOperand();\n let result = parseUntilFinalizer(s).root;\n if (!result) {\n return throwInternalError(`Root was unexpectedly unset after parsing string '${s.scanner.scanned}'`);\n }\n if (s.finalizer === \"=\")\n result = parseDefault(s);\n else if (s.finalizer === \"?\")\n result = [result, \"?\"];\n s.scanner.shiftUntilNonWhitespace();\n if (s.scanner.lookahead) {\n // throw a parse error if non-whitespace characters made it here without being parsed\n throwParseError(writeUnexpectedCharacterMessage(s.scanner.lookahead));\n }\n return result;\n};\nexport const parseUntilFinalizer = (s) => {\n while (s.finalizer === undefined)\n next(s);\n return s;\n};\nconst next = (s) => s.hasRoot() ? s.parseOperator() : s.parseOperand();\n",
|
|
97
|
+
"import { isKeyOf, throwInternalError, throwParseError, writeUnclosedGroupMessage, writeUnmatchedGroupCloseMessage } from \"@ark/util\";\nimport { parseOperand } from \"../shift/operand/operand.js\";\nimport { parseOperator } from \"../shift/operator/operator.js\";\nimport { parseUntilFinalizer } from \"../string.js\";\nimport { invertedComparators, minComparators, writeMultipleLeftBoundsMessage, writeOpenRangeMessage, writeUnpairableComparatorMessage } from \"./shared.js\";\nexport class RuntimeState {\n root;\n branches = {\n prefixes: [],\n leftBound: null,\n intersection: null,\n union: null,\n pipe: null\n };\n finalizer;\n groups = [];\n scanner;\n ctx;\n constructor(scanner, ctx) {\n this.scanner = scanner;\n this.ctx = ctx;\n }\n error(message) {\n return throwParseError(message);\n }\n hasRoot() {\n return this.root !== undefined;\n }\n setRoot(root) {\n this.root = root;\n }\n unsetRoot() {\n const value = this.root;\n this.root = undefined;\n return value;\n }\n constrainRoot(...args) {\n this.root = this.root.constrain(args[0], args[1]);\n }\n finalize(finalizer) {\n if (this.groups.length)\n return this.error(writeUnclosedGroupMessage(\")\"));\n this.finalizeBranches();\n this.finalizer = finalizer;\n }\n reduceLeftBound(limit, comparator) {\n const invertedComparator = invertedComparators[comparator];\n if (!isKeyOf(invertedComparator, minComparators))\n return this.error(writeUnpairableComparatorMessage(comparator));\n if (this.branches.leftBound) {\n return this.error(writeMultipleLeftBoundsMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator, limit, invertedComparator));\n }\n this.branches.leftBound = {\n comparator: invertedComparator,\n limit\n };\n }\n finalizeBranches() {\n this.assertRangeUnset();\n if (this.branches.pipe) {\n this.pushRootToBranch(\"|>\");\n this.root = this.branches.pipe;\n return;\n }\n if (this.branches.union) {\n this.pushRootToBranch(\"|\");\n this.root = this.branches.union;\n return;\n }\n if (this.branches.intersection) {\n this.pushRootToBranch(\"&\");\n this.root = this.branches.intersection;\n return;\n }\n this.applyPrefixes();\n }\n finalizeGroup() {\n this.finalizeBranches();\n const topBranchState = this.groups.pop();\n if (!topBranchState) {\n return this.error(writeUnmatchedGroupCloseMessage(\")\", this.scanner.unscanned));\n }\n this.branches = topBranchState;\n }\n addPrefix(prefix) {\n this.branches.prefixes.push(prefix);\n }\n applyPrefixes() {\n while (this.branches.prefixes.length) {\n const lastPrefix = this.branches.prefixes.pop();\n this.root =\n lastPrefix === \"keyof\" ?\n this.root.keyof()\n : throwInternalError(`Unexpected prefix '${lastPrefix}'`);\n }\n }\n pushRootToBranch(token) {\n this.assertRangeUnset();\n this.applyPrefixes();\n const root = this.root;\n this.root = undefined;\n this.branches.intersection =\n this.branches.intersection?.rawAnd(root) ?? root;\n if (token === \"&\")\n return;\n this.branches.union =\n this.branches.union?.rawOr(this.branches.intersection) ??\n this.branches.intersection;\n this.branches.intersection = null;\n if (token === \"|\")\n return;\n this.branches.pipe =\n this.branches.pipe?.rawPipeOnce(this.branches.union) ??\n this.branches.union;\n this.branches.union = null;\n }\n parseUntilFinalizer() {\n return parseUntilFinalizer(new RuntimeState(this.scanner, this.ctx));\n }\n parseOperator() {\n return parseOperator(this);\n }\n parseOperand() {\n return parseOperand(this);\n }\n assertRangeUnset() {\n if (this.branches.leftBound) {\n return this.error(writeOpenRangeMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator));\n }\n }\n reduceGroupOpen() {\n this.groups.push(this.branches);\n this.branches = {\n prefixes: [],\n leftBound: null,\n union: null,\n intersection: null,\n pipe: null\n };\n }\n previousOperator() {\n return (this.branches.leftBound?.comparator ??\n this.branches.prefixes[this.branches.prefixes.length - 1] ??\n (this.branches.intersection ? \"&\"\n : this.branches.union ? \"|\"\n : this.branches.pipe ? \"|>\"\n : undefined));\n }\n shiftedBy(count) {\n this.scanner.jumpForward(count);\n return this;\n }\n}\n",
|
|
98
|
+
"import { GenericRoot } from \"@ark/schema\";\nimport { throwParseError } from \"@ark/util\";\nimport { RuntimeState } from \"./parser/reduce/dynamic.js\";\nimport { terminatingChars } from \"./parser/shift/tokens.js\";\nimport { parseUntilFinalizer } from \"./parser/string.js\";\nexport const Generic = GenericRoot;\nexport const emptyGenericParameterMessage = \"An empty string is not a valid generic parameter name\";\nexport const parseGenericParamName = (scanner, result, ctx) => {\n scanner.shiftUntilNonWhitespace();\n const name = scanner.shiftUntilLookahead(terminatingChars);\n if (name === \"\") {\n // if we've reached the end of the string and have parsed at least one\n // param, return the valid result\n if (scanner.lookahead === \"\" && result.length)\n return result;\n return throwParseError(emptyGenericParameterMessage);\n }\n scanner.shiftUntilNonWhitespace();\n return _parseOptionalConstraint(scanner, name, result, ctx);\n};\nconst extendsToken = \"extends \";\nconst _parseOptionalConstraint = (scanner, name, result, ctx) => {\n scanner.shiftUntilNonWhitespace();\n if (scanner.unscanned.startsWith(extendsToken))\n scanner.jumpForward(extendsToken.length);\n else {\n // if we don't have a contraining token here, return now so we can\n // assume in the rest of the function body we do have a constraint\n if (scanner.lookahead === \",\")\n scanner.shift();\n result.push(name);\n return parseGenericParamName(scanner, result, ctx);\n }\n const s = parseUntilFinalizer(new RuntimeState(scanner, ctx));\n result.push([name, s.root]);\n return parseGenericParamName(scanner, result, ctx);\n};\n",
|
|
99
|
+
"import { Callable, throwParseError } from \"@ark/util\";\nexport class InternalFnParser extends Callable {\n constructor($) {\n const attach = {\n $: $,\n raw: $.fn\n };\n super((...signature) => {\n const returnOperatorIndex = signature.indexOf(\":\");\n const lastParamIndex = returnOperatorIndex === -1 ?\n signature.length - 1\n : returnOperatorIndex - 1;\n const paramDefs = signature.slice(0, lastParamIndex + 1);\n const paramTuple = $.parse(paramDefs).assertHasKind(\"intersection\");\n let returnType = $.intrinsic.unknown;\n if (returnOperatorIndex !== -1) {\n if (returnOperatorIndex !== signature.length - 2)\n return throwParseError(badFnReturnTypeMessage);\n returnType = $.parse(signature[returnOperatorIndex + 1]);\n }\n return (impl) => new InternalTypedFn(impl, paramTuple, returnType);\n }, { attach });\n }\n}\nexport class InternalTypedFn extends Callable {\n raw;\n params;\n returns;\n expression;\n constructor(raw, params, returns) {\n const typedName = `typed ${raw.name}`;\n const typed = {\n // assign to a key with the expected name to force it to be created that way\n [typedName]: (...args) => {\n const validatedArgs = params.assert(args);\n const returned = raw(...validatedArgs);\n return returns.assert(returned);\n }\n }[typedName];\n super(typed);\n this.raw = raw;\n this.params = params;\n this.returns = returns;\n let argsExpression = params.expression;\n if (argsExpression[0] === \"[\" &&\n argsExpression[argsExpression.length - 1] === \"]\")\n argsExpression = argsExpression.slice(1, -1);\n else if (argsExpression.endsWith(\"[]\"))\n argsExpression = `...${argsExpression}`;\n this.expression = `(${argsExpression}) => ${returns?.expression ?? \"unknown\"}`;\n }\n}\nexport const badFnReturnTypeMessage = `\":\" must be followed by exactly one return type e.g:\nfn(\"string\", \":\", \"number\")(s => s.length)`;\n",
|
|
100
|
+
"import { intrinsic } from \"@ark/schema\";\nimport { Callable, domainOf, throwParseError } from \"@ark/util\";\nexport class InternalMatchParser extends Callable {\n $;\n constructor($) {\n super((...args) => new InternalChainedMatchParser($)(...args), {\n bind: $\n });\n this.$ = $;\n }\n in(def) {\n return new InternalChainedMatchParser(this.$, def === undefined ? undefined : this.$.parse(def));\n }\n at(key, cases) {\n return new InternalChainedMatchParser(this.$).at(key, cases);\n }\n case(when, then) {\n return new InternalChainedMatchParser(this.$).case(when, then);\n }\n}\nexport class InternalChainedMatchParser extends Callable {\n $;\n in;\n key;\n branches = [];\n constructor($, In) {\n super(cases => this.caseEntries(Object.entries(cases).map(([k, v]) => k === \"default\" ? [k, v] : [this.$.parse(k), v])));\n this.$ = $;\n this.in = In;\n }\n at(key, cases) {\n if (this.key)\n throwParseError(doubleAtMessage);\n if (this.branches.length)\n throwParseError(chainedAtMessage);\n this.key = key;\n return cases ? this.match(cases) : this;\n }\n case(def, resolver) {\n return this.caseEntry(this.$.parse(def), resolver);\n }\n caseEntry(node, resolver) {\n const wrappableNode = this.key ? this.$.parse({ [this.key]: node }) : node;\n const branch = wrappableNode.pipe(resolver);\n this.branches.push(branch);\n return this;\n }\n match(cases) {\n return this(cases);\n }\n strings(cases) {\n return this.caseEntries(Object.entries(cases).map(([k, v]) => k === \"default\" ?\n [k, v]\n : [this.$.node(\"unit\", { unit: k }), v]));\n }\n caseEntries(entries) {\n for (let i = 0; i < entries.length; i++) {\n const [k, v] = entries[i];\n if (k === \"default\") {\n if (i !== entries.length - 1) {\n throwParseError(`default may only be specified as the last key of a switch definition`);\n }\n return this.default(v);\n }\n if (typeof v !== \"function\") {\n return throwParseError(`Value for case \"${k}\" must be a function (was ${domainOf(v)})`);\n }\n this.caseEntry(k, v);\n }\n return this;\n }\n default(defaultCase) {\n if (typeof defaultCase === \"function\")\n this.case(intrinsic.unknown, defaultCase);\n const schema = {\n branches: this.branches,\n ordered: true\n };\n if (defaultCase === \"never\" || defaultCase === \"assert\")\n schema.meta = { onFail: throwOnDefault };\n const cases = this.$.node(\"union\", schema);\n if (!this.in)\n return this.$.finalize(cases);\n let inputValidatedCases = this.in.pipe(cases);\n if (defaultCase === \"never\" || defaultCase === \"assert\") {\n inputValidatedCases = inputValidatedCases.configureReferences({\n onFail: throwOnDefault\n }, \"self\");\n }\n return this.$.finalize(inputValidatedCases);\n }\n}\nexport const throwOnDefault = errors => errors.throw();\nexport const chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`;\nexport const doubleAtMessage = `At most one key matcher may be specified per expression`;\n",
|
|
101
|
+
"import { isArray } from \"@ark/util\";\nimport { parseInnerDefinition } from \"./definition.js\";\nexport const parseProperty = (def, ctx) => {\n if (isArray(def)) {\n if (def[1] === \"=\")\n return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), \"=\", def[2]];\n if (def[1] === \"?\")\n return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), \"?\"];\n }\n // string-embedded defaults/optionals are handled by the string parser\n return parseInnerDefinition(def, ctx);\n};\n// single quote use here is better for TypeScript's inlined error to avoid escapes\nexport const invalidOptionalKeyKindMessage = `Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`;\n// single quote use here is better for TypeScript's inlined error to avoid escapes\nexport const invalidDefaultableKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`;\n",
|
|
102
|
+
"import { intrinsic, normalizeIndex } from \"@ark/schema\";\nimport { append, Backslash, isArray, isEmptyObject, printable, stringAndSymbolicEntriesOf, throwParseError } from \"@ark/util\";\nimport { invalidDefaultableKeyKindMessage, invalidOptionalKeyKindMessage, parseProperty } from \"./property.js\";\nexport const parseObjectLiteral = (def, ctx) => {\n let spread;\n const structure = {};\n // We only allow a spread operator to be used as the first key in an object\n // because to match JS behavior any keys before the spread are overwritten\n // by the values in the target object, so there'd be no useful purpose in having it\n // anywhere except for the beginning.\n const defEntries = stringAndSymbolicEntriesOf(def);\n for (const [k, v] of defEntries) {\n const parsedKey = preparseKey(k);\n if (parsedKey.kind === \"spread\") {\n if (!isEmptyObject(structure))\n return throwParseError(nonLeadingSpreadError);\n const operand = ctx.$.parseOwnDefinitionFormat(v, ctx);\n // treat object domain as empty for spreading (useful for generic constraints)\n if (operand.equals(intrinsic.object))\n continue;\n if (!operand.hasKind(\"intersection\") ||\n // still error on attempts to spread proto nodes like ...Date\n !operand.basis?.equals(intrinsic.object)) {\n return throwParseError(writeInvalidSpreadTypeMessage(operand.expression));\n }\n spread = operand.structure;\n continue;\n }\n if (parsedKey.kind === \"undeclared\") {\n if (v !== \"reject\" && v !== \"delete\" && v !== \"ignore\")\n throwParseError(writeInvalidUndeclaredBehaviorMessage(v));\n structure.undeclared = v;\n continue;\n }\n const parsedValue = parseProperty(v, ctx);\n const parsedEntryKey = parsedKey;\n if (parsedKey.kind === \"required\") {\n if (!isArray(parsedValue)) {\n appendNamedProp(structure, \"required\", {\n key: parsedKey.normalized,\n value: parsedValue\n }, ctx);\n }\n else {\n appendNamedProp(structure, \"optional\", parsedValue[1] === \"=\" ?\n {\n key: parsedKey.normalized,\n value: parsedValue[0],\n default: parsedValue[2]\n }\n : {\n key: parsedKey.normalized,\n value: parsedValue[0]\n }, ctx);\n }\n continue;\n }\n if (isArray(parsedValue)) {\n if (parsedValue[1] === \"?\")\n throwParseError(invalidOptionalKeyKindMessage);\n if (parsedValue[1] === \"=\")\n throwParseError(invalidDefaultableKeyKindMessage);\n }\n // value must be a BaseRoot at this point\n if (parsedKey.kind === \"optional\") {\n appendNamedProp(structure, \"optional\", {\n key: parsedKey.normalized,\n value: parsedValue\n }, ctx);\n continue;\n }\n // must be index at this point\n const signature = ctx.$.parseOwnDefinitionFormat(parsedEntryKey.normalized, ctx);\n const normalized = normalizeIndex(signature, parsedValue, ctx.$);\n if (normalized.index)\n structure.index = append(structure.index, normalized.index);\n if (normalized.required)\n structure.required = append(structure.required, normalized.required);\n }\n const structureNode = ctx.$.node(\"structure\", structure);\n return ctx.$.parseSchema({\n domain: \"object\",\n structure: spread?.merge(structureNode) ?? structureNode\n });\n};\nconst appendNamedProp = (structure, kind, inner, ctx) => {\n structure[kind] = append(\n // doesn't seem like this cast should be necessary\n structure[kind], ctx.$.node(kind, inner));\n};\nexport const writeInvalidUndeclaredBehaviorMessage = (actual) => `Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${printable(actual)})`;\nexport const nonLeadingSpreadError = \"Spread operator may only be used as the first key in an object\";\nexport const preparseKey = (key) => typeof key === \"symbol\" ? { kind: \"required\", normalized: key }\n : key[key.length - 1] === \"?\" ?\n key[key.length - 2] === Backslash ?\n { kind: \"required\", normalized: `${key.slice(0, -2)}?` }\n : {\n kind: \"optional\",\n normalized: key.slice(0, -1)\n }\n : key[0] === \"[\" && key[key.length - 1] === \"]\" ?\n { kind: \"index\", normalized: key.slice(1, -1) }\n : key[0] === Backslash && key[1] === \"[\" && key[key.length - 1] === \"]\" ?\n { kind: \"required\", normalized: key.slice(1) }\n : key === \"...\" ? { kind: \"spread\" }\n : key === \"+\" ? { kind: \"undeclared\" }\n : {\n kind: \"required\",\n normalized: key === \"\\\\...\" ? \"...\"\n : key === \"\\\\+\" ? \"+\"\n : key\n };\nexport const writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`;\n",
|
|
103
|
+
"import { Disjoint, intersectNodesRoot, pipeNodesRoot } from \"@ark/schema\";\nimport { objectKindOrDomainOf, throwParseError } from \"@ark/util\";\nimport { shallowDefaultableMessage, shallowOptionalMessage } from \"./ast/validate.js\";\nimport { writeMissingRightOperandMessage } from \"./shift/operand/unenclosed.js\";\nexport const maybeParseTupleExpression = (def, ctx) => isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx)\n : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx)\n : null;\nexport const parseKeyOfTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[1], ctx).keyof();\nconst parseBranchTuple = (def, ctx) => {\n if (def[2] === undefined)\n return throwParseError(writeMissingRightOperandMessage(def[1], \"\"));\n const l = ctx.$.parseOwnDefinitionFormat(def[0], ctx);\n const r = ctx.$.parseOwnDefinitionFormat(def[2], ctx);\n if (def[1] === \"|\")\n return ctx.$.node(\"union\", { branches: [l, r] });\n const result = def[1] === \"&\" ?\n intersectNodesRoot(l, r, ctx.$)\n : pipeNodesRoot(l, r, ctx.$);\n if (result instanceof Disjoint)\n return result.throw();\n return result;\n};\nconst parseArrayTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).array();\nexport const parseMorphTuple = (def, ctx) => {\n if (typeof def[2] !== \"function\") {\n return throwParseError(writeMalformedFunctionalExpressionMessage(\"=>\", def[2]));\n }\n return ctx.$.parseOwnDefinitionFormat(def[0], ctx).pipe(def[2]);\n};\nexport const writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === \":\" ? \"Narrow\" : \"Morph\"} expression requires a function following '${operator}' (was ${typeof value})`;\nexport const parseNarrowTuple = (def, ctx) => {\n if (typeof def[2] !== \"function\") {\n return throwParseError(writeMalformedFunctionalExpressionMessage(\":\", def[2]));\n }\n return ctx.$.parseOwnDefinitionFormat(def[0], ctx).constrain(\"predicate\", def[2]);\n};\nconst parseMetaTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configure(def[2], def[3]);\nconst defineIndexOneParsers = (parsers) => parsers;\nconst postfixParsers = defineIndexOneParsers({\n \"[]\": parseArrayTuple,\n \"?\": () => throwParseError(shallowOptionalMessage)\n});\nconst infixParsers = defineIndexOneParsers({\n \"|\": parseBranchTuple,\n \"&\": parseBranchTuple,\n \":\": parseNarrowTuple,\n \"=>\": parseMorphTuple,\n \"|>\": parseBranchTuple,\n \"@\": parseMetaTuple,\n // since object and tuple literals parse there via `parseProperty`,\n // they must be shallow if parsed directly as a tuple expression\n \"=\": () => throwParseError(shallowDefaultableMessage)\n});\nconst indexOneParsers = { ...postfixParsers, ...infixParsers };\nconst isIndexOneExpression = (def) => indexOneParsers[def[1]] !== undefined;\nconst defineIndexZeroParsers = (parsers) => parsers;\nconst indexZeroParsers = defineIndexZeroParsers({\n keyof: parseKeyOfTuple,\n instanceof: (def, ctx) => {\n if (typeof def[1] !== \"function\") {\n return throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1])));\n }\n const branches = def\n .slice(1)\n .map(ctor => typeof ctor === \"function\" ?\n ctx.$.node(\"proto\", { proto: ctor })\n : throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor))));\n return branches.length === 1 ?\n branches[0]\n : ctx.$.node(\"union\", { branches });\n },\n \"===\": (def, ctx) => ctx.$.units(def.slice(1))\n});\nconst isIndexZeroExpression = (def) => indexZeroParsers[def[0]] !== undefined;\nexport const writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`;\n",
|
|
104
|
+
"import { $ark, makeRootAndArrayPropertiesMutable, postfixAfterOptionalOrDefaultableMessage } from \"@ark/schema\";\nimport { append, isArray, isEmptyObject, throwParseError } from \"@ark/util\";\nimport { parseProperty } from \"./property.js\";\nexport const parseTupleLiteral = (def, ctx) => {\n let sequences = [{}];\n let i = 0;\n while (i < def.length) {\n let spread = false;\n if (def[i] === \"...\" && i < def.length - 1) {\n spread = true;\n i++;\n }\n const parsedProperty = parseProperty(def[i], ctx);\n const [valueNode, operator, possibleDefaultValue] = !isArray(parsedProperty) ? [parsedProperty] : parsedProperty;\n i++;\n if (spread) {\n if (!valueNode.extends($ark.intrinsic.Array))\n return throwParseError(writeNonArraySpreadMessage(valueNode.expression));\n // a spread must be distributed over branches e.g.:\n // def: [string, ...(number[] | [true, false])]\n // nodes: [string, ...number[]] | [string, true, false]\n sequences = sequences.flatMap(base => \n // since appendElement mutates base, we have to shallow-ish clone it for each branch\n valueNode.distribute(branch => appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)));\n }\n else {\n sequences = sequences.map(base => {\n if (operator === \"?\")\n return appendOptionalElement(base, valueNode);\n if (operator === \"=\")\n return appendDefaultableElement(base, valueNode, possibleDefaultValue);\n return appendRequiredElement(base, valueNode);\n });\n }\n }\n return ctx.$.parseSchema(sequences.map(sequence => isEmptyObject(sequence) ?\n {\n proto: Array,\n exactLength: 0\n }\n : {\n proto: Array,\n sequence\n }));\n};\nconst appendRequiredElement = (base, element) => {\n if (base.defaultables || base.optionals) {\n return throwParseError(base.variadic ?\n // e.g. [boolean = true, ...string[], number]\n postfixAfterOptionalOrDefaultableMessage\n // e.g. [string?, number]\n : requiredPostOptionalMessage);\n }\n if (base.variadic) {\n // e.g. [...string[], number]\n base.postfix = append(base.postfix, element);\n }\n else {\n // e.g. [string, number]\n base.prefix = append(base.prefix, element);\n }\n return base;\n};\nconst appendOptionalElement = (base, element) => {\n if (base.variadic)\n // e.g. [...string[], number?]\n return throwParseError(optionalOrDefaultableAfterVariadicMessage);\n // e.g. [string, number?]\n base.optionals = append(base.optionals, element);\n return base;\n};\nconst appendDefaultableElement = (base, element, value) => {\n if (base.variadic)\n // e.g. [...string[], number = 0]\n return throwParseError(optionalOrDefaultableAfterVariadicMessage);\n if (base.optionals)\n // e.g. [string?, number = 0]\n return throwParseError(defaultablePostOptionalMessage);\n // value's assignability to element will be checked when the\n // sequence is instantiated by @ark/schema\n // e.g. [string, number = 0]\n base.defaultables = append(base.defaultables, [[element, value]]);\n return base;\n};\nconst appendVariadicElement = (base, element) => {\n // e.g. [...string[], number, ...string[]]\n if (base.postfix)\n throwParseError(multipleVariadicMesage);\n if (base.variadic) {\n if (!base.variadic.equals(element)) {\n // e.g. [...string[], ...number[]]\n throwParseError(multipleVariadicMesage);\n }\n // e.g. [...string[], ...string[]]\n // do nothing, second spread doesn't change the type\n }\n else {\n // e.g. [string, ...number[]]\n base.variadic = element.internal;\n }\n return base;\n};\nconst appendSpreadBranch = (base, branch) => {\n const spread = branch.select({ method: \"find\", kind: \"sequence\" });\n if (!spread) {\n // the only array with no sequence reference is unknown[]\n return appendVariadicElement(base, $ark.intrinsic.unknown);\n }\n if (spread.prefix)\n for (const node of spread.prefix)\n appendRequiredElement(base, node);\n if (spread.optionals)\n for (const node of spread.optionals)\n appendOptionalElement(base, node);\n if (spread.variadic)\n appendVariadicElement(base, spread.variadic);\n if (spread.postfix)\n for (const node of spread.postfix)\n appendRequiredElement(base, node);\n return base;\n};\nexport const writeNonArraySpreadMessage = (operand) => `Spread element must be an array (was ${operand})`;\nexport const multipleVariadicMesage = \"A tuple may have at most one variadic element\";\nexport const requiredPostOptionalMessage = \"A required element may not follow an optional element\";\nexport const optionalOrDefaultableAfterVariadicMessage = \"An optional element may not follow a variadic element\";\nexport const spreadOptionalMessage = \"A spread element cannot be optional\";\nexport const spreadDefaultableMessage = \"A spread element cannot have a default\";\nexport const defaultablePostOptionalMessage = \"A defaultable element may not follow an optional element without a default\";\n",
|
|
105
|
+
"import { hasArkKind } from \"@ark/schema\";\nimport { domainOf, hasDomain, isThunk, objectKindOf, printable, throwParseError, uncapitalize } from \"@ark/util\";\nimport { parseObjectLiteral } from \"./objectLiteral.js\";\nimport { parseString } from \"./string.js\";\nimport { maybeParseTupleExpression } from \"./tupleExpressions.js\";\nimport { parseTupleLiteral } from \"./tupleLiteral.js\";\nconst parseCache = {};\nexport const parseInnerDefinition = (def, ctx) => {\n if (typeof def === \"string\") {\n if (ctx.args && Object.keys(ctx.args).some(k => def.includes(k))) {\n // we can only rely on the cache if there are no contextual\n // resolutions like \"this\" or generic args\n return parseString(def, ctx);\n }\n const scopeCache = (parseCache[ctx.$.name] ??= {});\n return (scopeCache[def] ??= parseString(def, ctx));\n }\n return hasDomain(def, \"object\") ?\n parseObject(def, ctx)\n : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)));\n};\nexport const parseObject = (def, ctx) => {\n const objectKind = objectKindOf(def);\n switch (objectKind) {\n case undefined:\n if (hasArkKind(def, \"root\"))\n return def;\n if (\"~standard\" in def)\n return parseStandardSchema(def, ctx);\n return parseObjectLiteral(def, ctx);\n case \"Array\":\n return parseTuple(def, ctx);\n case \"RegExp\":\n return ctx.$.node(\"intersection\", {\n domain: \"string\",\n pattern: def\n }, { prereduced: true });\n case \"Function\": {\n const resolvedDef = isThunk(def) ? def() : def;\n if (hasArkKind(resolvedDef, \"root\"))\n return resolvedDef;\n return throwParseError(writeBadDefinitionTypeMessage(\"Function\"));\n }\n default:\n return throwParseError(writeBadDefinitionTypeMessage(objectKind ?? printable(def)));\n }\n};\nconst parseStandardSchema = (def, ctx) => ctx.$.intrinsic.unknown.pipe((v, ctx) => {\n const result = def[\"~standard\"].validate(v);\n if (!result.issues)\n return result.value;\n for (const { message, path } of result.issues) {\n if (path) {\n if (path.length) {\n ctx.error({\n problem: uncapitalize(message),\n relativePath: path.map(k => (typeof k === \"object\" ? k.key : k))\n });\n }\n else {\n ctx.error({\n message\n });\n }\n }\n else {\n ctx.error({\n message\n });\n }\n }\n});\nexport const parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx);\nexport const writeBadDefinitionTypeMessage = (actual) => `Type definitions must be strings or objects (was ${actual})`;\n",
|
|
106
|
+
"import { ArkErrors, BaseRoot, GenericRoot } from \"@ark/schema\";\nimport { Callable, Hkt } from \"@ark/util\";\nexport class InternalTypeParser extends Callable {\n constructor($) {\n const attach = Object.assign({\n errors: ArkErrors,\n hkt: Hkt,\n $: $,\n raw: $.parse,\n module: $.constructor.module,\n scope: $.constructor.scope,\n declare: $.declare,\n define: $.define,\n match: $.match,\n generic: $.generic,\n schema: $.schema,\n // this won't be defined during bootstrapping, but externally always will be\n keywords: $.ambient,\n unit: $.unit,\n enumerated: $.enumerated,\n instanceOf: $.instanceOf,\n valueOf: $.valueOf,\n or: $.or,\n and: $.and,\n merge: $.merge,\n pipe: $.pipe,\n fn: $.fn\n }, \n // also won't be defined during bootstrapping\n $.ambientAttachments);\n super((...args) => {\n if (args.length === 1) {\n // treat as a simple definition\n return $.parse(args[0]);\n }\n if (args.length === 2 &&\n typeof args[0] === \"string\" &&\n args[0][0] === \"<\" &&\n args[0][args[0].length - 1] === \">\") {\n // if there are exactly two args, the first of which looks like <${string}>,\n // treat as a generic\n const paramString = args[0].slice(1, -1);\n const params = $.parseGenericParams(paramString, {});\n return new GenericRoot(params, args[1], $, $, null);\n }\n // otherwise, treat as a tuple expression. technically, this also allows\n // non-expression tuple definitions to be parsed, but it's not a supported\n // part of the API as specified by the associated types\n return $.parse(args);\n }, {\n attach\n });\n }\n}\nexport const Type = BaseRoot;\n",
|
|
107
|
+
"import { $ark, BaseScope, hasArkKind, parseGeneric } from \"@ark/schema\";\nimport { Scanner, enumValues, flatMorph, isArray, isThunk, throwParseError } from \"@ark/util\";\nimport { InternalFnParser } from \"./fn.js\";\nimport { parseGenericParamName } from \"./generic.js\";\nimport { InternalMatchParser } from \"./match.js\";\nimport { shallowDefaultableMessage, shallowOptionalMessage } from \"./parser/ast/validate.js\";\nimport { parseInnerDefinition } from \"./parser/definition.js\";\nimport { InternalTypeParser } from \"./type.js\";\nexport const $arkTypeRegistry = $ark;\nexport class InternalScope extends BaseScope {\n get ambientAttachments() {\n if (!$arkTypeRegistry.typeAttachments)\n return;\n return this.cacheGetter(\"ambientAttachments\", flatMorph($arkTypeRegistry.typeAttachments, (k, v) => [\n k,\n this.bindReference(v)\n ]));\n }\n preparseOwnAliasEntry(alias, def) {\n const firstParamIndex = alias.indexOf(\"<\");\n if (firstParamIndex === -1) {\n if (hasArkKind(def, \"module\") || hasArkKind(def, \"generic\"))\n return [alias, def];\n const qualifiedName = this.name === \"ark\" ? alias\n : alias === \"root\" ? this.name\n : `${this.name}.${alias}`;\n const config = this.resolvedConfig.keywords?.[qualifiedName];\n if (config)\n def = [def, \"@\", config];\n return [alias, def];\n }\n if (alias[alias.length - 1] !== \">\") {\n throwParseError(`'>' must be the last character of a generic declaration in a scope`);\n }\n const name = alias.slice(0, firstParamIndex);\n const paramString = alias.slice(firstParamIndex + 1, -1);\n return [\n name,\n // use a thunk definition for the generic so that we can parse\n // constraints within the current scope\n () => {\n const params = this.parseGenericParams(paramString, { alias: name });\n const generic = parseGeneric(params, def, this);\n return generic;\n }\n ];\n }\n parseGenericParams(def, opts) {\n return parseGenericParamName(new Scanner(def), [], this.createParseContext({\n ...opts,\n def,\n prefix: \"generic\"\n }));\n }\n normalizeRootScopeValue(resolution) {\n if (isThunk(resolution) && !hasArkKind(resolution, \"generic\"))\n return resolution();\n return resolution;\n }\n preparseOwnDefinitionFormat(def, opts) {\n return {\n ...opts,\n def,\n prefix: opts.alias ?? \"type\"\n };\n }\n parseOwnDefinitionFormat(def, ctx) {\n const isScopeAlias = ctx.alias && ctx.alias in this.aliases;\n // if the definition being parsed is not a scope alias and is not a\n // generic instantiation (i.e. opts don't include args), add `this` as a resolution.\n // if we're parsing a nested string, ctx.args will have already been set\n if (!isScopeAlias && !ctx.args)\n ctx.args = { this: ctx.id };\n const result = parseInnerDefinition(def, ctx);\n if (isArray(result)) {\n if (result[1] === \"=\")\n return throwParseError(shallowDefaultableMessage);\n if (result[1] === \"?\")\n return throwParseError(shallowOptionalMessage);\n }\n return result;\n }\n unit = value => this.units([value]);\n valueOf = tsEnum => this.units(enumValues(tsEnum));\n enumerated = (...values) => this.units(values);\n instanceOf = ctor => this.node(\"proto\", { proto: ctor }, { prereduced: true });\n or = (...defs) => this.schema(defs.map(def => this.parse(def)));\n and = (...defs) => defs.reduce((node, def) => node.and(this.parse(def)), this.intrinsic.unknown);\n merge = (...defs) => defs.reduce((node, def) => node.merge(this.parse(def)), this.intrinsic.object);\n pipe = (...morphs) => this.intrinsic.unknown.pipe(...morphs);\n fn = new InternalFnParser(this);\n match = new InternalMatchParser(this);\n declare = () => ({\n type: this.type\n });\n define(def) {\n return def;\n }\n type = new InternalTypeParser(this);\n static scope = ((def, config = {}) => new InternalScope(def, config));\n static module = ((def, config = {}) => this.scope(def, config).export());\n}\nexport const scope = Object.assign(InternalScope.scope, {\n define: (def) => def\n});\nexport const Scope = InternalScope;\n",
|
|
108
|
+
"import { genericNode, intrinsic } from \"@ark/schema\";\nimport { Hkt } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nclass MergeHkt extends Hkt {\n description = 'merge an object\\'s properties onto another like `Merge(User, { isAdmin: \"true\" })`';\n}\nconst Merge = genericNode([\"base\", intrinsic.object], [\"props\", intrinsic.object])(args => args.base.merge(args.props), MergeHkt);\nexport const arkBuiltins = Scope.module({\n Key: intrinsic.key,\n Merge\n});\n",
|
|
109
|
+
"import { genericNode, intrinsic, rootSchema } from \"@ark/schema\";\nimport { Hkt, liftArray } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nclass liftFromHkt extends Hkt {\n}\nconst liftFrom = genericNode(\"element\")(args => {\n const nonArrayElement = args.element.exclude(intrinsic.Array);\n const lifted = nonArrayElement.array();\n return nonArrayElement\n .rawOr(lifted)\n .pipe(liftArray)\n .distribute(branch => branch.assertHasKind(\"morph\").declareOut(lifted), rootSchema);\n}, liftFromHkt);\nexport const arkArray = Scope.module({\n root: intrinsic.Array,\n readonly: \"root\",\n index: intrinsic.nonNegativeIntegerString,\n liftFrom\n}, {\n name: \"Array\"\n});\n",
|
|
110
|
+
"import { rootSchema } from \"@ark/schema\";\nimport { registry } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nconst value = rootSchema([\"string\", registry.FileConstructor]);\nconst parsedFormDataValue = value.rawOr(value.array());\nconst parsed = rootSchema({\n meta: \"an object representing parsed form data\",\n domain: \"object\",\n index: {\n signature: \"string\",\n value: parsedFormDataValue\n }\n});\nexport const arkFormData = Scope.module({\n root: [\"instanceof\", FormData],\n value,\n parsed,\n parse: rootSchema({\n in: FormData,\n morphs: (data) => {\n const result = {};\n for (const [k, v] of data) {\n if (k in result) {\n const existing = result[k];\n if (typeof existing === \"string\" ||\n existing instanceof registry.FileConstructor)\n result[k] = [existing, v];\n else\n existing.push(v);\n }\n else\n result[k] = v;\n }\n return result;\n },\n declaredOut: parsed\n })\n}, {\n name: \"FormData\"\n});\n",
|
|
111
|
+
"import { Scope } from \"../scope.js\";\nexport const TypedArray = Scope.module({\n Int8: [\"instanceof\", Int8Array],\n Uint8: [\"instanceof\", Uint8Array],\n Uint8Clamped: [\"instanceof\", Uint8ClampedArray],\n Int16: [\"instanceof\", Int16Array],\n Uint16: [\"instanceof\", Uint16Array],\n Int32: [\"instanceof\", Int32Array],\n Uint32: [\"instanceof\", Uint32Array],\n Float32: [\"instanceof\", Float32Array],\n Float64: [\"instanceof\", Float64Array],\n BigInt64: [\"instanceof\", BigInt64Array],\n BigUint64: [\"instanceof\", BigUint64Array]\n}, {\n name: \"TypedArray\"\n});\n",
|
|
112
|
+
"import { ecmascriptConstructors, flatMorph, platformConstructors } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nimport { arkArray } from \"./Array.js\";\nimport { arkFormData } from \"./FormData.js\";\nimport { TypedArray } from \"./TypedArray.js\";\nconst omittedPrototypes = {\n Boolean: 1,\n Number: 1,\n String: 1\n};\nexport const arkPrototypes = Scope.module({\n ...flatMorph({ ...ecmascriptConstructors, ...platformConstructors }, (k, v) => (k in omittedPrototypes ? [] : [k, [\"instanceof\", v]])),\n Array: arkArray,\n TypedArray,\n FormData: arkFormData\n});\n",
|
|
113
|
+
"import { intrinsic, rootSchema } from \"@ark/schema\";\nimport { Scope } from \"../scope.js\";\n/**\n * As per the ECMA-262 specification:\n * A time value supports a slightly smaller range of -8,640,000,000,000,000 to 8,640,000,000,000,000 milliseconds.\n *\n * @see https://262.ecma-international.org/15.0/index.html#sec-time-values-and-time-range\n */\nexport const epoch = rootSchema({\n domain: {\n domain: \"number\",\n meta: \"a number representing a Unix timestamp\"\n },\n divisor: {\n rule: 1,\n meta: `an integer representing a Unix timestamp`\n },\n min: {\n rule: -8640000000000000,\n meta: `a Unix timestamp after -8640000000000000`\n },\n max: {\n rule: 8640000000000000,\n meta: \"a Unix timestamp before 8640000000000000\"\n },\n meta: \"an integer representing a safe Unix timestamp\"\n});\nexport const integer = rootSchema({\n domain: \"number\",\n divisor: 1\n});\nexport const number = Scope.module({\n root: intrinsic.number,\n integer,\n epoch,\n safe: rootSchema({\n domain: {\n domain: \"number\",\n numberAllowsNaN: false\n },\n min: Number.MIN_SAFE_INTEGER,\n max: Number.MAX_SAFE_INTEGER\n }),\n NaN: [\"===\", Number.NaN],\n Infinity: [\"===\", Number.POSITIVE_INFINITY],\n NegativeInfinity: [\"===\", Number.NEGATIVE_INFINITY]\n}, {\n name: \"number\"\n});\n",
|
|
114
|
+
"import { ArkErrors, intrinsic, node, rootSchema } from \"@ark/schema\";\nimport { flatMorph, numericStringMatcher, wellFormedIntegerMatcher } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nimport { number } from \"./number.js\";\n// non-trivial expressions should have an explanation or attribution\nexport const regexStringNode = (regex, description, jsonSchemaFormat) => {\n const schema = {\n domain: \"string\",\n pattern: {\n rule: regex.source,\n flags: regex.flags,\n meta: description\n }\n };\n if (jsonSchemaFormat)\n schema.meta = { format: jsonSchemaFormat };\n return node(\"intersection\", schema);\n};\nconst stringIntegerRoot = regexStringNode(wellFormedIntegerMatcher, \"a well-formed integer string\");\nexport const stringInteger = Scope.module({\n root: stringIntegerRoot,\n parse: rootSchema({\n in: stringIntegerRoot,\n morphs: (s, ctx) => {\n const parsed = Number.parseInt(s);\n return Number.isSafeInteger(parsed) ? parsed : (ctx.error(\"an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER\"));\n },\n declaredOut: intrinsic.integer\n })\n}, {\n name: \"string.integer\"\n});\nconst hex = regexStringNode(/^[\\dA-Fa-f]+$/, \"hex characters only\");\nconst base64 = Scope.module({\n root: regexStringNode(/^(?:[\\d+/A-Za-z]{4})*(?:[\\d+/A-Za-z]{2}==|[\\d+/A-Za-z]{3}=)?$/, \"base64-encoded\"),\n url: regexStringNode(/^(?:[\\w-]{4})*(?:[\\w-]{2}(?:==|%3D%3D)?|[\\w-]{3}(?:=|%3D)?)?$/, \"base64url-encoded\")\n}, {\n name: \"string.base64\"\n});\nconst preformattedCapitalize = regexStringNode(/^[A-Z].*$/, \"capitalized\");\nexport const capitalize = Scope.module({\n root: rootSchema({\n in: \"string\",\n morphs: (s) => s.charAt(0).toUpperCase() + s.slice(1),\n declaredOut: preformattedCapitalize\n }),\n preformatted: preformattedCapitalize\n}, {\n name: \"string.capitalize\"\n});\n// https://github.com/validatorjs/validator.js/blob/master/src/lib/isLuhnNumber.js\nexport const isLuhnValid = (creditCardInput) => {\n const sanitized = creditCardInput.replace(/[ -]+/g, \"\");\n let sum = 0;\n let digit;\n let tmpNum;\n let shouldDouble = false;\n for (let i = sanitized.length - 1; i >= 0; i--) {\n digit = sanitized.substring(i, i + 1);\n tmpNum = Number.parseInt(digit, 10);\n if (shouldDouble) {\n tmpNum *= 2;\n sum += tmpNum >= 10 ? (tmpNum % 10) + 1 : tmpNum;\n }\n else\n sum += tmpNum;\n shouldDouble = !shouldDouble;\n }\n return !!(sum % 10 === 0 ? sanitized : false);\n};\n// https://github.com/validatorjs/validator.js/blob/master/src/lib/isCreditCard.js\nconst creditCardMatcher = /^(?:4\\d{12}(?:\\d{3,6})?|5[1-5]\\d{14}|(222[1-9]|22[3-9]\\d|2[3-6]\\d{2}|27[01]\\d|2720)\\d{12}|6(?:011|5\\d\\d)\\d{12,15}|3[47]\\d{13}|3(?:0[0-5]|[68]\\d)\\d{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27]\\d{14}|^(81\\d{14,17}))$/;\nexport const creditCard = rootSchema({\n domain: \"string\",\n pattern: {\n meta: \"a credit card number\",\n rule: creditCardMatcher.source\n },\n predicate: {\n meta: \"a credit card number\",\n predicate: isLuhnValid\n }\n});\nconst dayDelimiterMatcher = /^[./-]$/;\n// ISO 8601 date/time modernized from https://github.com/validatorjs/validator.js/blob/master/src/lib/isISO8601.js\n// Based on https://tc39.es/ecma262/#sec-date-time-string-format, the T\n// delimiter for date/time is mandatory. Regex from validator.js strict matcher:\nexport const iso8601Matcher = /^([+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))(T((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24:?00)([,.]\\d+(?!:))?)?(\\17[0-5]\\d([,.]\\d+)?)?([Zz]|([+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$/;\nconst isValidDateInstance = (date) => !Number.isNaN(+date);\nconst writeFormattedExpected = (format) => `a ${format}-formatted date`;\nexport const tryParseDatePattern = (data, opts) => {\n if (!opts?.format) {\n const result = new Date(data);\n return isValidDateInstance(result) ? result : \"a valid date\";\n }\n if (opts.format === \"iso\") {\n return iso8601Matcher.test(data) ?\n new Date(data)\n : writeFormattedExpected(\"iso\");\n }\n const dataParts = data.split(dayDelimiterMatcher);\n // will be the first delimiter matched, if there is one\n const delimiter = data[dataParts[0].length];\n const formatParts = delimiter ? opts.format.split(delimiter) : [opts.format];\n if (dataParts.length !== formatParts.length)\n return writeFormattedExpected(opts.format);\n const parsedParts = {};\n for (let i = 0; i < formatParts.length; i++) {\n if (dataParts[i].length !== formatParts[i].length &&\n // if format is \"m\" or \"d\", data is allowed to be 1 or 2 characters\n !(formatParts[i].length === 1 && dataParts[i].length === 2))\n return writeFormattedExpected(opts.format);\n parsedParts[formatParts[i][0]] = dataParts[i];\n }\n const date = new Date(`${parsedParts.m}/${parsedParts.d}/${parsedParts.y}`);\n if (`${date.getDate()}` === parsedParts.d)\n return date;\n return writeFormattedExpected(opts.format);\n};\nconst isParsableDate = (s) => !Number.isNaN(new Date(s).valueOf());\nconst parsableDate = rootSchema({\n domain: \"string\",\n predicate: {\n meta: \"a parsable date\",\n predicate: isParsableDate\n }\n}).assertHasKind(\"intersection\");\nconst epochRoot = stringInteger.root.internal\n .narrow((s, ctx) => {\n // this is safe since it has already\n // been validated as an integer string\n const n = Number.parseInt(s);\n const out = number.epoch(n);\n if (out instanceof ArkErrors) {\n ctx.errors.merge(out);\n return false;\n }\n return true;\n})\n .configure({\n description: \"an integer string representing a safe Unix timestamp\"\n}, \"self\")\n .assertHasKind(\"intersection\");\nconst epoch = Scope.module({\n root: epochRoot,\n parse: rootSchema({\n in: epochRoot,\n morphs: (s) => new Date(s),\n declaredOut: intrinsic.Date\n })\n}, {\n name: \"string.date.epoch\"\n});\nconst isoRoot = regexStringNode(iso8601Matcher, \"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date\").internal.assertHasKind(\"intersection\");\nconst iso = Scope.module({\n root: isoRoot,\n parse: rootSchema({\n in: isoRoot,\n morphs: (s) => new Date(s),\n declaredOut: intrinsic.Date\n })\n}, {\n name: \"string.date.iso\"\n});\nexport const stringDate = Scope.module({\n root: parsableDate,\n parse: rootSchema({\n declaredIn: parsableDate,\n in: \"string\",\n morphs: (s, ctx) => {\n const date = new Date(s);\n if (Number.isNaN(date.valueOf()))\n return ctx.error(\"a parsable date\");\n return date;\n },\n declaredOut: intrinsic.Date\n }),\n iso,\n epoch\n}, {\n name: \"string.date\"\n});\nconst email = regexStringNode(\n// considered https://colinhacks.com/essays/reasonable-email-regex but it includes a lookahead\n// which breaks some integrations e.g. fast-check\n// regex based on:\n// https://www.regular-expressions.info/email.html\n/^[\\w%+.-]+@[\\d.A-Za-z-]+\\.[A-Za-z]{2,}$/, \"an email address\", \"email\");\n// based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isIP.js\nconst ipv4Segment = \"(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\";\nconst ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`;\nconst ipv4Matcher = new RegExp(`^${ipv4Address}$`);\nconst ipv6Segment = \"(?:[0-9a-fA-F]{1,4})\";\nconst ipv6Matcher = new RegExp(\"^(\" +\n `(?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|` +\n `(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|` +\n `(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|` +\n `(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|` +\n `(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|` +\n `(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|` +\n `(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|` +\n `(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:))` +\n \")(%[0-9a-zA-Z.]{1,})?$\");\nexport const ip = Scope.module({\n root: [\"v4 | v6\", \"@\", \"an IP address\"],\n v4: regexStringNode(ipv4Matcher, \"an IPv4 address\", \"ipv4\"),\n v6: regexStringNode(ipv6Matcher, \"an IPv6 address\", \"ipv6\")\n}, {\n name: \"string.ip\"\n});\nconst jsonStringDescription = \"a JSON string\";\nexport const writeJsonSyntaxErrorProblem = (error) => {\n if (!(error instanceof SyntaxError))\n throw error;\n return `must be ${jsonStringDescription} (${error})`;\n};\nconst jsonRoot = rootSchema({\n meta: jsonStringDescription,\n domain: \"string\",\n predicate: {\n meta: jsonStringDescription,\n predicate: (s, ctx) => {\n try {\n JSON.parse(s);\n return true;\n }\n catch (e) {\n return ctx.reject({\n code: \"predicate\",\n expected: jsonStringDescription,\n problem: writeJsonSyntaxErrorProblem(e)\n });\n }\n }\n }\n});\nconst parseJson = (s, ctx) => {\n if (s.length === 0) {\n return ctx.error({\n code: \"predicate\",\n expected: jsonStringDescription,\n actual: \"empty\"\n });\n }\n try {\n return JSON.parse(s);\n }\n catch (e) {\n return ctx.error({\n code: \"predicate\",\n expected: jsonStringDescription,\n problem: writeJsonSyntaxErrorProblem(e)\n });\n }\n};\nexport const json = Scope.module({\n root: jsonRoot,\n parse: rootSchema({\n meta: \"safe JSON string parser\",\n in: \"string\",\n morphs: parseJson,\n declaredOut: intrinsic.jsonObject\n })\n}, {\n name: \"string.json\"\n});\nconst preformattedLower = regexStringNode(/^[a-z]*$/, \"only lowercase letters\");\nconst lower = Scope.module({\n root: rootSchema({\n in: \"string\",\n morphs: (s) => s.toLowerCase(),\n declaredOut: preformattedLower\n }),\n preformatted: preformattedLower\n}, {\n name: \"string.lower\"\n});\nexport const normalizedForms = [\"NFC\", \"NFD\", \"NFKC\", \"NFKD\"];\nconst preformattedNodes = flatMorph(normalizedForms, (i, form) => [\n form,\n rootSchema({\n domain: \"string\",\n predicate: (s) => s.normalize(form) === s,\n meta: `${form}-normalized unicode`\n })\n]);\nconst normalizeNodes = flatMorph(normalizedForms, (i, form) => [\n form,\n rootSchema({\n in: \"string\",\n morphs: (s) => s.normalize(form),\n declaredOut: preformattedNodes[form]\n })\n]);\nexport const NFC = Scope.module({\n root: normalizeNodes.NFC,\n preformatted: preformattedNodes.NFC\n}, {\n name: \"string.normalize.NFC\"\n});\nexport const NFD = Scope.module({\n root: normalizeNodes.NFD,\n preformatted: preformattedNodes.NFD\n}, {\n name: \"string.normalize.NFD\"\n});\nexport const NFKC = Scope.module({\n root: normalizeNodes.NFKC,\n preformatted: preformattedNodes.NFKC\n}, {\n name: \"string.normalize.NFKC\"\n});\nexport const NFKD = Scope.module({\n root: normalizeNodes.NFKD,\n preformatted: preformattedNodes.NFKD\n}, {\n name: \"string.normalize.NFKD\"\n});\nexport const normalize = Scope.module({\n root: \"NFC\",\n NFC,\n NFD,\n NFKC,\n NFKD\n}, {\n name: \"string.normalize\"\n});\nconst numericRoot = regexStringNode(numericStringMatcher, \"a well-formed numeric string\");\nexport const stringNumeric = Scope.module({\n root: numericRoot,\n parse: rootSchema({\n in: numericRoot,\n morphs: (s) => Number.parseFloat(s),\n declaredOut: intrinsic.number\n })\n}, {\n name: \"string.numeric\"\n});\nconst regexPatternDescription = \"a regex pattern\";\nconst regex = rootSchema({\n domain: \"string\",\n predicate: {\n meta: regexPatternDescription,\n predicate: (s, ctx) => {\n try {\n new RegExp(s);\n return true;\n }\n catch (e) {\n return ctx.reject({\n code: \"predicate\",\n expected: regexPatternDescription,\n problem: String(e)\n });\n }\n }\n },\n meta: { format: \"regex\" }\n});\nconst semverMatcher = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[A-Za-z-][\\dA-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][\\dA-Za-z-]*))*))?(?:\\+([\\dA-Za-z-]+(?:\\.[\\dA-Za-z-]+)*))?$/;\nconst semver = regexStringNode(semverMatcher, \"a semantic version (see https://semver.org/)\");\nconst preformattedTrim = regexStringNode(\n// no leading or trailing whitespace\n/^\\S.*\\S$|^\\S?$/, \"trimmed\");\nconst trim = Scope.module({\n root: rootSchema({\n in: \"string\",\n morphs: (s) => s.trim(),\n declaredOut: preformattedTrim\n }),\n preformatted: preformattedTrim\n}, {\n name: \"string.trim\"\n});\nconst preformattedUpper = regexStringNode(/^[A-Z]*$/, \"only uppercase letters\");\nconst upper = Scope.module({\n root: rootSchema({\n in: \"string\",\n morphs: (s) => s.toUpperCase(),\n declaredOut: preformattedUpper\n }),\n preformatted: preformattedUpper\n}, {\n name: \"string.upper\"\n});\nconst isParsableUrl = (s) => URL.canParse(s);\nconst urlRoot = rootSchema({\n domain: \"string\",\n predicate: {\n meta: \"a URL string\",\n predicate: isParsableUrl\n },\n // URL.canParse allows a subset of the RFC-3986 URI spec\n // since there is no other serializable validation, best include a format\n meta: { format: \"uri\" }\n});\nexport const url = Scope.module({\n root: urlRoot,\n parse: rootSchema({\n declaredIn: urlRoot,\n in: \"string\",\n morphs: (s, ctx) => {\n try {\n return new URL(s);\n }\n catch {\n return ctx.error(\"a URL string\");\n }\n },\n declaredOut: rootSchema(URL)\n })\n}, {\n name: \"string.url\"\n});\n// based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isUUID.js\nexport const uuid = Scope.module({\n // the meta tuple expression ensures the error message does not delegate\n // to the individual branches, which are too detailed\n root: [\n \"versioned | nil | max\",\n \"@\",\n { description: \"a UUID\", format: \"uuid\" }\n ],\n \"#nil\": \"'00000000-0000-0000-0000-000000000000'\",\n \"#max\": \"'ffffffff-ffff-ffff-ffff-ffffffffffff'\",\n \"#versioned\": /[\\da-f]{8}-[\\da-f]{4}-[1-8][\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}/i,\n v1: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-1[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv1\"),\n v2: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-2[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv2\"),\n v3: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-3[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv3\"),\n v4: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-4[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv4\"),\n v5: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-5[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv5\"),\n v6: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-6[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv6\"),\n v7: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-7[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv7\"),\n v8: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-8[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv8\")\n}, {\n name: \"string.uuid\"\n});\nexport const string = Scope.module({\n root: intrinsic.string,\n alpha: regexStringNode(/^[A-Za-z]*$/, \"only letters\"),\n alphanumeric: regexStringNode(/^[\\dA-Za-z]*$/, \"only letters and digits 0-9\"),\n hex,\n base64,\n capitalize,\n creditCard,\n date: stringDate,\n digits: regexStringNode(/^\\d*$/, \"only digits 0-9\"),\n email,\n integer: stringInteger,\n ip,\n json,\n lower,\n normalize,\n numeric: stringNumeric,\n regex,\n semver,\n trim,\n upper,\n url,\n uuid\n}, {\n name: \"string\"\n});\n",
|
|
115
|
+
"import { genericNode, intrinsic, node } from \"@ark/schema\";\nimport { Hkt } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nexport const arkTsKeywords = Scope.module({\n bigint: intrinsic.bigint,\n boolean: intrinsic.boolean,\n false: intrinsic.false,\n never: intrinsic.never,\n null: intrinsic.null,\n number: intrinsic.number,\n object: intrinsic.object,\n string: intrinsic.string,\n symbol: intrinsic.symbol,\n true: intrinsic.true,\n unknown: intrinsic.unknown,\n undefined: intrinsic.undefined\n});\nexport const unknown = Scope.module({\n root: intrinsic.unknown,\n any: intrinsic.unknown\n}, {\n name: \"unknown\"\n});\nexport const json = Scope.module({\n root: intrinsic.jsonObject,\n stringify: node(\"morph\", {\n in: intrinsic.jsonObject,\n morphs: (data) => JSON.stringify(data),\n declaredOut: intrinsic.string\n })\n}, {\n name: \"object.json\"\n});\nexport const object = Scope.module({\n root: intrinsic.object,\n json\n}, {\n name: \"object\"\n});\nclass RecordHkt extends Hkt {\n description = 'instantiate an object from an index signature and corresponding value type like `Record(\"string\", \"number\")`';\n}\nconst Record = genericNode([\"K\", intrinsic.key], \"V\")(args => ({\n domain: \"object\",\n index: {\n signature: args.K,\n value: args.V\n }\n}), RecordHkt);\nclass PickHkt extends Hkt {\n description = 'pick a set of properties from an object like `Pick(User, \"name | age\")`';\n}\nconst Pick = genericNode([\"T\", intrinsic.object], [\"K\", intrinsic.key])(args => args.T.pick(args.K), PickHkt);\nclass OmitHkt extends Hkt {\n description = 'omit a set of properties from an object like `Omit(User, \"age\")`';\n}\nconst Omit = genericNode([\"T\", intrinsic.object], [\"K\", intrinsic.key])(args => args.T.omit(args.K), OmitHkt);\nclass PartialHkt extends Hkt {\n description = \"make all named properties of an object optional like `Partial(User)`\";\n}\nconst Partial = genericNode([\"T\", intrinsic.object])(args => args.T.partial(), PartialHkt);\nclass RequiredHkt extends Hkt {\n description = \"make all named properties of an object required like `Required(User)`\";\n}\nconst Required = genericNode([\"T\", intrinsic.object])(args => args.T.required(), RequiredHkt);\nclass ExcludeHkt extends Hkt {\n description = 'exclude branches of a union like `Exclude(\"boolean\", \"true\")`';\n}\nconst Exclude = genericNode(\"T\", \"U\")(args => args.T.exclude(args.U), ExcludeHkt);\nclass ExtractHkt extends Hkt {\n description = 'extract branches of a union like `Extract(\"0 | false | 1\", \"number\")`';\n}\nconst Extract = genericNode(\"T\", \"U\")(args => args.T.extract(args.U), ExtractHkt);\nexport const arkTsGenerics = Scope.module({\n Exclude,\n Extract,\n Omit,\n Partial,\n Pick,\n Record,\n Required\n});\n",
|
|
116
|
+
"import { $arkTypeRegistry, scope } from \"../scope.js\";\nimport { arkBuiltins } from \"./builtins.js\";\nimport { arkPrototypes } from \"./constructors.js\";\nimport { number } from \"./number.js\";\nimport { string } from \"./string.js\";\nimport { arkTsGenerics, arkTsKeywords, object, unknown } from \"./ts.js\";\nexport const ark = scope({\n ...arkTsKeywords,\n ...arkTsGenerics,\n ...arkPrototypes,\n ...arkBuiltins,\n string,\n number,\n object,\n unknown\n}, { prereducedAliases: true, name: \"ark\" });\nexport const keywords = ark.export();\nObject.assign($arkTypeRegistry.ambient, keywords);\n$arkTypeRegistry.typeAttachments = {\n string: keywords.string.root,\n number: keywords.number.root,\n bigint: keywords.bigint,\n boolean: keywords.boolean,\n symbol: keywords.symbol,\n undefined: keywords.undefined,\n null: keywords.null,\n object: keywords.object.root,\n unknown: keywords.unknown.root,\n false: keywords.false,\n true: keywords.true,\n never: keywords.never,\n arrayIndex: keywords.Array.index,\n Key: keywords.Key,\n Record: keywords.Record,\n Array: keywords.Array.root,\n Date: keywords.Date\n};\nexport const type = Object.assign(ark.type, \n// assign attachments newly parsed in keywords\n// future scopes add these directly from the\n// registry when their TypeParsers are instantiated\n$arkTypeRegistry.typeAttachments);\nexport const match = ark.match;\nexport const fn = ark.fn;\nexport const generic = ark.generic;\nexport const schema = ark.schema;\nexport const define = ark.define;\nexport const declare = ark.declare;\n",
|
|
117
|
+
"// src/domain/validator.ts\r\nimport { type, scope } from \"arktype\";\r\nimport type { TriggerRule } from \"../types\";\r\n\r\n// --- ArkType Scope & Schemas ---\r\n\r\n// Define a Validation Scope to handle recursive types and mutual dependencies\r\nconst types = scope({\r\n\r\n // List of allowed operators\r\n Operator: \"'EQ' | '==' | 'NEQ' | '!=' | 'GT' | '>' | 'GTE' | '>=' | 'LT' | '<' | 'LTE' | '<=' | 'IN' | 'NOT_IN' | 'CONTAINS' | 'MATCHES' | 'RANGE' | 'SINCE' | 'AFTER' | 'BEFORE' | 'UNTIL'\",\r\n \r\n // Discriminated union for better value validation based on operator\r\n Condition: \"RangeCondition | ListCondition | ContainsCondition | NumericCondition | RegexCondition | BasicCondition\",\r\n \r\n RangeCondition: {\r\n field: \"string > 0\",\r\n operator: \"'RANGE'\",\r\n value: \"unknown[] == 2\" // Requires an array of exactly 2 items\r\n },\r\n \r\n ListCondition: {\r\n field: \"string > 0\",\r\n operator: \"'IN' | 'NOT_IN'\",\r\n value: \"unknown[]\" // Requires an array\r\n },\r\n\r\n ContainsCondition: {\r\n field: \"string > 0\",\r\n operator: \"'CONTAINS'\",\r\n value: \"string | unknown[]\" // Can be string (substring) or array (includes)\r\n },\r\n \r\n NumericCondition: {\r\n field: \"string > 0\",\r\n operator: \"'>' | '>=' | '<' | '<=' | 'GT' | 'GTE' | 'LT' | 'LTE'\",\r\n value: \"number | string\" // Numbers or expressions\r\n },\r\n \r\n RegexCondition: {\r\n field: \"string > 0\",\r\n operator: \"'MATCHES'\",\r\n value: \"string\" // Regex pattern must be a string\r\n },\r\n \r\n BasicCondition: {\r\n field: \"string > 0\",\r\n operator: \"Operator\",\r\n value: \"unknown\"\r\n },\r\n \r\n ConditionGroup: {\r\n operator: \"'AND' | 'OR'\",\r\n // Recursive reference to Condition or ConditionGroup\r\n conditions: \"(Condition | ConditionGroup)[] >= 1\" // Must have at least 1 condition\r\n },\r\n \r\n RuleCondition: \"Condition | ConditionGroup\",\r\n\r\n Action: {\r\n type: \"string > 0\", // Must define a type\r\n \"params?\": \"object\", // Must be an object if present\r\n \"delay?\": \"number.integer >= 0\", // Integer check for milliseconds\r\n \"probability?\": \"0 <= number <= 1\"\r\n },\r\n\r\n ActionGroup: {\r\n \"mode?\": \"'ALL' | 'EITHER' | 'SEQUENCE'\",\r\n actions: \"(Action | ActionGroup)[] >= 1\" // Recursive\r\n },\r\n\r\n RuleAction: \"Action | ActionGroup\",\r\n\r\n TriggerRule: {\r\n id: \"string > 0\",\r\n \"name?\": \"string\",\r\n \"description?\": \"string\",\r\n \"priority?\": \"number.integer\", // Priority is integer\r\n \"enabled?\": \"boolean\",\r\n \"cooldown?\": \"number.integer >= 0\", // Milliseconds\r\n \"tags?\": \"string[]\",\r\n on: \"string > 0\", // Non-empty event name\r\n \r\n \"if?\": \"RuleCondition | RuleCondition[]\",\r\n \r\n do: \"RuleAction | RuleAction[]\",\r\n \"comment?\": \"string\"\r\n }\r\n}).export();\r\n\r\n// Export individual schemas for external usage if needed\r\nexport const ComparisonOperatorSchema = types.Operator;\r\nexport const ConditionSchema = types.Condition;\r\nexport const ConditionGroupSchema = types.ConditionGroup;\r\nexport const RuleConditionSchema = types.RuleCondition;\r\nexport const ActionSchema = types.Action;\r\nexport const ActionGroupSchema = types.ActionGroup;\r\nexport const TriggerRuleSchema = types.TriggerRule;\r\n\r\n// --- Validation Result Types ---\r\n\r\nexport interface ValidationSuccess {\r\n valid: true;\r\n rule: TriggerRule;\r\n}\r\n\r\nexport interface ValidationIssue {\r\n path: string;\r\n message: string;\r\n suggestion?: string;\r\n severity: \"error\" | \"warning\";\r\n}\r\n\r\nexport interface ValidationFailure {\r\n valid: false;\r\n issues: ValidationIssue[];\r\n}\r\n\r\nexport type ValidationResult = ValidationSuccess | ValidationFailure;\r\n\r\n// --- Validator Class ---\r\n\r\nexport class TriggerValidator {\r\n \r\n static validate(data: any): ValidationResult {\r\n // ArkType validation\r\n const out = TriggerRuleSchema(data);\r\n\r\n if (out instanceof type.errors) {\r\n const issues: ValidationIssue[] = [];\r\n \r\n // Iterate over problems (ArkType specific)\r\n for (const problem of out) {\r\n const path = problem.path.join(\".\");\r\n let message = problem.message;\r\n let suggestion = undefined;\r\n\r\n // Custom Error Enhancements (replicating Zod logic)\r\n // ArkType error for missing string might differ, typically says \"must be a string\"\r\n if (path.endsWith(\"on\") && (message.includes(\"string\") || message.includes(\"must be\"))) {\r\n // Heuristic check if it failed because it was interpretted as boolean 'true' in YAML\r\n // We can't see the original value easily here without checking 'data' at path\r\n // But we can just suggest it generally.\r\n if (typeof data === 'object' && data && data.on === true) {\r\n message = \"The 'on' field is incorrect (boolean true found).\";\r\n suggestion = \"In YAML, 'on' is a boolean keyword (true). Quote it: \\\"on\\\": \\\"EventName\\\"\";\r\n } else {\r\n // Generic suggestion\r\n suggestion = \"Ensure 'on' is a string event name.\";\r\n }\r\n }\r\n\r\n issues.push({\r\n path,\r\n message,\r\n suggestion,\r\n severity: \"error\"\r\n });\r\n }\r\n\r\n return { valid: false, issues };\r\n }\r\n \r\n // Structural validation passed. Now perform Semantic Validation (Value Types)\r\n const rule = out as TriggerRule;\r\n const semanticIssues: ValidationIssue[] = [];\r\n \r\n this.validateConditionsRecursive(rule.if, semanticIssues, 'if');\r\n\r\n if (semanticIssues.length > 0) {\r\n return { valid: false, issues: semanticIssues };\r\n }\r\n\r\n return { valid: true, rule };\r\n }\r\n\r\n private static validateConditionsRecursive(\r\n condition: any, \r\n issues: ValidationIssue[], \r\n path: string\r\n ): void {\r\n if (!condition) return;\r\n\r\n if (Array.isArray(condition)) {\r\n condition.forEach((c, idx) => {\r\n this.validateConditionsRecursive(c, issues, `${path}.${idx}`);\r\n });\r\n return;\r\n }\r\n\r\n // Check if it's a ConditionGroup (has 'conditions')\r\n if ('conditions' in condition && Array.isArray(condition.conditions)) {\r\n condition.conditions.forEach((c: any, idx: number) => {\r\n this.validateConditionsRecursive(c, issues, `${path}.conditions.${idx}`);\r\n });\r\n return;\r\n }\r\n\r\n // It must be a Condition\r\n if ('operator' in condition && 'value' in condition) {\r\n this.validateConditionValue(condition, issues, path);\r\n }\r\n }\r\n\r\n private static validateConditionValue(\r\n condition: any, \r\n issues: ValidationIssue[], \r\n path: string\r\n ): void {\r\n const { operator, value } = condition;\r\n \r\n // 1. List/Collection Operators (IN, NOT_IN, RANGE, CONTAINS)\r\n if (['IN', 'NOT_IN', 'RANGE', 'CONTAINS'].includes(operator)) {\r\n if (operator === 'CONTAINS') {\r\n if (typeof value !== 'string' && !Array.isArray(value)) {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect value type: Operator 'CONTAINS' expects a String or List (Array), but received ${typeof value}.`,\r\n suggestion: \"Use a substring or a list of items.\",\r\n severity: \"error\"\r\n });\r\n }\r\n return;\r\n }\r\n\r\n if (!Array.isArray(value)) {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect value type: Operator '${operator}' expects a List (Array), but received ${typeof value}.`,\r\n suggestion: operator === 'RANGE' ? \"Use format [min, max]\" : \"Use format [item1, item2]\",\r\n severity: \"error\"\r\n });\r\n return;\r\n }\r\n\r\n if (operator === 'RANGE') {\r\n if (value.length !== 2) {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Invalid Range: Operator 'RANGE' requires exactly 2 values (min and max).`,\r\n suggestion: \"Use format [min, max], e.g. [1, 10]\",\r\n severity: \"error\"\r\n });\r\n } else if (typeof value[0] !== 'number' && typeof value[0] !== 'string') {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect range type: Range values must be numbers or expression strings.`,\r\n severity: \"error\"\r\n });\r\n }\r\n }\r\n } \r\n // 2. Regex\r\n else if (operator === 'MATCHES') {\r\n if (typeof value !== 'string') {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect value type: Operator 'MATCHES' expects a string (regex pattern), but received ${typeof value}.`,\r\n severity: \"error\"\r\n });\r\n } else {\r\n try {\r\n new RegExp(value);\r\n } catch (e) {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Invalid Regex pattern: ${(e as Error).message}`,\r\n severity: \"error\"\r\n });\r\n }\r\n }\r\n }\r\n // 3. Numeric Comparisons (GT, LT, etc)\r\n else if (['GT', 'GTE', 'LT', 'LTE', '>', '>=', '<', '<='].includes(operator)) {\r\n if (typeof value !== 'number' && typeof value !== 'string') {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect value type: Operator '${operator}' expects a number or expression string, but received ${typeof value}.`,\r\n severity: \"error\"\r\n });\r\n }\r\n }\r\n }\r\n}\r\n"
|
|
118
|
+
],
|
|
119
|
+
"mappings": "AAMO,MAAM,CAAiB,OAMrB,SAAQ,CAAC,EAAoB,EAA8B,CAChE,GAAI,CAEF,GAAI,EAAW,SAAS,IAAI,EAAG,CAC7B,IAAM,EAAe,KAAK,YAAY,EAAY,CAAO,EAEzD,GAAI,CAAC,MAAM,OAAO,CAAY,CAAC,GAAK,EAAa,KAAK,IAAM,GACxD,OAAO,OAAO,CAAY,EAE9B,OAAO,EAIT,OAAO,KAAK,mBAAmB,EAAY,CAAO,EAClD,MAAO,EAAO,CAEd,OADA,QAAQ,MAAM,gCAAgC,IAAc,CAAK,EAC1D,YAQJ,YAAW,CAAC,EAAkB,EAAiC,CACpE,OAAO,EAAS,QAAQ,iBAAkB,CAAC,EAAO,IAAe,CAC/D,GAAI,CACF,IAAM,EAAS,KAAK,mBAAmB,EAAY,CAAO,EAC1D,GAAI,IAAW,QAAa,IAA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