@axintai/compiler 0.3.0 → 0.3.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/types.ts","../../src/core/parser.ts","../../src/core/generator.ts","../../src/core/validator.ts","../../src/core/compiler.ts","../../src/templates/index.ts","../../src/core/format.ts","../../src/core/sandbox.ts","../../src/mcp/scaffold.ts","../../src/mcp/server.ts","../../src/cli/index.ts","../../src/core/eject.ts","../../src/cli/scaffold.ts"],"sourcesContent":["/**\n * Axint Core Types\n *\n * Intermediate Representation (IR) and compiler types for the\n * TypeScript → Swift App Intent compilation pipeline.\n */\n\n// ─── IR Types ────────────────────────────────────────────────────────\n\n/** Primitive types supported by App Intents */\nexport type IRPrimitiveType =\n | \"string\"\n | \"int\"\n | \"double\"\n | \"float\"\n | \"boolean\"\n | \"date\"\n | \"duration\"\n | \"url\";\n\n/** Type node in the IR */\nexport type IRType =\n | { kind: \"primitive\"; value: IRPrimitiveType }\n | { kind: \"array\"; elementType: IRType }\n | { kind: \"optional\"; innerType: IRType }\n | { kind: \"entity\"; entityName: string; properties: IRParameter[] }\n | { kind: \"entityQuery\"; entityName: string; queryType: \"all\" | \"id\" | \"string\" | \"property\" }\n | { kind: \"dynamicOptions\"; valueType: IRType; providerName: string }\n | { kind: \"enum\"; name: string; cases: string[] };\n\n/** A single parameter in an intent definition */\nexport interface IRParameter {\n name: string;\n type: IRType;\n title: string;\n description: string;\n isOptional: boolean;\n defaultValue?: unknown;\n}\n\n/**\n * Display representation configuration for an entity.\n * Maps which properties to show in Siri and Shortcuts UI.\n */\nexport interface DisplayRepresentation {\n title: string;\n subtitle?: string;\n image?: string;\n}\n\n/**\n * An App Entity definition for complex, domain-specific data types.\n * Entities can be queried and used as parameter types in intents.\n */\nexport interface IREntity {\n name: string;\n displayRepresentation: DisplayRepresentation;\n properties: IRParameter[];\n queryType: \"all\" | \"id\" | \"string\" | \"property\";\n}\n\n/** The main IR node representing a compiled intent */\nexport interface IRIntent {\n name: string;\n title: string;\n description: string;\n domain?: string;\n category?: string;\n parameters: IRParameter[];\n returnType: IRType;\n sourceFile: string;\n /** Entitlements required by this intent (e.g., \"com.apple.developer.siri\") */\n entitlements?: string[];\n /** Info.plist keys required by this intent (e.g., \"NSCalendarsUsageDescription\") */\n infoPlistKeys?: Record<string, string>;\n /** Whether the intent should be exposed to Spotlight indexing */\n isDiscoverable?: boolean;\n /** App Entities used by this intent */\n entities?: IREntity[];\n /** Whether to donate this intent to Spotlight/Siri when performed */\n donateOnPerform?: boolean;\n /** Custom result type (SwiftUI view or custom struct) to return */\n customResultType?: string;\n}\n\n// ─── Compiler Types ──────────────────────────────────────────────────\n\nexport interface CompilerOptions {\n /** Output directory for generated Swift files */\n outDir: string;\n /** Whether to run validation after generation */\n validate?: boolean;\n /** Target iOS/macOS version */\n target?: \"ios16\" | \"ios17\" | \"ios18\" | \"ios26\" | \"macos13\" | \"macos14\" | \"macos15\" | \"macos26\";\n /** Whether to emit an Info.plist fragment alongside the Swift file */\n emitInfoPlist?: boolean;\n /** Whether to emit an entitlements fragment alongside the Swift file */\n emitEntitlements?: boolean;\n /** Whether to run swift-format on the output (requires swift-format on PATH) */\n format?: boolean;\n}\n\nexport interface CompilerOutput {\n /** Path to the generated Swift file */\n outputPath: string;\n /** The generated Swift source code */\n swiftCode: string;\n /** Info.plist fragment (if emitInfoPlist is true) */\n infoPlistFragment?: string;\n /** Entitlements fragment (if emitEntitlements is true) */\n entitlementsFragment?: string;\n /** The intermediate representation */\n ir: IRIntent;\n /** Validation diagnostics */\n diagnostics: Diagnostic[];\n}\n\n// ─── Diagnostics ─────────────────────────────────────────────────────\n\nexport type DiagnosticSeverity = \"error\" | \"warning\" | \"info\";\n\nexport interface Diagnostic {\n code: string;\n severity: DiagnosticSeverity;\n message: string;\n file?: string;\n line?: number;\n column?: number;\n suggestion?: string;\n}\n\n// ─── Param Type Registry ─────────────────────────────────────────────\n\n/**\n * Canonical set of supported param types.\n * Single source of truth — parser, SDK, and docs all derive from this.\n * To add a new type: add it to IRPrimitiveType, PARAM_TYPES, and SWIFT_TYPE_MAP.\n */\nexport const PARAM_TYPES: ReadonlySet<IRPrimitiveType> = new Set<IRPrimitiveType>([\n \"string\",\n \"int\",\n \"double\",\n \"float\",\n \"boolean\",\n \"date\",\n \"duration\",\n \"url\",\n]);\n\n/**\n * Legacy alias: \"number\" → \"int\" for backwards compatibility with v0.1.x files.\n * Parser will accept \"number\" and rewrite it to \"int\" with a deprecation warning.\n */\nexport const LEGACY_PARAM_ALIASES: Record<string, IRPrimitiveType> = {\n number: \"int\",\n};\n\n// ─── Swift Type Mapping ──────────────────────────────────────────────\n\nexport const SWIFT_TYPE_MAP: Record<IRPrimitiveType, string> = {\n string: \"String\",\n int: \"Int\",\n double: \"Double\",\n float: \"Float\",\n boolean: \"Bool\",\n date: \"Date\",\n duration: \"Measurement<UnitDuration>\",\n url: \"URL\",\n};\n\n/**\n * Convert an IRType to its Swift type string.\n */\nexport function irTypeToSwift(type: IRType): string {\n switch (type.kind) {\n case \"primitive\":\n return SWIFT_TYPE_MAP[type.value];\n case \"array\":\n return `[${irTypeToSwift(type.elementType)}]`;\n case \"optional\":\n return `${irTypeToSwift(type.innerType)}?`;\n case \"entity\":\n return type.entityName;\n case \"entityQuery\":\n return `${type.entityName}Query`;\n case \"dynamicOptions\":\n return `[DynamicOptionsResult<${irTypeToSwift(type.valueType)}>]`;\n case \"enum\":\n return type.name;\n }\n}\n","/**\n * Axint Parser\n *\n * Parses TypeScript intent definitions (using the defineIntent() API)\n * into the Axint Intermediate Representation (IR).\n *\n * Approach: Real TypeScript compiler API AST walker. We create a\n * SourceFile, find defineIntent() CallExpressions, and extract the\n * ObjectLiteralExpression properties using the actual TS AST.\n *\n * The previous v0.1.x parser used regex matching. That approach was\n * replaced in v0.2.0 to support enums, arrays, entities, and accurate\n * return-type inference.\n */\n\nimport ts from \"typescript\";\nimport type {\n IRIntent,\n IRParameter,\n IRType,\n IRPrimitiveType,\n IREntity,\n DisplayRepresentation,\n} from \"./types.js\";\nimport { PARAM_TYPES, LEGACY_PARAM_ALIASES } from \"./types.js\";\n\n/**\n * Parse a TypeScript source file containing defineIntent() and/or\n * defineEntity() calls and return the IR representation.\n */\nexport function parseIntentSource(\n source: string,\n filePath: string = \"<stdin>\"\n): IRIntent {\n const sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.Latest,\n true, // setParentNodes\n ts.ScriptKind.TS\n );\n\n // Parse all entity definitions first, so they can be referenced by intents\n const entities = findDefineEntityCalls(sourceFile).map((call) =>\n parseEntityDefinition(call, filePath, sourceFile)\n );\n\n const defineIntentCall = findDefineIntentCall(sourceFile);\n if (!defineIntentCall) {\n throw new ParserError(\n \"AX001\",\n `No defineIntent() call found in ${filePath}`,\n filePath,\n undefined,\n \"Ensure your file contains a `defineIntent({ ... })` call.\"\n );\n }\n\n const arg = defineIntentCall.arguments[0];\n if (!arg || !ts.isObjectLiteralExpression(arg)) {\n throw new ParserError(\n \"AX001\",\n \"defineIntent() must be called with an object literal\",\n filePath,\n posOf(sourceFile, defineIntentCall),\n \"Pass an object: defineIntent({ name, title, description, params, perform })\"\n );\n }\n\n const props = propertyMap(arg);\n\n const name = readStringLiteral(props.get(\"name\"));\n const title = readStringLiteral(props.get(\"title\"));\n const description = readStringLiteral(props.get(\"description\"));\n const domain = readStringLiteral(props.get(\"domain\"));\n const category = readStringLiteral(props.get(\"category\"));\n const isDiscoverable = readBooleanLiteral(props.get(\"isDiscoverable\"));\n\n if (!name) {\n throw new ParserError(\n \"AX002\",\n \"Missing required field: name\",\n filePath,\n posOf(sourceFile, arg),\n 'Add a name field: name: \"MyIntent\"'\n );\n }\n if (!title) {\n throw new ParserError(\n \"AX003\",\n \"Missing required field: title\",\n filePath,\n posOf(sourceFile, arg),\n 'Add a title field: title: \"My Intent Title\"'\n );\n }\n if (!description) {\n throw new ParserError(\n \"AX004\",\n \"Missing required field: description\",\n filePath,\n posOf(sourceFile, arg),\n 'Add a description field: description: \"What this intent does\"'\n );\n }\n\n const paramsNode = props.get(\"params\");\n const parameters: IRParameter[] = paramsNode\n ? extractParameters(paramsNode, filePath, sourceFile)\n : [];\n\n // Return-type inference from the perform() function signature.\n const performNode = props.get(\"perform\");\n const returnType = inferReturnType(performNode);\n\n // Entitlements (optional array of strings)\n const entitlementsNode = props.get(\"entitlements\");\n const entitlements = readStringArray(entitlementsNode);\n\n // Info.plist keys (optional object literal of { key: \"description\" })\n const infoPlistNode = props.get(\"infoPlistKeys\");\n const infoPlistKeys = readStringRecord(infoPlistNode);\n\n // Intent donation (optional boolean)\n const donateOnPerformNode = props.get(\"donateOnPerform\");\n const donateOnPerform = readBooleanLiteral(donateOnPerformNode);\n\n // Custom result type (optional string)\n const customResultTypeNode = props.get(\"customResultType\");\n const customResultType = readStringLiteral(customResultTypeNode);\n\n return {\n name,\n title,\n description,\n domain: domain || undefined,\n category: category || undefined,\n parameters,\n returnType,\n sourceFile: filePath,\n entitlements: entitlements.length > 0 ? entitlements : undefined,\n infoPlistKeys:\n Object.keys(infoPlistKeys).length > 0 ? infoPlistKeys : undefined,\n isDiscoverable: isDiscoverable ?? undefined,\n entities: entities.length > 0 ? entities : undefined,\n donateOnPerform: donateOnPerform ?? undefined,\n customResultType: customResultType ?? undefined,\n };\n}\n\n// ─── AST Walkers ─────────────────────────────────────────────────────\n\n/**\n * Find the first defineIntent() call in the AST.\n */\nfunction findDefineIntentCall(\n node: ts.Node\n): ts.CallExpression | undefined {\n let found: ts.CallExpression | undefined;\n const visit = (n: ts.Node): void => {\n if (found) return;\n if (\n ts.isCallExpression(n) &&\n ts.isIdentifier(n.expression) &&\n n.expression.text === \"defineIntent\"\n ) {\n found = n;\n return;\n }\n ts.forEachChild(n, visit);\n };\n visit(node);\n return found;\n}\n\n/**\n * Find all defineEntity() calls in the AST.\n */\nfunction findDefineEntityCalls(node: ts.Node): ts.CallExpression[] {\n const found: ts.CallExpression[] = [];\n const visit = (n: ts.Node): void => {\n if (\n ts.isCallExpression(n) &&\n ts.isIdentifier(n.expression) &&\n n.expression.text === \"defineEntity\"\n ) {\n found.push(n);\n return;\n }\n ts.forEachChild(n, visit);\n };\n visit(node);\n return found;\n}\n\nfunction propertyMap(\n obj: ts.ObjectLiteralExpression\n): Map<string, ts.Expression> {\n const map = new Map<string, ts.Expression>();\n for (const prop of obj.properties) {\n if (ts.isPropertyAssignment(prop)) {\n const key = propertyKeyName(prop.name);\n if (key) map.set(key, prop.initializer);\n } else if (ts.isShorthandPropertyAssignment(prop)) {\n map.set(prop.name.text, prop.name);\n } else if (ts.isMethodDeclaration(prop)) {\n const key = propertyKeyName(prop.name);\n if (key) map.set(key, prop as unknown as ts.Expression);\n }\n }\n return map;\n}\n\nfunction propertyKeyName(name: ts.PropertyName): string | undefined {\n if (ts.isIdentifier(name)) return name.text;\n if (ts.isStringLiteral(name)) return name.text;\n if (ts.isNumericLiteral(name)) return name.text;\n return undefined;\n}\n\nfunction readStringLiteral(node: ts.Expression | undefined): string | null {\n if (!node) return null;\n if (ts.isStringLiteral(node)) return node.text;\n if (ts.isNoSubstitutionTemplateLiteral(node)) return node.text;\n return null;\n}\n\nfunction readBooleanLiteral(\n node: ts.Expression | undefined\n): boolean | undefined {\n if (!node) return undefined;\n if (node.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (node.kind === ts.SyntaxKind.FalseKeyword) return false;\n return undefined;\n}\n\nfunction readStringArray(node: ts.Expression | undefined): string[] {\n if (!node || !ts.isArrayLiteralExpression(node)) return [];\n const out: string[] = [];\n for (const el of node.elements) {\n const s = readStringLiteral(el);\n if (s !== null) out.push(s);\n }\n return out;\n}\n\nfunction readStringRecord(\n node: ts.Expression | undefined\n): Record<string, string> {\n if (!node || !ts.isObjectLiteralExpression(node)) return {};\n const rec: Record<string, string> = {};\n for (const prop of node.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const key = propertyKeyName(prop.name);\n const val = readStringLiteral(prop.initializer);\n if (key && val !== null) rec[key] = val;\n }\n return rec;\n}\n\n// ─── Entity Definition Parsing ───────────────────────────────────────\n\n/**\n * Parse a defineEntity() call into an IREntity.\n */\nfunction parseEntityDefinition(\n call: ts.CallExpression,\n filePath: string,\n sourceFile: ts.SourceFile\n): IREntity {\n const arg = call.arguments[0];\n if (!arg || !ts.isObjectLiteralExpression(arg)) {\n throw new ParserError(\n \"AX015\",\n \"defineEntity() must be called with an object literal\",\n filePath,\n posOf(sourceFile, call),\n \"Pass an object: defineEntity({ name, display, properties, query })\"\n );\n }\n\n const props = propertyMap(arg);\n\n const name = readStringLiteral(props.get(\"name\"));\n if (!name) {\n throw new ParserError(\n \"AX016\",\n \"Entity definition missing required field: name\",\n filePath,\n posOf(sourceFile, arg),\n 'Add a name field: name: \"Task\"'\n );\n }\n\n const displayNode = props.get(\"display\");\n if (!displayNode || !ts.isObjectLiteralExpression(displayNode)) {\n throw new ParserError(\n \"AX017\",\n \"Entity definition missing required field: display\",\n filePath,\n posOf(sourceFile, arg),\n 'Add display field: display: { title: \"name\", subtitle: \"status\" }'\n );\n }\n\n const displayProps = propertyMap(displayNode);\n const displayRepresentation: DisplayRepresentation = {\n title: readStringLiteral(displayProps.get(\"title\")) || \"name\",\n subtitle: readStringLiteral(displayProps.get(\"subtitle\")) || undefined,\n image: readStringLiteral(displayProps.get(\"image\")) || undefined,\n };\n\n const propertiesNode = props.get(\"properties\");\n const properties = propertiesNode\n ? extractParameters(propertiesNode, filePath, sourceFile)\n : [];\n\n const queryTypeNode = props.get(\"query\");\n const queryTypeStr = readStringLiteral(queryTypeNode);\n const queryType = validateQueryType(queryTypeStr, filePath, sourceFile, queryTypeNode);\n\n return {\n name,\n displayRepresentation,\n properties,\n queryType,\n };\n}\n\n/**\n * Validate and normalize query type string.\n */\nfunction validateQueryType(\n value: string | null,\n filePath: string,\n sourceFile: ts.SourceFile,\n node: ts.Expression | undefined\n): \"all\" | \"id\" | \"string\" | \"property\" {\n if (!value) {\n throw new ParserError(\n \"AX018\",\n \"Entity definition missing required field: query\",\n filePath,\n node ? posOf(sourceFile, node) : undefined,\n 'Add query field: query: \"string\" (or \"all\", \"id\", \"property\")'\n );\n }\n const valid = [\"all\", \"id\", \"string\", \"property\"] as const;\n if (!valid.includes(value as any)) {\n throw new ParserError(\n \"AX019\",\n `Invalid query type: \"${value}\". Must be one of: all, id, string, property`,\n filePath,\n node ? posOf(sourceFile, node) : undefined\n );\n }\n return value as \"all\" | \"id\" | \"string\" | \"property\";\n}\n\n// ─── Parameter Extraction ────────────────────────────────────────────\n\nfunction extractParameters(\n node: ts.Expression,\n filePath: string,\n sourceFile: ts.SourceFile\n): IRParameter[] {\n if (!ts.isObjectLiteralExpression(node)) {\n throw new ParserError(\n \"AX006\",\n \"`params` must be an object literal\",\n filePath,\n posOf(sourceFile, node),\n \"Use params: { name: param.string(...), ... }\"\n );\n }\n\n const params: IRParameter[] = [];\n for (const prop of node.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const paramName = propertyKeyName(prop.name);\n if (!paramName) continue;\n\n const { typeName, description, configObject, callExpr } = extractParamCall(\n prop.initializer,\n filePath,\n sourceFile\n );\n\n const resolvedType = resolveParamType(typeName, filePath, sourceFile, prop, callExpr);\n\n const isOptional = configObject\n ? readBooleanLiteral(configObject.get(\"required\")) === false\n : false;\n\n const defaultExpr = configObject?.get(\"default\");\n const defaultValue = defaultExpr ? evaluateLiteral(defaultExpr) : undefined;\n\n const titleFromConfig = configObject\n ? readStringLiteral(configObject.get(\"title\"))\n : null;\n\n const irType: IRType = isOptional\n ? {\n kind: \"optional\",\n innerType: resolvedType,\n }\n : resolvedType;\n\n params.push({\n name: paramName,\n type: irType,\n title: titleFromConfig || prettyTitle(paramName),\n description,\n isOptional,\n defaultValue,\n });\n }\n\n return params;\n}\n\ninterface ParamCallInfo {\n typeName: string;\n description: string;\n configObject: Map<string, ts.Expression> | null;\n callExpr: ts.CallExpression;\n}\n\n/**\n * Extract param type, description, and config from a param.* call.\n * For param.entity() and param.dynamicOptions(), the structure is different.\n */\nfunction extractParamCall(\n expr: ts.Expression,\n filePath: string,\n sourceFile: ts.SourceFile\n): ParamCallInfo {\n if (!ts.isCallExpression(expr)) {\n throw new ParserError(\n \"AX007\",\n \"Parameter value must be a call to a param.* helper\",\n filePath,\n posOf(sourceFile, expr),\n \"Use param.string(...), param.int(...), param.date(...), etc.\"\n );\n }\n\n // Expect: param.<type>(description?, config?)\n if (\n !ts.isPropertyAccessExpression(expr.expression) ||\n !ts.isIdentifier(expr.expression.expression) ||\n expr.expression.expression.text !== \"param\"\n ) {\n throw new ParserError(\n \"AX007\",\n \"Parameter value must be a call to a param.* helper\",\n filePath,\n posOf(sourceFile, expr),\n \"Use param.string(...), param.int(...), param.date(...), etc.\"\n );\n }\n\n const typeName = expr.expression.name.text;\n\n // For entity and dynamicOptions, the structure differs:\n // - param.entity(\"EntityName\", \"description\", config?)\n // - param.dynamicOptions(\"Provider\", param.string(...), \"description\", config?)\n let descriptionArg: ts.Expression | undefined;\n let configArg: ts.Expression | undefined;\n\n if (typeName === \"entity\" && expr.arguments.length >= 2) {\n descriptionArg = expr.arguments[1];\n configArg = expr.arguments[2];\n } else if (typeName === \"dynamicOptions\" && expr.arguments.length >= 3) {\n descriptionArg = expr.arguments[2];\n configArg = expr.arguments[3];\n } else {\n descriptionArg = expr.arguments[0];\n configArg = expr.arguments[1];\n }\n\n const description = descriptionArg ? readStringLiteral(descriptionArg) : null;\n if (description === null) {\n throw new ParserError(\n \"AX008\",\n `param.${typeName}() requires a string description`,\n filePath,\n posOf(sourceFile, expr),\n `Example: param.${typeName}(\"Human-readable description\")`\n );\n }\n\n const configObject =\n configArg && ts.isObjectLiteralExpression(configArg)\n ? propertyMap(configArg)\n : null;\n\n return { typeName, description, configObject, callExpr: expr };\n}\n\n/**\n * Resolve a param type name into an IRType.\n * Supports primitives, entity references, and dynamic options.\n */\nfunction resolveParamType(\n typeName: string,\n filePath: string,\n sourceFile: ts.SourceFile,\n node: ts.Node,\n callExpr?: ts.CallExpression\n): IRType {\n // Primitive types\n if (PARAM_TYPES.has(typeName as IRPrimitiveType)) {\n return { kind: \"primitive\", value: typeName as IRPrimitiveType };\n }\n\n // Legacy aliases\n if (typeName in LEGACY_PARAM_ALIASES) {\n return {\n kind: \"primitive\",\n value: LEGACY_PARAM_ALIASES[typeName],\n };\n }\n\n // Entity types: param.entity(\"EntityName\")\n if (typeName === \"entity\") {\n if (!callExpr || callExpr.arguments.length === 0) {\n throw new ParserError(\n \"AX020\",\n \"param.entity() requires the entity name as the first argument\",\n filePath,\n posOf(sourceFile, node),\n 'Example: param.entity(\"Task\", \"Reference an entity\")'\n );\n }\n const entityName = readStringLiteral(callExpr.arguments[0]);\n if (!entityName) {\n throw new ParserError(\n \"AX021\",\n \"param.entity() requires a string entity name\",\n filePath,\n posOf(sourceFile, node)\n );\n }\n return {\n kind: \"entity\",\n entityName,\n properties: [],\n };\n }\n\n // Dynamic options: param.dynamicOptions(\"ProviderName\", innerType)\n if (typeName === \"dynamicOptions\") {\n if (!callExpr || callExpr.arguments.length < 2) {\n throw new ParserError(\n \"AX022\",\n \"param.dynamicOptions() requires (providerName, paramType)\",\n filePath,\n posOf(sourceFile, node),\n 'Example: param.dynamicOptions(\"PlaylistProvider\", param.string(...))'\n );\n }\n const providerName = readStringLiteral(callExpr.arguments[0]);\n if (!providerName) {\n throw new ParserError(\n \"AX023\",\n \"param.dynamicOptions() provider name must be a string\",\n filePath,\n posOf(sourceFile, node)\n );\n }\n // TODO: Extract inner param type from the second argument\n const valueType: IRType = { kind: \"primitive\", value: \"string\" };\n return {\n kind: \"dynamicOptions\",\n valueType,\n providerName,\n };\n }\n\n throw new ParserError(\n \"AX005\",\n `Unknown param type: param.${typeName}`,\n filePath,\n posOf(sourceFile, node),\n `Supported types: ${[...PARAM_TYPES].join(\", \")}, entity, dynamicOptions`\n );\n}\n\n// ─── Literal Evaluation ──────────────────────────────────────────────\n\nfunction evaluateLiteral(node: ts.Expression): unknown {\n if (ts.isStringLiteral(node)) return node.text;\n if (ts.isNoSubstitutionTemplateLiteral(node)) return node.text;\n if (ts.isNumericLiteral(node)) return Number(node.text);\n if (node.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (node.kind === ts.SyntaxKind.FalseKeyword) return false;\n if (node.kind === ts.SyntaxKind.NullKeyword) return null;\n if (\n ts.isPrefixUnaryExpression(node) &&\n node.operator === ts.SyntaxKind.MinusToken &&\n ts.isNumericLiteral(node.operand)\n ) {\n return -Number(node.operand.text);\n }\n return undefined;\n}\n\n// ─── Return-Type Inference ───────────────────────────────────────────\n\nfunction inferReturnType(performNode: ts.Expression | undefined): IRType {\n // Default when we can't infer anything.\n const defaultType: IRType = { kind: \"primitive\", value: \"string\" };\n if (!performNode) return defaultType;\n\n // Handle method shorthand: perform() { ... }\n if (ts.isMethodDeclaration(performNode)) {\n return inferFromReturnStatements(performNode.body);\n }\n\n // Handle arrow function: perform: async () => { ... }\n if (ts.isArrowFunction(performNode)) {\n if (performNode.body && ts.isBlock(performNode.body)) {\n return inferFromReturnStatements(performNode.body);\n }\n // Single-expression arrow: perform: async (p) => \"literal\"\n return inferFromExpression(performNode.body as ts.Expression);\n }\n\n // Handle function expression: perform: async function() { ... }\n if (ts.isFunctionExpression(performNode)) {\n return inferFromReturnStatements(performNode.body);\n }\n\n return defaultType;\n}\n\nfunction inferFromReturnStatements(block: ts.Block | undefined): IRType {\n const defaultType: IRType = { kind: \"primitive\", value: \"string\" };\n if (!block) return defaultType;\n\n let inferred: IRType | undefined;\n const visit = (n: ts.Node): void => {\n if (inferred) return;\n if (ts.isReturnStatement(n) && n.expression) {\n inferred = inferFromExpression(n.expression);\n return;\n }\n // Don't walk into nested functions — only the top-level perform() body.\n if (\n ts.isFunctionDeclaration(n) ||\n ts.isFunctionExpression(n) ||\n ts.isArrowFunction(n)\n ) {\n return;\n }\n ts.forEachChild(n, visit);\n };\n visit(block);\n return inferred ?? defaultType;\n}\n\nfunction inferFromExpression(expr: ts.Expression): IRType {\n if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) {\n return { kind: \"primitive\", value: \"string\" };\n }\n if (ts.isNumericLiteral(expr)) {\n return expr.text.includes(\".\")\n ? { kind: \"primitive\", value: \"double\" }\n : { kind: \"primitive\", value: \"int\" };\n }\n if (\n expr.kind === ts.SyntaxKind.TrueKeyword ||\n expr.kind === ts.SyntaxKind.FalseKeyword\n ) {\n return { kind: \"primitive\", value: \"boolean\" };\n }\n // Default fallback\n return { kind: \"primitive\", value: \"string\" };\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction prettyTitle(name: string): string {\n const spaced = name.replace(/([A-Z])/g, \" $1\").trim();\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n\nfunction posOf(\n sourceFile: ts.SourceFile,\n node: ts.Node\n): number | undefined {\n try {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n return line + 1;\n } catch {\n return undefined;\n }\n}\n\n// ─── Error Class ─────────────────────────────────────────────────────\n\nexport class ParserError extends Error {\n constructor(\n public code: string,\n message: string,\n public file: string,\n public line?: number,\n public suggestion?: string\n ) {\n super(message);\n this.name = \"ParserError\";\n }\n\n format(): string {\n let output = `\\n error[${this.code}]: ${this.message}\\n`;\n if (this.file) output += ` --> ${this.file}`;\n if (this.line) output += `:${this.line}`;\n output += \"\\n\";\n if (this.suggestion) {\n output += ` = help: ${this.suggestion}\\n`;\n }\n return output;\n }\n}\n","/**\n * Axint Swift Code Generator\n *\n * Transforms the IR into clean, idiomatic Swift App Intent source code.\n * Uses string templates for readability and maintainability.\n *\n * In addition to the primary Swift file, this module can emit two\n * companion fragments:\n * - an Info.plist XML fragment, listing the keys the intent requires\n * - an .entitlements XML fragment, listing the entitlements the\n * intent requires\n *\n * Both fragments are designed to be merged into the host Xcode project\n * by the user (or a future axint-link command).\n */\n\nimport type { IRIntent, IRParameter, IRType, IREntity } from \"./types.js\";\nimport { irTypeToSwift } from \"./types.js\";\n\n// ─── String Escaping ─────────────────────────────────────────────────\n\n/**\n * Escape a string for safe interpolation into Swift string literals.\n * Prevents code injection via user-controlled titles/descriptions.\n */\nexport function escapeSwiftString(s: string): string {\n return s\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\t/g, \"\\\\t\");\n}\n\n/**\n * Escape a string for safe interpolation into XML (Info.plist or\n * .entitlements). Plist XML uses the same rules as general XML.\n */\nexport function escapeXml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&apos;\");\n}\n\n// ─── Primary Swift Generator ─────────────────────────────────────────\n\n/**\n * Generate a Swift App Intent source file from an IR intent.\n * If entities are present, they are generated first, followed by the intent.\n */\nexport function generateSwift(intent: IRIntent): string {\n const lines: string[] = [];\n\n // File header\n lines.push(`// ${intent.name}Intent.swift`);\n lines.push(`// Generated by Axint — https://github.com/agenticempire/axint`);\n lines.push(`// Do not edit manually. Re-run \\`axint compile\\` to regenerate.`);\n lines.push(``);\n lines.push(`import AppIntents`);\n lines.push(`import Foundation`);\n lines.push(``);\n\n // Generate entities before the intent\n if (intent.entities && intent.entities.length > 0) {\n for (const entity of intent.entities) {\n lines.push(generateEntity(entity));\n lines.push(``);\n lines.push(generateEntityQuery(entity));\n lines.push(``);\n }\n }\n\n // Struct declaration\n lines.push(`struct ${intent.name}Intent: AppIntent {`);\n\n // Static metadata\n lines.push(\n ` static let title: LocalizedStringResource = \"${escapeSwiftString(intent.title)}\"`\n );\n lines.push(\n ` static let description: IntentDescription = IntentDescription(\"${escapeSwiftString(intent.description)}\")`\n );\n if (intent.isDiscoverable !== undefined) {\n lines.push(` static let isDiscoverable: Bool = ${intent.isDiscoverable}`);\n }\n lines.push(``);\n\n // Parameters\n for (const param of intent.parameters) {\n lines.push(generateParameter(param));\n }\n\n if (intent.parameters.length > 0) {\n lines.push(``);\n }\n\n // Perform function with return-type aware signature\n const returnTypeSignature = generateReturnSignature(\n intent.returnType,\n intent.customResultType\n );\n lines.push(` func perform() async throws -> ${returnTypeSignature} {`);\n lines.push(` // TODO: Implement your intent logic here.`);\n\n if (intent.parameters.length > 0) {\n const paramList = intent.parameters.map((p) => `\\\\(${p.name})`).join(\", \");\n lines.push(` // Parameters available: ${paramList}`);\n }\n\n // Add intent donation if enabled\n if (intent.donateOnPerform) {\n lines.push(` `);\n lines.push(` // Donate this intent to Siri and Spotlight`);\n lines.push(` try? await IntentDonationManager.shared.donate(intent: self)`);\n }\n\n lines.push(generatePerformReturn(intent.returnType, intent.customResultType));\n lines.push(` }`);\n lines.push(`}`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Entity Generation ───────────────────────────────────────────────\n\n/**\n * Generate an AppEntity struct from an IREntity definition.\n */\nexport function generateEntity(entity: IREntity): string {\n const lines: string[] = [];\n const propertyNames = new Set(entity.properties.map((p) => p.name));\n\n lines.push(`struct ${entity.name}: AppEntity {`);\n lines.push(` static var defaultQuery = ${entity.name}Query()`);\n lines.push(``);\n\n // Apple requires AppEntity to have an id property\n const hasId = propertyNames.has(\"id\");\n if (!hasId) {\n lines.push(` var id: String`);\n }\n\n // Properties\n for (const prop of entity.properties) {\n const swiftType = irTypeToSwift(prop.type);\n lines.push(` var ${prop.name}: ${swiftType}`);\n }\n\n lines.push(``);\n\n // Type display representation\n lines.push(\n ` static let typeDisplayRepresentation: TypeDisplayRepresentation = TypeDisplayRepresentation(`\n );\n lines.push(\n ` name: LocalizedStringResource(\"${escapeSwiftString(entity.name)}\")`\n );\n lines.push(` )`);\n lines.push(``);\n\n // Display representation computed property — title/subtitle are property\n // name references, so we emit Swift string interpolation \\(propName)\n lines.push(` var displayRepresentation: DisplayRepresentation {`);\n lines.push(` DisplayRepresentation(`);\n lines.push(\n ` title: \"\\\\(${entity.displayRepresentation.title})\"${entity.displayRepresentation.subtitle || entity.displayRepresentation.image ? \",\" : \"\"}`\n );\n if (entity.displayRepresentation.subtitle) {\n const hasImage = !!entity.displayRepresentation.image;\n lines.push(\n ` subtitle: \"\\\\(${entity.displayRepresentation.subtitle})\"${hasImage ? \",\" : \"\"}`\n );\n }\n if (entity.displayRepresentation.image) {\n lines.push(\n ` image: .init(systemName: \"${escapeSwiftString(entity.displayRepresentation.image)}\")`\n );\n }\n lines.push(` )`);\n lines.push(` }`);\n\n lines.push(`}`);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate an EntityQuery conformance struct based on the entity's query type.\n */\nexport function generateEntityQuery(entity: IREntity): string {\n const lines: string[] = [];\n const queryType = entity.queryType;\n\n lines.push(`struct ${entity.name}Query: EntityQuery {`);\n lines.push(\n ` func entities(for identifiers: [${entity.name}.ID]) async throws -> [${entity.name}] {`\n );\n lines.push(` // TODO: Fetch entities by IDs`);\n lines.push(` return []`);\n lines.push(` }`);\n lines.push(``);\n\n // Generate appropriate query method based on queryType\n if (queryType === \"all\") {\n lines.push(` func allEntities() async throws -> [${entity.name}] {`);\n lines.push(` // TODO: Return all entities`);\n lines.push(` return []`);\n lines.push(` }`);\n } else if (queryType === \"id\") {\n // ID-based query is handled by entities(for:) above\n lines.push(` // ID-based query is provided by the entities(for:) method above`);\n } else if (queryType === \"string\") {\n lines.push(\n ` func entities(matching string: String) async throws -> [${entity.name}] {`\n );\n lines.push(` // TODO: Search entities by string`);\n lines.push(` return []`);\n lines.push(` }`);\n } else if (queryType === \"property\") {\n // Property-based query requires additional configuration\n lines.push(` // Property-based query: implement using EntityPropertyQuery`);\n lines.push(` // Example: property.where { \\\\$0.status == \"active\" }`);\n }\n\n lines.push(`}`);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Info.plist Fragment Generator ───────────────────────────────────\n\n/**\n * Generate an Info.plist XML fragment from the intent's declared keys.\n * Returns `undefined` if the intent declares no Info.plist keys.\n *\n * The fragment is a bare `<dict>`-less sequence of `<key>…</key>` /\n * `<string>…</string>` pairs, ready to be merged into an existing\n * Info.plist. A commented header identifies the source intent so users\n * can audit provenance.\n */\nexport function generateInfoPlistFragment(intent: IRIntent): string | undefined {\n const keys = intent.infoPlistKeys;\n if (!keys || Object.keys(keys).length === 0) return undefined;\n\n const lines: string[] = [];\n lines.push(`<?xml version=\"1.0\" encoding=\"UTF-8\"?>`);\n lines.push(`<!-- Info.plist fragment generated by Axint for ${intent.name}Intent -->`);\n lines.push(`<!-- Merge these keys into your app's Info.plist. -->`);\n lines.push(`<plist version=\"1.0\">`);\n lines.push(`<dict>`);\n for (const [key, desc] of Object.entries(keys)) {\n lines.push(` <key>${escapeXml(key)}</key>`);\n lines.push(` <string>${escapeXml(desc)}</string>`);\n }\n lines.push(`</dict>`);\n lines.push(`</plist>`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Entitlements Fragment Generator ─────────────────────────────────\n\n/**\n * Generate a `.entitlements` XML fragment from the intent's declared\n * entitlements. Returns `undefined` if the intent declares none.\n *\n * Axint only knows the entitlement identifiers, so all entries are\n * emitted as `<true/>` boolean entitlements. If an entitlement requires\n * a typed value (string, array), users must edit the fragment after\n * generation — a TODO comment is emitted to flag this.\n */\nexport function generateEntitlementsFragment(intent: IRIntent): string | undefined {\n const ents = intent.entitlements;\n if (!ents || ents.length === 0) return undefined;\n\n const lines: string[] = [];\n lines.push(`<?xml version=\"1.0\" encoding=\"UTF-8\"?>`);\n lines.push(\n `<!-- Entitlements fragment generated by Axint for ${intent.name}Intent -->`\n );\n lines.push(`<!-- Merge these into your target's .entitlements file. -->`);\n lines.push(`<!-- Note: entitlements requiring typed values (string/array) -->`);\n lines.push(`<!-- need manual adjustment — defaults below are boolean true. -->`);\n lines.push(\n `<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">`\n );\n lines.push(`<plist version=\"1.0\">`);\n lines.push(`<dict>`);\n for (const ent of ents) {\n lines.push(` <key>${escapeXml(ent)}</key>`);\n lines.push(` <true/>`);\n }\n lines.push(`</dict>`);\n lines.push(`</plist>`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction generateParameter(param: IRParameter): string {\n const swiftType = irTypeToSwift(param.type);\n const lines: string[] = [];\n\n // Build @Parameter decorator\n const attrs: string[] = [];\n attrs.push(`title: \"${escapeSwiftString(param.title)}\"`);\n if (param.description) {\n attrs.push(`description: \"${escapeSwiftString(param.description)}\"`);\n }\n\n const decorator = ` @Parameter(${attrs.join(\", \")})`;\n lines.push(decorator);\n\n // Property declaration\n if (param.defaultValue !== undefined) {\n const defaultStr = formatSwiftDefault(param.defaultValue, param.type);\n lines.push(` var ${param.name}: ${swiftType} = ${defaultStr}`);\n } else {\n lines.push(` var ${param.name}: ${swiftType}`);\n }\n\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Choose the Swift return-type signature for the generated perform().\n * We map the inferred IR return type to an App Intents `IntentResult`\n * shape. For primitive return types we use `some ReturnsValue<T>`;\n * for custom result types we use the custom type; otherwise we fall\n * back to `some IntentResult`.\n */\nfunction generateReturnSignature(type: IRType, customResultType?: string): string {\n if (customResultType) {\n return customResultType;\n }\n if (type.kind === \"primitive\") {\n const swift = irTypeToSwift(type);\n return `some IntentResult & ReturnsValue<${swift}>`;\n }\n if (type.kind === \"optional\" && type.innerType.kind === \"primitive\") {\n const swift = irTypeToSwift(type.innerType);\n return `some IntentResult & ReturnsValue<${swift}>`;\n }\n return `some IntentResult`;\n}\n\n/**\n * Emit the `return .result(...)` line that matches the return signature\n * produced by `generateReturnSignature`. When the return type is a\n * primitive we return a well-typed default placeholder the user can\n * replace; otherwise we emit a plain `.result()`.\n */\nfunction generatePerformReturn(type: IRType, customResultType?: string): string {\n const indent = \" \";\n if (customResultType) {\n // For custom result types, the user must provide the implementation\n return `${indent}// TODO: Return a ${customResultType} instance`;\n }\n if (type.kind === \"primitive\") {\n return `${indent}return .result(value: ${defaultLiteralFor(type.value)})`;\n }\n if (type.kind === \"optional\" && type.innerType.kind === \"primitive\") {\n return `${indent}return .result(value: ${defaultLiteralFor(type.innerType.value)})`;\n }\n return `${indent}return .result()`;\n}\n\nfunction defaultLiteralFor(primitive: string): string {\n switch (primitive) {\n case \"string\":\n return `\"\"`;\n case \"int\":\n return `0`;\n case \"double\":\n return `0.0`;\n case \"float\":\n return `Float(0)`;\n case \"boolean\":\n return `false`;\n case \"date\":\n return `Date()`;\n case \"duration\":\n return `Measurement<UnitDuration>(value: 0, unit: .seconds)`;\n case \"url\":\n return `URL(string: \"about:blank\")!`;\n default:\n return `\"\"`;\n }\n}\n\nfunction formatSwiftDefault(value: unknown, _type: IRType): string {\n if (typeof value === \"string\") return `\"${escapeSwiftString(value)}\"`;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) return `0`; // Guard against NaN/Infinity\n return `${value}`;\n }\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n return `\"${escapeSwiftString(String(value))}\"`; // Safe fallback\n}\n","/**\n * Axint Validator\n *\n * Validates generated Swift App Intent code against Apple's API surface.\n * Returns diagnostics with error codes, locations, and fix suggestions.\n */\n\nimport type { Diagnostic, IRIntent, IREntity } from \"./types.js\";\n\n/** Apple-recommended maximum parameters per intent for usability */\nconst MAX_PARAMETERS = 10;\n\n/** Maximum title length before Siri may truncate display */\nconst MAX_TITLE_LENGTH = 60;\n\n/**\n * Validate an IR intent for App Intents framework compliance.\n */\nexport function validateIntent(intent: IRIntent): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n\n // Rule: Intent name must be PascalCase and non-empty\n if (!intent.name || !/^[A-Z][a-zA-Z0-9]*$/.test(intent.name)) {\n diagnostics.push({\n code: \"AX100\",\n severity: \"error\",\n message: `Intent name \"${intent.name}\" must be PascalCase (e.g., \"CreateEvent\")`,\n file: intent.sourceFile,\n suggestion: `Rename to \"${toPascalCase(intent.name)}\"`,\n });\n }\n\n // Rule: Title must not be empty\n if (!intent.title || intent.title.trim().length === 0) {\n diagnostics.push({\n code: \"AX101\",\n severity: \"error\",\n message: \"Intent title must not be empty\",\n file: intent.sourceFile,\n suggestion: \"Add a human-readable title for Siri and Shortcuts display\",\n });\n }\n\n // Rule: Description must not be empty\n if (!intent.description || intent.description.trim().length === 0) {\n diagnostics.push({\n code: \"AX102\",\n severity: \"error\",\n message: \"Intent description must not be empty\",\n file: intent.sourceFile,\n suggestion: \"Add a description explaining what this intent does\",\n });\n }\n\n // Rule: Parameter names must be valid Swift identifiers\n for (const param of intent.parameters) {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(param.name)) {\n diagnostics.push({\n code: \"AX103\",\n severity: \"error\",\n message: `Parameter name \"${param.name}\" is not a valid Swift identifier`,\n file: intent.sourceFile,\n suggestion: `Rename to \"${param.name.replace(/[^a-zA-Z0-9_]/g, \"_\")}\"`,\n });\n }\n\n // Rule: Parameter description should not be empty\n if (!param.description || param.description.trim().length === 0) {\n diagnostics.push({\n code: \"AX104\",\n severity: \"warning\",\n message: `Parameter \"${param.name}\" has no description — Siri will display it without context`,\n file: intent.sourceFile,\n suggestion: \"Add a description for better Siri/Shortcuts display\",\n });\n }\n }\n\n // Rule: Max 10 parameters per intent (App Intents recommendation)\n if (intent.parameters.length > MAX_PARAMETERS) {\n diagnostics.push({\n code: \"AX105\",\n severity: \"warning\",\n message: `Intent has ${intent.parameters.length} parameters. Apple recommends ${MAX_PARAMETERS} or fewer for usability.`,\n file: intent.sourceFile,\n suggestion:\n \"Consider splitting into multiple intents or grouping parameters into an entity\",\n });\n }\n\n // Rule: Title should not exceed 60 characters (Siri display constraint)\n if (intent.title && intent.title.length > MAX_TITLE_LENGTH) {\n diagnostics.push({\n code: \"AX106\",\n severity: \"warning\",\n message: `Intent title is ${intent.title.length} characters. Siri display may truncate titles over ${MAX_TITLE_LENGTH} characters.`,\n file: intent.sourceFile,\n });\n }\n\n // Rule: Parameter names must be unique within an intent\n const seen = new Set<string>();\n for (const param of intent.parameters) {\n if (seen.has(param.name)) {\n diagnostics.push({\n code: \"AX107\",\n severity: \"error\",\n message: `Duplicate parameter name \"${param.name}\"`,\n file: intent.sourceFile,\n suggestion: \"Each parameter in a single intent must have a unique name\",\n });\n }\n seen.add(param.name);\n }\n\n // Rule: Entitlement strings must look like reverse-DNS identifiers\n for (const ent of intent.entitlements ?? []) {\n if (!/^[a-zA-Z0-9._-]+$/.test(ent) || !ent.includes(\".\")) {\n diagnostics.push({\n code: \"AX108\",\n severity: \"warning\",\n message: `Entitlement \"${ent}\" does not look like a valid reverse-DNS identifier`,\n file: intent.sourceFile,\n suggestion:\n 'Use reverse-DNS, e.g., \"com.apple.developer.siri\" or \"com.apple.security.app-sandbox\"',\n });\n }\n }\n\n // Rule: Info.plist keys must start with \"NS\" or other known prefixes\n for (const key of Object.keys(intent.infoPlistKeys ?? {})) {\n if (!/^(NS|UI|LS|CF|CA|CK)[A-Za-z0-9]+$/.test(key)) {\n diagnostics.push({\n code: \"AX109\",\n severity: \"warning\",\n message: `Info.plist key \"${key}\" does not match Apple's usual naming conventions`,\n file: intent.sourceFile,\n suggestion:\n 'Apple keys generally start with \"NS\" (e.g., \"NSCalendarsUsageDescription\")',\n });\n }\n }\n\n // Validate all entities\n if (intent.entities) {\n for (const entity of intent.entities) {\n diagnostics.push(...validateEntity(entity, intent.sourceFile));\n }\n }\n\n return diagnostics;\n}\n\n/**\n * Validate an IREntity for App Intents framework compliance.\n */\nexport function validateEntity(entity: IREntity, sourceFile: string): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n\n // Rule AX110: Entity name must be PascalCase\n if (!entity.name || !/^[A-Z][a-zA-Z0-9]*$/.test(entity.name)) {\n diagnostics.push({\n code: \"AX110\",\n severity: \"error\",\n message: `Entity name \"${entity.name}\" must be PascalCase (e.g., \"Task\", \"Playlist\")`,\n file: sourceFile,\n suggestion: `Rename to \"${toPascalCase(entity.name)}\"`,\n });\n }\n\n // Rule AX111: Entity must have at least one property\n if (entity.properties.length === 0) {\n diagnostics.push({\n code: \"AX111\",\n severity: \"error\",\n message: `Entity \"${entity.name}\" must have at least one property`,\n file: sourceFile,\n suggestion: \"Add properties to define the entity's structure\",\n });\n }\n\n // Rule AX112: Display title must reference an existing property\n const titleProp = entity.displayRepresentation.title;\n const propertyNames = new Set(entity.properties.map((p) => p.name));\n if (titleProp && !propertyNames.has(titleProp)) {\n diagnostics.push({\n code: \"AX112\",\n severity: \"warning\",\n message: `Display title \"${titleProp}\" does not reference an existing property`,\n file: sourceFile,\n suggestion: `Available properties: ${[...propertyNames].join(\", \")}`,\n });\n }\n\n // Rule AX113: Query type must be valid\n const validQueryTypes = [\"all\", \"id\", \"string\", \"property\"];\n if (!validQueryTypes.includes(entity.queryType)) {\n diagnostics.push({\n code: \"AX113\",\n severity: \"error\",\n message: `Entity query type \"${entity.queryType}\" is not valid`,\n file: sourceFile,\n suggestion: `Use one of: ${validQueryTypes.join(\", \")}`,\n });\n }\n\n return diagnostics;\n}\n\n/**\n * Validate generated Swift source code for basic correctness.\n */\nexport function validateSwiftSource(swift: string): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n\n // Check for required import\n if (!swift.includes(\"import AppIntents\")) {\n diagnostics.push({\n code: \"AX200\",\n severity: \"error\",\n message: 'Generated Swift is missing \"import AppIntents\"',\n });\n }\n\n // Check for AppIntent conformance\n if (!swift.includes(\": AppIntent\")) {\n diagnostics.push({\n code: \"AX201\",\n severity: \"error\",\n message: \"Generated struct does not conform to AppIntent protocol\",\n });\n }\n\n // Check for perform function\n if (!swift.includes(\"func perform()\")) {\n diagnostics.push({\n code: \"AX202\",\n severity: \"error\",\n message: \"Generated struct is missing the perform() function\",\n });\n }\n\n return diagnostics;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction toPascalCase(s: string): string {\n if (!s) return \"UnnamedIntent\";\n return s\n .replace(/[-_\\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : \"\"))\n .replace(/^(.)/, (c) => c.toUpperCase());\n}\n","/**\n * Axint Compiler\n *\n * Orchestrates the full compilation pipeline:\n * 1. Parse TypeScript intent definition → IR\n * 2. Validate IR against App Intents constraints\n * 3. Generate Swift source code\n * 4. Validate generated Swift\n * 5. Optionally emit Info.plist and entitlements fragments\n *\n * This is the main entry point for the compilation process.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parseIntentSource, ParserError } from \"./parser.js\";\nimport {\n generateSwift,\n generateInfoPlistFragment,\n generateEntitlementsFragment,\n} from \"./generator.js\";\nimport { validateIntent, validateSwiftSource } from \"./validator.js\";\nimport type {\n CompilerOutput,\n CompilerOptions,\n Diagnostic,\n IRIntent,\n IRType,\n IRParameter,\n IRPrimitiveType,\n} from \"./types.js\";\n\nexport interface CompileResult {\n success: boolean;\n output?: CompilerOutput;\n diagnostics: Diagnostic[];\n}\n\n/**\n * Compile a TypeScript intent definition file into Swift.\n */\nexport function compileFile(\n filePath: string,\n options: Partial<CompilerOptions> = {}\n): CompileResult {\n // 1. Read source\n let source: string;\n try {\n source = readFileSync(filePath, \"utf-8\");\n } catch (_err) {\n return {\n success: false,\n diagnostics: [\n {\n code: \"AX000\",\n severity: \"error\",\n message: `Cannot read file: ${filePath}`,\n file: filePath,\n },\n ],\n };\n }\n\n return compileSource(source, filePath, options);\n}\n\n/**\n * Compile a TypeScript source string directly (no file I/O).\n * Useful for MCP server and testing.\n */\nexport function compileSource(\n source: string,\n fileName: string = \"<stdin>\",\n options: Partial<CompilerOptions> = {}\n): CompileResult {\n // 1. Parse → IR (catch ParserError as a diagnostic so the caller\n // sees a clean error list instead of an uncaught exception)\n let ir;\n try {\n ir = parseIntentSource(source, fileName);\n } catch (err) {\n if (err instanceof ParserError) {\n return {\n success: false,\n diagnostics: [\n {\n code: err.code,\n severity: \"error\",\n message: err.message,\n file: err.file,\n line: err.line,\n suggestion: err.suggestion,\n },\n ],\n };\n }\n throw err;\n }\n\n return compileFromIR(ir, options);\n}\n\n/**\n * Compile from a pre-built IR (skips parsing). This is the bridge\n * that allows any frontend language (Python, Rust, Go) to emit an\n * IRIntent JSON and feed it directly into the Swift generator.\n *\n * Used by:\n * - `compileSource()` after its own parse step\n * - `axint compile --from-ir <file.json>` for cross-language pipelines\n * - The Python SDK's `axintai compile` command\n */\nexport function compileFromIR(\n ir: IRIntent,\n options: Partial<CompilerOptions> = {}\n): CompileResult {\n const diagnostics: Diagnostic[] = [];\n\n // 1. Validate IR\n const irDiagnostics = validateIntent(ir);\n diagnostics.push(...irDiagnostics);\n\n if (irDiagnostics.some((d) => d.severity === \"error\")) {\n return { success: false, diagnostics };\n }\n\n // 2. Generate Swift\n const swiftCode = generateSwift(ir);\n\n // 3. Validate generated Swift\n if (options.validate !== false) {\n const swiftDiagnostics = validateSwiftSource(swiftCode);\n diagnostics.push(...swiftDiagnostics);\n\n if (swiftDiagnostics.some((d) => d.severity === \"error\")) {\n return { success: false, diagnostics };\n }\n }\n\n // 4. Optional fragments\n const infoPlistFragment = options.emitInfoPlist\n ? generateInfoPlistFragment(ir)\n : undefined;\n const entitlementsFragment = options.emitEntitlements\n ? generateEntitlementsFragment(ir)\n : undefined;\n\n // 5. Build output\n const intentFileName = `${ir.name}Intent.swift`;\n const outputPath = options.outDir\n ? `${options.outDir}/${intentFileName}`\n : intentFileName;\n\n return {\n success: true,\n output: {\n outputPath,\n swiftCode,\n infoPlistFragment,\n entitlementsFragment,\n ir,\n diagnostics,\n },\n diagnostics,\n };\n}\n\n// ─── Cross-Language IR Bridge ───────────────────────────────────────\n\n/** Valid primitive type strings from any SDK */\nconst VALID_PRIMITIVES = new Set<string>([\n \"string\",\n \"int\",\n \"double\",\n \"float\",\n \"boolean\",\n \"date\",\n \"duration\",\n \"url\",\n]);\n\n/**\n * Parse a raw JSON object into a typed IRIntent. Accepts the flat\n * format that the Python SDK's `IntentIR.to_dict()` produces, where\n * parameter types are plain strings rather than `{ kind, value }` objects.\n *\n * This is the key function that bridges the Python → TypeScript gap.\n */\nexport function irFromJSON(data: Record<string, unknown>): IRIntent {\n const parameters: IRParameter[] = ((data.parameters as unknown[]) ?? []).map(\n (p: unknown) => {\n const param = p as Record<string, unknown>;\n return {\n name: param.name as string,\n type: normalizeIRType(param.type),\n title: (param.title as string) ?? (param.description as string) ?? \"\",\n description: (param.description as string) ?? \"\",\n isOptional: (param.optional as boolean) ?? (param.isOptional as boolean) ?? false,\n defaultValue: param.default ?? param.defaultValue,\n };\n }\n );\n\n return {\n name: data.name as string,\n title: data.title as string,\n description: data.description as string,\n domain: data.domain as string | undefined,\n parameters,\n returnType: data.returnType\n ? normalizeIRType(data.returnType)\n : { kind: \"primitive\", value: \"string\" },\n sourceFile: (data.sourceFile as string) ?? undefined,\n entitlements: (data.entitlements as string[]) ?? undefined,\n infoPlistKeys: (data.infoPlistKeys as Record<string, string>) ?? undefined,\n isDiscoverable: (data.isDiscoverable as boolean) ?? true,\n };\n}\n\n/**\n * Normalize a type value from JSON. The Python SDK sends types as\n * plain strings (\"string\", \"int\", etc.) while the TS IR uses\n * `{ kind: \"primitive\", value: \"string\" }`. This function handles both.\n */\nfunction normalizeIRType(type: unknown): IRType {\n if (typeof type === \"string\") {\n const normalized = type === \"number\" ? \"int\" : type;\n if (VALID_PRIMITIVES.has(normalized)) {\n return { kind: \"primitive\", value: normalized as IRPrimitiveType };\n }\n return { kind: \"primitive\", value: \"string\" };\n }\n if (type && typeof type === \"object\") {\n const t = type as Record<string, unknown>;\n if (t.kind === \"primitive\") return type as IRType;\n if (t.kind === \"array\")\n return { kind: \"array\", elementType: normalizeIRType(t.elementType) };\n if (t.kind === \"optional\")\n return { kind: \"optional\", innerType: normalizeIRType(t.innerType) };\n if (t.kind === \"entity\") return type as IRType;\n if (t.kind === \"enum\") return type as IRType;\n }\n // Default fallback\n return { kind: \"primitive\", value: \"string\" };\n}\n","/**\n * Intent Template Registry\n *\n * Pre-built reference templates for common App Intent patterns across\n * every major Apple domain. Each template is a complete, runnable\n * TypeScript file that compiles cleanly with `axint compile`.\n *\n * Templates are exposed through the MCP server (`axint_list_templates`,\n * `axint_template`) and the CLI (`axint new --template <id>`).\n */\n\nexport interface IntentTemplate {\n /** Unique template identifier, kebab-case */\n id: string;\n /** Short kebab/camel name (kept for backwards compat) */\n name: string;\n /** Human-readable display title */\n title: string;\n /** Apple App Intent domain */\n domain: string;\n /** Category for filtering — usually mirrors domain */\n category: string;\n /** Description of what this template generates */\n description: string;\n /** The TypeScript source template (uses defineIntent API) */\n source: string;\n}\n\n// ─── Template definitions ────────────────────────────────────────────\n\nconst sendMessage: IntentTemplate = {\n id: \"send-message\",\n name: \"send-message\",\n title: \"Send Message\",\n domain: \"messaging\",\n category: \"messaging\",\n description: \"Send a text message to a contact.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"SendMessage\",\n title: \"Send Message\",\n description: \"Sends a message to a specified contact.\",\n domain: \"messaging\",\n params: {\n recipient: param.string(\"Who to send the message to\"),\n body: param.string(\"The message content\"),\n },\n perform: async ({ recipient, body }) => {\n // TODO: Integrate with your messaging backend\n return { sent: true };\n },\n});\n`,\n};\n\nconst createEvent: IntentTemplate = {\n id: \"create-event\",\n name: \"create-event\",\n title: \"Create Calendar Event\",\n domain: \"productivity\",\n category: \"productivity\",\n description: \"Create a calendar event with a title, date, and duration.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"CreateEvent\",\n title: \"Create Calendar Event\",\n description: \"Creates a new event in the user's calendar.\",\n domain: \"productivity\",\n entitlements: [\"com.apple.developer.siri\"],\n infoPlistKeys: {\n NSCalendarsUsageDescription: \"Access to your calendar to create events.\",\n },\n params: {\n title: param.string(\"Event title\"),\n date: param.date(\"Event date\"),\n durationMinutes: param.int(\"Duration in minutes\", { default: 30 }),\n allDay: param.boolean(\"All-day event\", { required: false }),\n },\n perform: async ({ title, date }) => {\n return { eventId: \"evt_placeholder\" };\n },\n});\n`,\n};\n\nconst bookRide: IntentTemplate = {\n id: \"book-ride\",\n name: \"book-ride\",\n title: \"Book a Ride\",\n domain: \"navigation\",\n category: \"navigation\",\n description: \"Request a ride from a pickup location to a destination.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"BookRide\",\n title: \"Book a Ride\",\n description: \"Requests a ride from a pickup location to a destination.\",\n domain: \"navigation\",\n params: {\n pickup: param.string(\"Pickup location\"),\n destination: param.string(\"Destination address\"),\n passengers: param.int(\"Number of passengers\", { default: 1 }),\n },\n perform: async ({ pickup, destination }) => {\n return { rideId: \"ride_placeholder\", eta: 300 };\n },\n});\n`,\n};\n\nconst getDirections: IntentTemplate = {\n id: \"get-directions\",\n name: \"get-directions\",\n title: \"Get Directions\",\n domain: \"navigation\",\n category: \"navigation\",\n description: \"Get turn-by-turn directions to a destination.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"GetDirections\",\n title: \"Get Directions\",\n description: \"Returns turn-by-turn directions to a destination.\",\n domain: \"navigation\",\n params: {\n destination: param.string(\"Where to navigate to\"),\n mode: param.string(\"Travel mode (driving, walking, transit)\", {\n default: \"driving\",\n }),\n },\n perform: async ({ destination }) => {\n return { routeId: \"route_placeholder\" };\n },\n});\n`,\n};\n\nconst playTrack: IntentTemplate = {\n id: \"play-track\",\n name: \"play-track\",\n title: \"Play Track\",\n domain: \"media\",\n category: \"media\",\n description: \"Play a specific track or song.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"PlayTrack\",\n title: \"Play Track\",\n description: \"Plays a specific track by title and artist.\",\n domain: \"media\",\n params: {\n track: param.string(\"Track title\"),\n artist: param.string(\"Artist name\", { required: false }),\n shuffle: param.boolean(\"Shuffle mode\", { required: false }),\n },\n perform: async ({ track }) => {\n return { playing: true };\n },\n});\n`,\n};\n\nconst createNote: IntentTemplate = {\n id: \"create-note\",\n name: \"create-note\",\n title: \"Create Note\",\n domain: \"productivity\",\n category: \"productivity\",\n description: \"Create a new note with a title and body.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"CreateNote\",\n title: \"Create Note\",\n description: \"Creates a new note with a title and body.\",\n domain: \"productivity\",\n params: {\n title: param.string(\"Note title\"),\n body: param.string(\"Note body\"),\n pinned: param.boolean(\"Pin the note\", { required: false }),\n },\n perform: async ({ title, body }) => {\n return { noteId: \"note_placeholder\" };\n },\n});\n`,\n};\n\nconst logExpense: IntentTemplate = {\n id: \"log-expense\",\n name: \"log-expense\",\n title: \"Log Expense\",\n domain: \"finance\",\n category: \"finance\",\n description: \"Log a financial expense with amount, category, and note.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"LogExpense\",\n title: \"Log Expense\",\n description: \"Logs a financial expense with amount, category, and note.\",\n domain: \"finance\",\n params: {\n amount: param.double(\"Expense amount\"),\n currency: param.string(\"ISO currency code (e.g., USD)\", {\n default: \"USD\",\n }),\n category: param.string(\"Expense category\"),\n note: param.string(\"Optional note\", { required: false }),\n },\n perform: async ({ amount, category }) => {\n return { expenseId: \"exp_placeholder\" };\n },\n});\n`,\n};\n\nconst logWorkout: IntentTemplate = {\n id: \"log-workout\",\n name: \"log-workout\",\n title: \"Log Workout\",\n domain: \"health\",\n category: \"health\",\n description: \"Log a workout with duration, type, and calories burned.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"LogWorkout\",\n title: \"Log Workout\",\n description: \"Logs a workout with duration, type, and calories burned.\",\n domain: \"health\",\n entitlements: [\"com.apple.developer.healthkit\"],\n infoPlistKeys: {\n NSHealthShareUsageDescription: \"Read workout history to track progress.\",\n NSHealthUpdateUsageDescription: \"Save new workouts you log.\",\n },\n params: {\n type: param.string(\"Workout type (e.g., running, cycling)\"),\n duration: param.duration(\"Workout duration\"),\n calories: param.int(\"Calories burned\", { required: false }),\n },\n perform: async ({ type, duration }) => {\n return { workoutId: \"wo_placeholder\" };\n },\n});\n`,\n};\n\nconst setThermostat: IntentTemplate = {\n id: \"set-thermostat\",\n name: \"set-thermostat\",\n title: \"Set Thermostat\",\n domain: \"smart-home\",\n category: \"smart-home\",\n description: \"Set a smart-home thermostat to a target temperature.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"SetThermostat\",\n title: \"Set Thermostat\",\n description: \"Sets a smart-home thermostat to a target temperature.\",\n domain: \"smart-home\",\n params: {\n room: param.string(\"Which room\"),\n temperature: param.double(\"Target temperature\"),\n unit: param.string(\"Temperature unit (F or C)\", { default: \"F\" }),\n },\n perform: async ({ room, temperature }) => {\n return { set: true };\n },\n});\n`,\n};\n\nconst placeOrder: IntentTemplate = {\n id: \"place-order\",\n name: \"place-order\",\n title: \"Place Order\",\n domain: \"commerce\",\n category: \"commerce\",\n description: \"Place a commerce order for a product.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"PlaceOrder\",\n title: \"Place Order\",\n description: \"Places an order for a product.\",\n domain: \"commerce\",\n params: {\n productId: param.string(\"Product identifier\"),\n quantity: param.int(\"Quantity\", { default: 1 }),\n shippingAddress: param.string(\"Shipping address\", { required: false }),\n },\n perform: async ({ productId, quantity }) => {\n return { orderId: \"ord_placeholder\", total: 0 };\n },\n});\n`,\n};\n\nconst searchTasks: IntentTemplate = {\n id: \"search-tasks\",\n name: \"search-tasks\",\n title: \"Search Tasks\",\n domain: \"productivity\",\n category: \"productivity\",\n description: \"Search for tasks using EntityQuery with string-based search.\",\n source: `import { defineIntent, defineEntity, param } from \"@axintai/compiler\";\n\ndefineEntity({\n name: \"Task\",\n display: {\n title: \"name\",\n subtitle: \"status\",\n },\n properties: {\n id: param.string(\"Unique task identifier\"),\n name: param.string(\"Task name\"),\n status: param.string(\"Task status (todo, in-progress, done)\"),\n dueDate: param.date(\"Due date\"),\n },\n query: \"string\",\n});\n\nexport default defineIntent({\n name: \"SearchTasks\",\n title: \"Search Tasks\",\n description: \"Search for tasks by name or status.\",\n domain: \"productivity\",\n params: {\n query: param.string(\"Search query\"),\n status: param.string(\"Filter by status (optional)\", { required: false }),\n },\n donateOnPerform: true,\n perform: async ({ query, status }) => {\n // TODO: Search your task database with the query\n // Use status filter if provided\n return { found: true, results: 0 };\n },\n});\n`,\n};\n\nconst dynamicPlaylist: IntentTemplate = {\n id: \"dynamic-playlist\",\n name: \"dynamic-playlist\",\n title: \"Dynamic Playlist\",\n domain: \"media\",\n category: \"media\",\n description: \"Create a playlist by name, mood, and track count.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"DynamicPlaylist\",\n title: \"Create Dynamic Playlist\",\n description: \"Create a playlist with a given mood or genre.\",\n domain: \"media\",\n params: {\n name: param.string(\"Playlist name\"),\n mood: param.string(\"Mood or genre (e.g., chill, workout, focus)\"),\n trackCount: param.int(\"Number of tracks\", { default: 20 }),\n },\n perform: async ({ name, mood }) => {\n return { playlistId: \"playlist_placeholder\" };\n },\n});\n`,\n};\n\n// ─── Registry ────────────────────────────────────────────────────────\n\nexport const TEMPLATES: IntentTemplate[] = [\n sendMessage,\n createEvent,\n bookRide,\n getDirections,\n playTrack,\n createNote,\n logExpense,\n logWorkout,\n setThermostat,\n placeOrder,\n searchTasks,\n dynamicPlaylist,\n];\n\n/** @deprecated Use TEMPLATES. Kept for v0.1.x import compatibility. */\nexport const templates = TEMPLATES;\n\nexport function getTemplate(id: string): IntentTemplate | undefined {\n return TEMPLATES.find((t) => t.id === id);\n}\n\nexport function listTemplates(category?: string): IntentTemplate[] {\n if (category) {\n return TEMPLATES.filter((t) => t.category === category);\n }\n return TEMPLATES;\n}\n","/**\n * swift-format integration (optional post-processor)\n *\n * After codegen, optionally pipe the emitted Swift through Apple's\n * `swift-format` tool with a house style file that mirrors Apple's own\n * codebase. This is the last stage of the pipeline that runs before\n * writing to disk.\n *\n * `swift-format` ships with the Swift toolchain on macOS. If the binary\n * isn't on $PATH (Linux CI, Windows, containers) we log a warning and\n * return the source unchanged rather than failing the build — the\n * generator already emits valid, well-indented Swift without it.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { writeFile, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { tmpdir } from \"node:os\";\n\nexport interface FormatOptions {\n /** Hard timeout in ms for the swift-format call (default 8s) */\n timeoutMs?: number;\n /** Throw on failure instead of returning the original source */\n strict?: boolean;\n}\n\nexport interface FormatResult {\n formatted: string;\n ran: boolean;\n reason?: string;\n}\n\n/** The house style file — tracks Apple's swift-format defaults + Axint tweaks. */\nexport const SWIFT_FORMAT_CONFIG = {\n version: 1,\n lineLength: 100,\n indentation: { spaces: 4 },\n tabWidth: 4,\n maximumBlankLines: 1,\n respectsExistingLineBreaks: true,\n lineBreakBeforeControlFlowKeywords: false,\n lineBreakBeforeEachArgument: false,\n lineBreakBeforeEachGenericRequirement: false,\n prioritizeKeepingFunctionOutputTogether: false,\n indentConditionalCompilationBlocks: true,\n lineBreakAroundMultilineExpressionChainComponents: false,\n fileScopedDeclarationPrivacy: { accessLevel: \"private\" },\n rules: {\n AllPublicDeclarationsHaveDocumentation: false,\n AlwaysUseLowerCamelCase: true,\n AmbiguousTrailingClosureOverload: true,\n BeginDocumentationCommentWithOneLineSummary: false,\n DoNotUseSemicolons: true,\n DontRepeatTypeInStaticProperties: true,\n FileScopedDeclarationPrivacy: true,\n FullyIndirectEnum: true,\n GroupNumericLiterals: true,\n IdentifiersMustBeASCII: true,\n NeverForceUnwrap: false,\n NeverUseForceTry: false,\n NeverUseImplicitlyUnwrappedOptionals: false,\n NoBlockComments: false,\n NoCasesWithOnlyFallthrough: true,\n NoEmptyTrailingClosureParentheses: true,\n NoLabelsInCasePatterns: true,\n NoLeadingUnderscores: false,\n NoParensAroundConditions: true,\n NoVoidReturnOnFunctionSignature: true,\n OneCasePerLine: true,\n OneVariableDeclarationPerLine: true,\n OnlyOneTrailingClosureArgument: true,\n OrderedImports: true,\n ReturnVoidInsteadOfEmptyTuple: true,\n UseEarlyExits: false,\n UseLetInEveryBoundCaseVariable: true,\n UseShorthandTypeNames: true,\n UseSingleLinePropertyGetter: true,\n UseSynthesizedInitializer: true,\n UseTripleSlashForDocumentationComments: true,\n UseWhereClausesInForLoops: false,\n ValidateDocumentationComments: false,\n },\n} as const;\n\n/**\n * Run swift-format against a Swift source string and return the formatted\n * output. Falls back to the original source if swift-format is unavailable.\n */\nexport async function formatSwift(\n source: string,\n options: FormatOptions = {}\n): Promise<FormatResult> {\n const available = await hasSwiftFormat();\n if (!available) {\n if (options.strict) {\n throw new Error(\n \"swift-format not found on $PATH. Install Xcode + Command Line Tools, or drop --format.\"\n );\n }\n return {\n formatted: source,\n ran: false,\n reason: \"swift-format not found on $PATH\",\n };\n }\n\n const configPath = join(\n tmpdir(),\n `axint-swift-format-${Date.now()}-${Math.random().toString(36).slice(2)}.json`\n );\n await writeFile(configPath, JSON.stringify(SWIFT_FORMAT_CONFIG, null, 2));\n\n try {\n const result = await runSwiftFormat(source, configPath, options.timeoutMs ?? 8_000);\n if (result.code === 0) {\n return { formatted: result.stdout, ran: true };\n }\n if (options.strict) {\n throw new Error(`swift-format failed: ${result.stderr}`);\n }\n return {\n formatted: source,\n ran: false,\n reason: `swift-format exited ${result.code}: ${result.stderr}`,\n };\n } finally {\n await unlink(configPath).catch(() => undefined);\n }\n}\n\nfunction hasSwiftFormat(): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(\"swift-format\", [\"--version\"], { stdio: \"pipe\" });\n child.on(\"error\", () => resolve(false));\n child.on(\"exit\", (code) => resolve(code === 0));\n });\n}\n\nfunction runSwiftFormat(\n source: string,\n configPath: string,\n timeoutMs: number\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolve) => {\n const child = spawn(\"swift-format\", [\"format\", \"--configuration\", configPath], {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (d) => (stdout += d.toString()));\n child.stderr?.on(\"data\", (d) => (stderr += d.toString()));\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n resolve({\n stdout,\n stderr: stderr + `\\n[format] killed after ${timeoutMs}ms`,\n code: 124,\n });\n }, timeoutMs);\n child.on(\"exit\", (code) => {\n clearTimeout(timer);\n resolve({ stdout, stderr, code: code ?? 1 });\n });\n child.stdin?.write(source);\n child.stdin?.end();\n });\n}\n","/**\n * Stage 4 Validator — SPM Sandbox Compile\n *\n * The \"prove the Swift actually builds\" stage. Generated Swift is dropped into\n * a throwaway Swift Package Manager project and compiled with `swift build`.\n * If it builds cleanly, we've proven the intent file is Xcode-ready.\n *\n * This stage is macOS-only (requires `swift` in PATH and the App Intents\n * framework from the Xcode SDK). It's wired behind the `--sandbox` flag so\n * Linux/Windows CI stays green without it.\n *\n * The sandbox lives in a deterministic directory inside os.tmpdir() so that\n * repeated invocations can reuse the `.build/` cache — typical per-intent\n * compile time is ~1.2s warm, ~4s cold on an M-series Mac.\n */\n\nimport { mkdir, writeFile, rm } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { tmpdir } from \"node:os\";\nimport { spawn } from \"node:child_process\";\n\nexport interface SandboxOptions {\n intentName: string;\n /** Override the sandbox root (default: $TMPDIR/axint-sandbox) */\n rootDir?: string;\n /** Keep the sandbox on disk after the run (default: false) */\n keep?: boolean;\n /** Hard timeout in ms for the `swift build` call (default: 60s) */\n timeoutMs?: number;\n}\n\nexport interface SandboxResult {\n ok: boolean;\n stdout: string;\n stderr: string;\n durationMs: number;\n sandboxPath: string;\n}\n\nconst PACKAGE_SWIFT = (name: string) => `// swift-tools-version:5.9\nimport PackageDescription\n\nlet package = Package(\n name: \"${name}Sandbox\",\n platforms: [\n .iOS(.v16),\n .macOS(.v13),\n ],\n products: [\n .library(name: \"${name}Sandbox\", targets: [\"${name}Sandbox\"]),\n ],\n targets: [\n .target(\n name: \"${name}Sandbox\",\n path: \"Sources/${name}Sandbox\"\n ),\n ]\n)\n`;\n\n/**\n * Compile a Swift source string inside a throwaway SPM project and return\n * the result. Does not throw on build failure — the caller inspects `ok`.\n */\nexport async function sandboxCompile(\n swiftSource: string,\n options: SandboxOptions\n): Promise<SandboxResult> {\n const start = Date.now();\n\n // Check that swift is available before we touch disk\n const available = await hasSwiftToolchain();\n if (!available) {\n throw new Error(\n \"Swift toolchain not found. Install Xcode + Command Line Tools, or run without `--sandbox`.\"\n );\n }\n\n const root = options.rootDir ?? join(tmpdir(), \"axint-sandbox\", options.intentName);\n const srcDir = join(root, \"Sources\", `${options.intentName}Sandbox`);\n\n try {\n await mkdir(srcDir, { recursive: true });\n await writeFile(join(root, \"Package.swift\"), PACKAGE_SWIFT(options.intentName));\n await writeFile(join(srcDir, `${options.intentName}Intent.swift`), swiftSource);\n } catch (err) {\n return {\n ok: false,\n stdout: \"\",\n stderr: `Failed to stage sandbox: ${(err as Error).message}`,\n durationMs: Date.now() - start,\n sandboxPath: root,\n };\n }\n\n const { stdout, stderr, code } = await runSwiftBuild(root, options.timeoutMs ?? 60_000);\n\n if (!options.keep && code === 0) {\n // Only tear down on success — keep failures for post-mortem.\n await rm(root, { recursive: true, force: true }).catch(() => undefined);\n }\n\n return {\n ok: code === 0,\n stdout,\n stderr,\n durationMs: Date.now() - start,\n sandboxPath: root,\n };\n}\n\nasync function hasSwiftToolchain(): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(\"swift\", [\"--version\"], { stdio: \"pipe\" });\n child.on(\"error\", () => resolve(false));\n child.on(\"exit\", (code) => resolve(code === 0));\n });\n}\n\nfunction runSwiftBuild(\n cwd: string,\n timeoutMs: number\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolve) => {\n const child = spawn(\"swift\", [\"build\", \"-c\", \"debug\"], {\n cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (d) => (stdout += d.toString()));\n child.stderr?.on(\"data\", (d) => (stderr += d.toString()));\n\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n resolve({\n stdout,\n stderr: stderr + `\\n[sandbox] killed after ${timeoutMs}ms`,\n code: 124,\n });\n }, timeoutMs);\n\n child.on(\"exit\", (code) => {\n clearTimeout(timer);\n resolve({ stdout, stderr, code: code ?? 1 });\n });\n });\n}\n\n/** Helper for tests: check whether the sandbox dir exists */\nexport function sandboxExists(intentName: string): boolean {\n return existsSync(join(tmpdir(), \"axint-sandbox\", intentName));\n}\n","/**\n * Scaffold generator for the axint MCP server.\n *\n * Produces a ready-to-save TypeScript intent file from a small set of\n * inputs. This is the \"blank canvas\" AI assistants hit when a user says\n * \"create a new App Intent for X\" — instead of guessing, the assistant\n * calls axint_scaffold and writes the result straight to disk.\n */\n\nimport {\n PARAM_TYPES,\n LEGACY_PARAM_ALIASES,\n type IRPrimitiveType,\n} from \"../core/types.js\";\n\nexport interface ScaffoldInput {\n name: string;\n description: string;\n domain?: string;\n params?: Array<{ name: string; type: string; description: string }>;\n}\n\n/**\n * Generate a starter TypeScript intent file from the given inputs.\n * The result is valid input to `axint compile` — it uses the public\n * defineIntent() / param.* API and includes a TODO in the perform body.\n */\nexport function scaffoldIntent(input: ScaffoldInput): string {\n const name = toPascalCase(input.name);\n const title = humanize(name);\n const desc = sanitize(input.description);\n const domain = input.domain ? sanitize(input.domain) : undefined;\n\n const paramLines: string[] = [];\n const destructureNames: string[] = [];\n for (const p of input.params ?? []) {\n const type = resolveType(p.type);\n const safeName = toCamelCase(p.name);\n destructureNames.push(safeName);\n paramLines.push(\n ` ${safeName}: param.${type}(${JSON.stringify(sanitize(p.description))}),`\n );\n }\n\n const paramsBlock = paramLines.length > 0 ? `\\n${paramLines.join(\"\\n\")}\\n ` : \"\";\n const destructure =\n destructureNames.length > 0 ? `{ ${destructureNames.join(\", \")} }` : \"_\";\n\n const lines: string[] = [];\n lines.push(`/**`);\n lines.push(` * ${name}Intent`);\n lines.push(` *`);\n lines.push(` * ${desc}`);\n lines.push(` *`);\n lines.push(` * Generated by axint_scaffold. Edit freely, then run:`);\n lines.push(` * npx axint compile src/intents/${kebab(name)}.ts`);\n lines.push(` */`);\n lines.push(`import { defineIntent, param } from \"@axintai/compiler\";`);\n lines.push(``);\n lines.push(`export default defineIntent({`);\n lines.push(` name: ${JSON.stringify(name)},`);\n lines.push(` title: ${JSON.stringify(title)},`);\n lines.push(` description: ${JSON.stringify(desc)},`);\n if (domain) lines.push(` domain: ${JSON.stringify(domain)},`);\n lines.push(` params: {${paramsBlock}},`);\n lines.push(` perform: async (${destructure}) => {`);\n lines.push(` // TODO: Implement ${name}`);\n lines.push(` return { success: true };`);\n lines.push(` },`);\n lines.push(`});`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction resolveType(raw: string): IRPrimitiveType {\n const lc = raw.toLowerCase();\n if (PARAM_TYPES.has(lc as IRPrimitiveType)) return lc as IRPrimitiveType;\n if (lc in LEGACY_PARAM_ALIASES) return LEGACY_PARAM_ALIASES[lc];\n // Fall back to string — keeps scaffolding from throwing on unknown\n // types. Users can edit the file if they wanted something more exotic.\n return \"string\";\n}\n\nfunction toPascalCase(s: string): string {\n if (!s) return \"UnnamedIntent\";\n return s\n .replace(/[-_\\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : \"\"))\n .replace(/^(.)/, (c) => c.toUpperCase());\n}\n\nfunction toCamelCase(s: string): string {\n const pascal = toPascalCase(s);\n return pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n\nfunction humanize(pascal: string): string {\n return pascal.replace(/([A-Z])/g, \" $1\").trim();\n}\n\nfunction kebab(pascal: string): string {\n return pascal\n .replace(/([a-z])([A-Z])/g, \"$1-$2\")\n .replace(/\\s+/g, \"-\")\n .toLowerCase();\n}\n\n/**\n * Keep user-provided strings safe for interpolation. We strip control\n * chars and collapse runs of whitespace — this prevents scaffold output\n * from getting garbled by rogue newlines or tabs in a description.\n */\nfunction sanitize(s: string): string {\n return s\n .replace(/[\\x00-\\x1f\\x7f]+/g, \" \") // eslint-disable-line no-control-regex\n .replace(/\\s+/g, \" \")\n .trim();\n}\n","/**\n * Axint MCP Server\n *\n * Exposes Axint capabilities as MCP tools that AI coding assistants\n * (Claude Code, Cursor, Windsurf, Zed, any MCP client) can call\n * automatically.\n *\n * Tools:\n * - axint_scaffold: Generate a starter TypeScript intent file\n * - axint_compile: Compile TypeScript intent → Swift App Intent\n * (optionally with Info.plist and entitlements)\n * - axint_validate: Validate an intent definition without codegen\n * - axint_list_templates: List bundled reference templates\n * - axint_template: Return the source of a specific template\n */\n\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { compileSource } from \"../core/compiler.js\";\nimport { scaffoldIntent } from \"./scaffold.js\";\nimport { TEMPLATES, getTemplate } from \"../templates/index.js\";\n\n// Read version from package.json so it stays in sync\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(\n readFileSync(resolve(__dirname, \"../../package.json\"), \"utf-8\")\n);\n\ntype CompileArgs = {\n source: string;\n fileName?: string;\n emitInfoPlist?: boolean;\n emitEntitlements?: boolean;\n};\n\ntype ScaffoldArgs = {\n name: string;\n description: string;\n domain?: string;\n params?: Array<{ name: string; type: string; description: string }>;\n};\n\ntype TemplateArgs = { id: string };\n\nexport async function startMCPServer(): Promise<void> {\n const server = new Server(\n { name: \"axint\", version: pkg.version },\n { capabilities: { tools: {} } }\n );\n\n // List available tools\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [\n {\n name: \"axint_scaffold\",\n description:\n \"Generate a starter TypeScript intent file using the axint SDK. \" +\n \"Pass a PascalCase name, a description, and optionally a domain \" +\n \"(messaging, productivity, health, finance, commerce, media, \" +\n \"navigation, smart-home) and a list of parameters. Returns ready-\" +\n \"to-save source code that compiles with `axint compile`.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n name: {\n type: \"string\",\n description: \"PascalCase name for the intent, e.g., 'CreateEvent'\",\n },\n description: {\n type: \"string\",\n description: \"Human-readable description of what the intent does\",\n },\n domain: {\n type: \"string\",\n description:\n \"Optional Apple App Intent domain (messaging, productivity, \" +\n \"health, finance, commerce, media, navigation, smart-home)\",\n },\n params: {\n type: \"array\",\n description:\n \"Optional initial parameters. Each item: { name, type, description }. \" +\n \"Supported types: string, int, double, float, boolean, date, duration, url.\",\n items: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n type: { type: \"string\" },\n description: { type: \"string\" },\n },\n required: [\"name\", \"type\", \"description\"],\n },\n },\n },\n required: [\"name\", \"description\"],\n },\n },\n {\n name: \"axint_compile\",\n description:\n \"Compile a TypeScript intent definition into a native Swift App \" +\n \"Intent. Optionally emits Info.plist and entitlements fragments \" +\n \"alongside the Swift file. Pass the full TypeScript source code \" +\n \"using the defineIntent() API.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n source: {\n type: \"string\",\n description: \"TypeScript source code containing a defineIntent() call\",\n },\n fileName: {\n type: \"string\",\n description: \"Optional file name for error messages\",\n },\n emitInfoPlist: {\n type: \"boolean\",\n description:\n \"When true, also returns an Info.plist XML fragment for the \" +\n \"intent's declared infoPlistKeys\",\n },\n emitEntitlements: {\n type: \"boolean\",\n description:\n \"When true, also returns an .entitlements XML fragment for \" +\n \"the intent's declared entitlements\",\n },\n },\n required: [\"source\"],\n },\n },\n {\n name: \"axint_validate\",\n description:\n \"Validate a TypeScript intent definition without generating Swift \" +\n \"output. Returns diagnostics with error codes and fix suggestions.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n source: {\n type: \"string\",\n description: \"TypeScript source code containing a defineIntent() call\",\n },\n },\n required: [\"source\"],\n },\n },\n {\n name: \"axint_list_templates\",\n description:\n \"List the bundled reference templates. Use `axint_template` to \" +\n \"fetch the full source of a specific template by id.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"axint_template\",\n description:\n \"Return the full TypeScript source code of a bundled reference \" +\n \"template by id. Use `axint_list_templates` to discover valid ids.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n id: {\n type: \"string\",\n description: \"Template id (e.g., 'send-message', 'create-event')\",\n },\n },\n required: [\"id\"],\n },\n },\n ],\n }));\n\n // Handle tool calls\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n try {\n if (name === \"axint_scaffold\") {\n const a = args as unknown as ScaffoldArgs;\n const source = scaffoldIntent({\n name: a.name,\n description: a.description,\n domain: a.domain,\n params: a.params,\n });\n return { content: [{ type: \"text\" as const, text: source }] };\n }\n\n if (name === \"axint_compile\") {\n const a = args as unknown as CompileArgs;\n const result = compileSource(a.source, a.fileName || \"<mcp>\", {\n emitInfoPlist: a.emitInfoPlist,\n emitEntitlements: a.emitEntitlements,\n });\n\n if (result.success && result.output) {\n const parts: string[] = [\n \"// ─── Swift ──────────────────────────\",\n result.output.swiftCode,\n ];\n if (result.output.infoPlistFragment) {\n parts.push(\"// ─── Info.plist fragment ────────────\");\n parts.push(result.output.infoPlistFragment);\n }\n if (result.output.entitlementsFragment) {\n parts.push(\"// ─── .entitlements fragment ─────────\");\n parts.push(result.output.entitlementsFragment);\n }\n return {\n content: [{ type: \"text\" as const, text: parts.join(\"\\n\") }],\n };\n }\n\n const errorText = result.diagnostics\n .map((d) => `[${d.code}] ${d.severity}: ${d.message}`)\n .join(\"\\n\");\n return {\n content: [{ type: \"text\" as const, text: errorText }],\n isError: true,\n };\n }\n\n if (name === \"axint_validate\") {\n const a = args as unknown as { source: string };\n const result = compileSource(a.source, \"<validate>\");\n const text =\n result.diagnostics.length > 0\n ? result.diagnostics\n .map((d) => `[${d.code}] ${d.severity}: ${d.message}`)\n .join(\"\\n\")\n : \"Valid intent definition. No issues found.\";\n return { content: [{ type: \"text\" as const, text }] };\n }\n\n if (name === \"axint_list_templates\") {\n const list = TEMPLATES.map(\n (t) => `${t.id} — ${t.title}${t.domain ? ` [${t.domain}]` : \"\"}`\n ).join(\"\\n\");\n return {\n content: [\n {\n type: \"text\" as const,\n text: list || \"No templates registered.\",\n },\n ],\n };\n }\n\n if (name === \"axint_template\") {\n const a = args as unknown as TemplateArgs;\n const tpl = getTemplate(a.id);\n if (!tpl) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Unknown template id: ${a.id}. Use axint_list_templates to see available ids.`,\n },\n ],\n isError: true,\n };\n }\n return { content: [{ type: \"text\" as const, text: tpl.source }] };\n }\n\n return {\n content: [{ type: \"text\" as const, text: `Unknown tool: ${name}` }],\n isError: true,\n };\n } catch (err: unknown) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Tool error: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n isError: true,\n };\n }\n });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n","/**\n * Axint CLI\n *\n * The command-line interface for the Axint compiler.\n *\n * axint init [dir] Scaffold a new Axint project\n * axint compile <file> Compile TS intent → Swift App Intent\n * axint validate <file> Validate a compiled intent\n * axint eject <file> Eject intent to standalone Swift (no vendor lock-in)\n * axint templates List bundled intent templates\n * axint login Authenticate with the Axint Registry\n * axint publish Publish an intent to the Registry\n * axint add <package> Install a template from the Registry\n * axint mcp Start the MCP server (stdio)\n * axint --version Show version\n */\n\nimport { Command } from \"commander\";\nimport { readFileSync, writeFileSync, mkdirSync, existsSync } from \"node:fs\";\nimport { resolve, dirname, basename } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { compileFile, compileFromIR, irFromJSON } from \"../core/compiler.js\";\nimport { ejectIntent } from \"../core/eject.js\";\nimport { scaffoldProject } from \"./scaffold.js\";\nimport { listTemplates, getTemplate } from \"../templates/index.js\";\n\n// Read version from package.json so it stays in sync\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(resolve(__dirname, \"../../package.json\"), \"utf-8\"));\nconst VERSION = pkg.version as string;\n\nconst program = new Command();\n\nprogram\n .name(\"axint\")\n .description(\n \"The open-source compiler that transforms AI agent definitions into native Apple App Intents.\"\n )\n .version(VERSION);\n\n// ─── init ────────────────────────────────────────────────────────────\n\nprogram\n .command(\"init\")\n .description(\"Scaffold a new Axint project (zero-config, ready to compile)\")\n .argument(\"[dir]\", \"Project directory (defaults to current dir)\", \".\")\n .option(\n \"-t, --template <name>\",\n \"Starter template (send-message, create-event, book-ride, ...)\",\n \"create-event\"\n )\n .option(\"--no-install\", \"Skip running `npm install`\")\n .option(\"--name <name>\", \"Project name (defaults to the directory name)\")\n .action(\n async (\n dir: string,\n options: { template: string; install: boolean; name?: string }\n ) => {\n const targetDir = resolve(dir);\n const projectName = options.name ?? basename(targetDir);\n\n try {\n const result = await scaffoldProject({\n targetDir,\n projectName,\n template: options.template,\n version: VERSION,\n install: options.install,\n });\n\n console.log();\n console.log(` \\x1b[38;5;208m◆\\x1b[0m \\x1b[1mAxint\\x1b[0m · project ready`);\n console.log();\n console.log(\n ` \\x1b[2m${result.files.length} files written to ${targetDir}\\x1b[0m`\n );\n console.log();\n console.log(` \\x1b[1mNext:\\x1b[0m`);\n if (dir !== \".\") console.log(` cd ${dir}`);\n if (options.install) {\n console.log(\n ` npx axint compile intents/${result.entryFile} --out ios/Intents/`\n );\n } else {\n console.log(` npm install`);\n console.log(\n ` npx axint compile intents/${result.entryFile} --out ios/Intents/`\n );\n }\n console.log();\n console.log(` \\x1b[2mDocs: https://axint.ai/docs\\x1b[0m`);\n console.log(\n ` \\x1b[2mMCP: npx axint-mcp (add to Claude Code, Cursor, Windsurf)\\x1b[0m`\n );\n console.log();\n } catch (err: unknown) {\n console.error(`\\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n process.exit(1);\n }\n }\n );\n\n// ─── compile ─────────────────────────────────────────────────────────\n\nprogram\n .command(\"compile\")\n .description(\"Compile a TypeScript intent definition into Swift\")\n .argument(\"<file>\", \"Path to the TypeScript intent definition\")\n .option(\"-o, --out <dir>\", \"Output directory for generated Swift\", \".\")\n .option(\"--no-validate\", \"Skip validation of generated Swift\")\n .option(\"--stdout\", \"Print generated Swift to stdout instead of writing a file\")\n .option(\"--json\", \"Output result as JSON (machine-readable)\")\n .option(\n \"--emit-info-plist\",\n \"Emit a <Name>.plist.fragment.xml with NSAppIntentsDomains next to the Swift file\"\n )\n .option(\n \"--emit-entitlements\",\n \"Emit a <Name>.entitlements.fragment.xml next to the Swift file\"\n )\n .option(\n \"--sandbox\",\n \"Run stage 4 validation: swift build in an SPM sandbox (macOS only)\"\n )\n .option(\n \"--format\",\n \"Pipe generated Swift through swift-format with the Axint house style (macOS/Linux if swift-format is on $PATH)\"\n )\n .option(\n \"--strict-format\",\n \"Fail the build if swift-format is missing or errors (implies --format)\"\n )\n .option(\n \"--from-ir\",\n \"Treat <file> as IR JSON (from Python SDK or any language) instead of TypeScript. Use - to read from stdin.\"\n )\n .action(\n async (\n file: string,\n options: {\n out: string;\n validate: boolean;\n stdout: boolean;\n json: boolean;\n emitInfoPlist: boolean;\n emitEntitlements: boolean;\n sandbox: boolean;\n format: boolean;\n strictFormat: boolean;\n fromIr: boolean;\n }\n ) => {\n const filePath = resolve(file);\n\n try {\n let result;\n\n if (options.fromIr) {\n // Cross-language bridge: read IR JSON and skip the TS parser\n let irRaw: string;\n if (file === \"-\") {\n // Read from stdin\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n irRaw = Buffer.concat(chunks).toString(\"utf-8\");\n } else {\n irRaw = readFileSync(filePath, \"utf-8\");\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(irRaw);\n } catch {\n console.error(`\\x1b[31merror:\\x1b[0m Invalid JSON in ${file}`);\n process.exit(1);\n }\n\n // Accept both a single IR object and an array (Python SDK emits arrays)\n const irData = Array.isArray(parsed)\n ? (parsed[0] as Record<string, unknown>)\n : (parsed as Record<string, unknown>);\n if (!irData || typeof irData !== \"object\") {\n console.error(\n `\\x1b[31merror:\\x1b[0m Expected an IR object or array in ${file}`\n );\n process.exit(1);\n }\n\n const ir = irFromJSON(irData);\n result = compileFromIR(ir, {\n outDir: options.out,\n validate: options.validate,\n emitInfoPlist: options.emitInfoPlist,\n emitEntitlements: options.emitEntitlements,\n });\n } else {\n result = compileFile(filePath, {\n outDir: options.out,\n validate: options.validate,\n emitInfoPlist: options.emitInfoPlist,\n emitEntitlements: options.emitEntitlements,\n });\n }\n\n // JSON mode — output everything as structured JSON and exit\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n success: result.success,\n swift: result.output?.swiftCode ?? null,\n outputPath: result.output?.outputPath ?? null,\n infoPlistFragment: result.output?.infoPlistFragment ?? null,\n entitlementsFragment: result.output?.entitlementsFragment ?? null,\n diagnostics: result.diagnostics.map((d) => ({\n code: d.code,\n severity: d.severity,\n message: d.message,\n file: d.file,\n line: d.line,\n suggestion: d.suggestion,\n })),\n },\n null,\n 2\n )\n );\n if (!result.success) process.exit(1);\n return;\n }\n\n // Print diagnostics\n for (const d of result.diagnostics) {\n const prefix =\n d.severity === \"error\"\n ? \"\\x1b[31merror\\x1b[0m\"\n : d.severity === \"warning\"\n ? \"\\x1b[33mwarning\\x1b[0m\"\n : \"\\x1b[36minfo\\x1b[0m\";\n\n console.error(` ${prefix}[${d.code}]: ${d.message}`);\n if (d.file) console.error(` --> ${d.file}${d.line ? `:${d.line}` : \"\"}`);\n if (d.suggestion) console.error(` = help: ${d.suggestion}`);\n console.error();\n }\n\n if (!result.success || !result.output) {\n console.error(\n `\\x1b[31mCompilation failed with ${result.diagnostics.filter((d) => d.severity === \"error\").length} error(s)\\x1b[0m`\n );\n process.exit(1);\n }\n\n // Optional swift-format pass — mutate the swiftCode in place before writing\n if (options.format || options.strictFormat) {\n try {\n const { formatSwift } = await import(\"../core/format.js\");\n const fmt = await formatSwift(result.output.swiftCode, {\n strict: options.strictFormat,\n });\n if (fmt.ran) {\n result.output.swiftCode = fmt.formatted;\n } else if (!options.json) {\n console.error(\n `\\x1b[33mwarning:\\x1b[0m swift-format skipped — ${fmt.reason}`\n );\n }\n } catch (fmtErr: unknown) {\n if (options.strictFormat) {\n console.error(`\\x1b[31merror:\\x1b[0m ${(fmtErr as Error).message}`);\n process.exit(1);\n }\n console.error(\n `\\x1b[33mwarning:\\x1b[0m swift-format skipped — ${(fmtErr as Error).message}`\n );\n }\n }\n\n if (options.stdout) {\n console.log(result.output.swiftCode);\n } else {\n const outPath = resolve(result.output.outputPath);\n mkdirSync(dirname(outPath), { recursive: true });\n writeFileSync(outPath, result.output.swiftCode, \"utf-8\");\n console.log(`\\x1b[32m✓\\x1b[0m Compiled ${result.output.ir.name} → ${outPath}`);\n\n // Emit optional fragments next to the Swift file\n if (options.emitInfoPlist && result.output.infoPlistFragment) {\n const plistPath = outPath.replace(/\\.swift$/, \".plist.fragment.xml\");\n writeFileSync(plistPath, result.output.infoPlistFragment, \"utf-8\");\n console.log(`\\x1b[32m✓\\x1b[0m Info.plist fragment → ${plistPath}`);\n }\n\n if (options.emitEntitlements && result.output.entitlementsFragment) {\n const entPath = outPath.replace(/\\.swift$/, \".entitlements.fragment.xml\");\n writeFileSync(entPath, result.output.entitlementsFragment, \"utf-8\");\n console.log(`\\x1b[32m✓\\x1b[0m Entitlements fragment → ${entPath}`);\n }\n }\n\n // Stage 4 validation: SPM sandbox compile\n if (options.sandbox && !options.stdout) {\n try {\n const { sandboxCompile } = await import(\"../core/sandbox.js\");\n console.log();\n console.log(`\\x1b[36m→\\x1b[0m Stage 4: SPM sandbox compile...`);\n const sandboxResult = await sandboxCompile(result.output.swiftCode, {\n intentName: result.output.ir.name,\n });\n if (sandboxResult.ok) {\n console.log(\n `\\x1b[32m✓\\x1b[0m Swift builds cleanly (${sandboxResult.durationMs}ms in ${sandboxResult.sandboxPath})`\n );\n } else {\n console.error(\n `\\x1b[31m✗\\x1b[0m Sandbox compile failed:\\n${sandboxResult.stderr}`\n );\n process.exit(1);\n }\n } catch (sbErr: unknown) {\n console.error(\n `\\x1b[33mwarning:\\x1b[0m sandbox compile skipped — ${(sbErr as Error).message}`\n );\n }\n }\n\n const warnings = result.diagnostics.filter(\n (d) => d.severity === \"warning\"\n ).length;\n if (warnings > 0) {\n console.log(` ${warnings} warning(s)`);\n }\n } catch (err: unknown) {\n if (\n err &&\n typeof err === \"object\" &&\n \"format\" in err &&\n typeof (err as Record<string, unknown>).format === \"function\"\n ) {\n console.error((err as { format: () => string }).format());\n } else {\n console.error(`\\x1b[31merror:\\x1b[0m ${err}`);\n }\n process.exit(1);\n }\n }\n );\n\n// ─── validate ────────────────────────────────────────────────────────\n\nprogram\n .command(\"validate\")\n .description(\"Validate a TypeScript intent definition without generating output\")\n .argument(\"<file>\", \"Path to the TypeScript intent definition\")\n .option(\n \"--sandbox\",\n \"Run stage 4 validation: swift build in an SPM sandbox (macOS only)\"\n )\n .action(async (file: string, options: { sandbox: boolean }) => {\n const filePath = resolve(file);\n\n try {\n const result = compileFile(filePath, { validate: true });\n\n for (const d of result.diagnostics) {\n const prefix =\n d.severity === \"error\"\n ? \"\\x1b[31merror\\x1b[0m\"\n : d.severity === \"warning\"\n ? \"\\x1b[33mwarning\\x1b[0m\"\n : \"\\x1b[36minfo\\x1b[0m\";\n console.error(` ${prefix}[${d.code}]: ${d.message}`);\n if (d.suggestion) console.error(` = help: ${d.suggestion}`);\n }\n\n if (!result.success) {\n process.exit(1);\n }\n\n if (options.sandbox && result.output) {\n const { sandboxCompile } = await import(\"../core/sandbox.js\");\n console.log(`\\x1b[36m→\\x1b[0m Stage 4: SPM sandbox compile...`);\n const sandboxResult = await sandboxCompile(result.output.swiftCode, {\n intentName: result.output.ir.name,\n });\n if (!sandboxResult.ok) {\n console.error(`\\x1b[31m✗\\x1b[0m ${sandboxResult.stderr}`);\n process.exit(1);\n }\n console.log(\n `\\x1b[32m✓\\x1b[0m Valid intent definition (sandbox-verified, ${sandboxResult.durationMs}ms)`\n );\n } else {\n console.log(`\\x1b[32m✓\\x1b[0m Valid intent definition`);\n }\n } catch (err: unknown) {\n if (\n err &&\n typeof err === \"object\" &&\n \"format\" in err &&\n typeof (err as Record<string, unknown>).format === \"function\"\n ) {\n console.error((err as { format: () => string }).format());\n } else {\n console.error(`\\x1b[31merror:\\x1b[0m ${err}`);\n }\n process.exit(1);\n }\n });\n\n// ─── eject ──────────────────────────────────────────────────────────\n\nprogram\n .command(\"eject\")\n .description(\"Eject an intent to standalone Swift with no Axint dependency\")\n .argument(\"<file>\", \"Path to the TypeScript intent definition\")\n .option(\"-o, --out <dir>\", \"Output directory for ejected files\", \".\")\n .option(\"--include-tests\", \"Generate a basic XCTest file alongside the Swift\")\n .option(\n \"--format\",\n \"Pipe generated Swift through swift-format with the Axint house style (macOS/Linux if swift-format is on $PATH)\"\n )\n .action(\n async (\n file: string,\n options: {\n out: string;\n includeTests: boolean;\n format: boolean;\n }\n ) => {\n const filePath = resolve(file);\n\n try {\n // Read source\n let source: string;\n try {\n source = readFileSync(filePath, \"utf-8\");\n } catch (_err) {\n console.error(`\\x1b[31merror:\\x1b[0m Cannot read file: ${filePath}`);\n process.exit(1);\n }\n\n // Eject\n const result = ejectIntent(source, basename(filePath), {\n outDir: options.out,\n includeTests: options.includeTests,\n format: options.format,\n });\n\n // Write all files\n const filesWritten: string[] = [];\n\n // Swift file\n mkdirSync(dirname(result.swiftFile.path), { recursive: true });\n writeFileSync(result.swiftFile.path, result.swiftFile.content, \"utf-8\");\n filesWritten.push(\"Swift\");\n\n // Optional Info.plist fragment\n if (result.infoPlist) {\n writeFileSync(result.infoPlist.path, result.infoPlist.content, \"utf-8\");\n filesWritten.push(\"Info.plist fragment\");\n }\n\n // Optional entitlements fragment\n if (result.entitlements) {\n writeFileSync(result.entitlements.path, result.entitlements.content, \"utf-8\");\n filesWritten.push(\"entitlements fragment\");\n }\n\n // Optional test file\n if (result.testFile) {\n writeFileSync(result.testFile.path, result.testFile.content, \"utf-8\");\n filesWritten.push(\"XCTest file\");\n }\n\n // Success message\n console.log();\n console.log(\n `\\x1b[32m✓\\x1b[0m Ejected → ${filesWritten.length} file(s) (${filesWritten.join(\", \")})`\n );\n console.log();\n console.log(` \\x1b[1mOutput directory:\\x1b[0m ${resolve(options.out)}`);\n console.log();\n console.log(` These files are now standalone and have no Axint dependency.`);\n console.log(\n ` You can commit them to version control and use them in your project.`\n );\n console.log();\n } catch (err: unknown) {\n if (\n err &&\n typeof err === \"object\" &&\n \"format\" in err &&\n typeof (err as Record<string, unknown>).format === \"function\"\n ) {\n console.error((err as { format: () => string }).format());\n } else {\n console.error(`\\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n }\n process.exit(1);\n }\n }\n );\n\n// ─── templates ───────────────────────────────────────────────────────\n\nprogram\n .command(\"templates\")\n .description(\"List bundled intent templates\")\n .argument(\"[name]\", \"Template name to print (omit to list all)\")\n .option(\"--json\", \"Output as JSON\")\n .action((name: string | undefined, options: { json: boolean }) => {\n if (!name) {\n const list = listTemplates();\n if (options.json) {\n console.log(JSON.stringify(list, null, 2));\n return;\n }\n console.log(` \\x1b[1mBundled templates\\x1b[0m (${list.length})`);\n console.log();\n for (const t of list) {\n console.log(\n ` \\x1b[38;5;208m◆\\x1b[0m ${t.name} \\x1b[2m— ${t.description}\\x1b[0m`\n );\n }\n console.log();\n console.log(\n ` \\x1b[2mUse: axint templates <name> or axint init -t <name>\\x1b[0m`\n );\n return;\n }\n\n const tpl = getTemplate(name);\n if (!tpl) {\n console.error(`\\x1b[31merror:\\x1b[0m template \"${name}\" not found`);\n process.exit(1);\n }\n if (options.json) {\n console.log(JSON.stringify(tpl, null, 2));\n return;\n }\n console.log(tpl.source);\n });\n\n// ─── login ──────────────────────────────────────────────────────────\n//\n// Device-code flow for CLI auth against registry.axint.ai.\n// Opens the browser to complete GitHub OAuth, polls for the token,\n// stores it in ~/.axint/credentials.json.\n\nprogram\n .command(\"login\")\n .description(\"Authenticate with the Axint Registry via GitHub\")\n .action(async () => {\n const { homedir } = await import(\"node:os\");\n const { join } = await import(\"node:path\");\n const { spawn } = await import(\"node:child_process\");\n\n const configDir = join(homedir(), \".axint\");\n const credPath = join(configDir, \"credentials.json\");\n const registryUrl = process.env.AXINT_REGISTRY_URL ?? \"https://registry.axint.ai\";\n\n console.log();\n console.log(` \\x1b[38;5;208m◆\\x1b[0m \\x1b[1mAxint\\x1b[0m · login`);\n console.log();\n\n try {\n // Request a device code from the registry\n const res = await fetch(`${registryUrl}/api/v1/auth/device-code`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: \"axint-cli\" }),\n });\n\n if (!res.ok) {\n console.error(\n `\\x1b[31merror:\\x1b[0m Failed to start login flow (HTTP ${res.status})`\n );\n process.exit(1);\n }\n\n const { device_code, user_code, verification_uri, interval } =\n (await res.json()) as {\n device_code: string;\n user_code: string;\n verification_uri: string;\n interval: number;\n };\n\n console.log(` Open this URL in your browser:`);\n console.log();\n console.log(` \\x1b[1;4m${verification_uri}\\x1b[0m`);\n console.log();\n console.log(` And enter this code: \\x1b[1;38;5;208m${user_code}\\x1b[0m`);\n console.log();\n console.log(` \\x1b[2mWaiting for authorization…\\x1b[0m`);\n\n // Best-effort browser open — spawn with array args to avoid shell injection\n try {\n const openCmd =\n process.platform === \"darwin\"\n ? \"open\"\n : process.platform === \"win32\"\n ? \"start\"\n : \"xdg-open\";\n spawn(openCmd, [verification_uri], { stdio: \"ignore\", detached: true }).unref();\n } catch {\n // non-blocking — user can open the URL manually\n }\n\n // Poll for the token\n const pollInterval = (interval ?? 5) * 1000;\n let token: string | null = null;\n\n for (let i = 0; i < 60; i++) {\n await new Promise((r) => setTimeout(r, pollInterval));\n\n const pollRes = await fetch(`${registryUrl}/api/v1/auth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ device_code, grant_type: \"device_code\" }),\n });\n\n if (pollRes.ok) {\n const data = (await pollRes.json()) as { access_token: string };\n token = data.access_token;\n break;\n }\n\n const err = (await pollRes.json()) as { error?: string };\n if (err.error === \"authorization_pending\") continue;\n if (err.error === \"slow_down\") {\n await new Promise((r) => setTimeout(r, 5000));\n continue;\n }\n if (err.error === \"expired_token\") {\n console.error(\n `\\x1b[31merror:\\x1b[0m Login timed out. Run \\`axint login\\` again.`\n );\n process.exit(1);\n }\n console.error(`\\x1b[31merror:\\x1b[0m ${err.error ?? \"Unknown error\"}`);\n process.exit(1);\n }\n\n if (!token) {\n console.error(`\\x1b[31merror:\\x1b[0m Login timed out after 5 minutes.`);\n process.exit(1);\n }\n\n // Save credentials\n mkdirSync(configDir, { recursive: true });\n writeFileSync(\n credPath,\n JSON.stringify({ access_token: token, registry: registryUrl }, null, 2),\n \"utf-8\"\n );\n\n console.log(\n ` \\x1b[32m✓\\x1b[0m Logged in! Credentials saved to \\x1b[2m${credPath}\\x1b[0m`\n );\n console.log();\n } catch (err: unknown) {\n console.error(`\\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n process.exit(1);\n }\n });\n\n// ─── publish ────────────────────────────────────────────────────────\n//\n// Reads axint.json from the current directory, compiles the intent,\n// and publishes it to registry.axint.ai.\n\nprogram\n .command(\"publish\")\n .description(\"Publish an intent to the Axint Registry\")\n .option(\"--dry-run\", \"Validate and show what would be published without uploading\")\n .option(\"--tag <tags...>\", \"Override tags\")\n .action(async (options: { dryRun?: boolean; tag?: string[] }) => {\n const cwd = process.cwd();\n const configPath = resolve(cwd, \"axint.json\");\n\n console.log();\n console.log(` \\x1b[38;5;208m◆\\x1b[0m \\x1b[1mAxint\\x1b[0m · publish`);\n console.log();\n\n // 1. Read axint.json\n if (!existsSync(configPath)) {\n console.error(` \\x1b[31merror:\\x1b[0m No axint.json found in ${cwd}`);\n console.error(` \\x1b[2mRun \\`axint init\\` to create one.\\x1b[0m`);\n process.exit(1);\n }\n\n let config: {\n name: string;\n namespace: string;\n slug: string;\n version: string;\n description?: string;\n primary_language?: string;\n surface_areas?: string[];\n tags?: string[];\n license?: string;\n homepage?: string;\n repository?: string;\n entry?: string;\n readme?: string;\n siri_phrases?: string[];\n permissions?: string[];\n };\n\n try {\n config = JSON.parse(readFileSync(configPath, \"utf-8\"));\n } catch {\n console.error(` \\x1b[31merror:\\x1b[0m Failed to parse axint.json`);\n process.exit(1);\n }\n\n const entryFile = config.entry ?? \"intent.ts\";\n const entryPath = resolve(cwd, entryFile);\n\n if (!existsSync(entryPath)) {\n console.error(` \\x1b[31merror:\\x1b[0m Entry file not found: ${entryFile}`);\n process.exit(1);\n }\n\n console.log(` \\x1b[2m⏺\\x1b[0m Compiling ${entryFile}…`);\n\n // 2. Compile\n let result: Awaited<ReturnType<typeof compileFile>>;\n try {\n result = await compileFile(entryPath, {});\n } catch (err: unknown) {\n console.error(` \\x1b[31m✗\\x1b[0m Compilation failed: ${(err as Error).message}`);\n process.exit(1);\n }\n\n if (!result.success || !result.output) {\n console.error(` \\x1b[31m✗\\x1b[0m Compilation failed`);\n for (const d of result.diagnostics) {\n console.error(` [${d.code}] ${d.message}`);\n }\n process.exit(1);\n }\n\n console.log(\n ` \\x1b[32m✓\\x1b[0m Compiled → ${result.output.swiftCode.split(\"\\n\").length} lines of Swift`\n );\n\n // 3. Read optional files\n let readme: string | undefined;\n const readmePath = resolve(cwd, config.readme ?? \"README.md\");\n if (existsSync(readmePath)) {\n readme = readFileSync(readmePath, \"utf-8\");\n }\n\n let pySource: string | undefined;\n const pyPath = resolve(cwd, entryFile.replace(/\\.ts$/, \".py\"));\n if (existsSync(pyPath)) {\n pySource = readFileSync(pyPath, \"utf-8\");\n }\n\n const tags = options.tag ?? config.tags ?? [];\n const namespace = config.namespace.startsWith(\"@\")\n ? config.namespace\n : `@${config.namespace}`;\n\n const payload = {\n namespace,\n slug: config.slug,\n name: config.name,\n version: config.version,\n description: config.description,\n readme,\n primary_language: config.primary_language ?? (pySource ? \"both\" : \"typescript\"),\n surface_areas: config.surface_areas ?? [],\n tags,\n license: config.license ?? \"Apache-2.0\",\n homepage: config.homepage,\n repository: config.repository,\n ts_source: readFileSync(entryPath, \"utf-8\"),\n py_source: pySource,\n swift_output: result.output.swiftCode,\n plist_fragment: result.output.infoPlistFragment ?? null,\n ir: result.output.ir ?? {},\n compiler_version: VERSION,\n };\n\n if (options.dryRun) {\n console.log(` \\x1b[32m✓\\x1b[0m Validation passed`);\n console.log();\n console.log(\n ` Would publish: \\x1b[1m${namespace}/${config.slug}@${config.version}\\x1b[0m`\n );\n console.log(\n ` Bundle size: ${Buffer.from(JSON.stringify(payload)).byteLength} bytes`\n );\n console.log(` Tags: ${tags.join(\", \") || \"(none)\"}`);\n console.log();\n return;\n }\n\n // 4. Load credentials\n const { homedir } = await import(\"node:os\");\n const { join } = await import(\"node:path\");\n const credPath = join(homedir(), \".axint\", \"credentials.json\");\n\n if (!existsSync(credPath)) {\n console.error(` \\x1b[31merror:\\x1b[0m Not logged in. Run \\`axint login\\` first.`);\n process.exit(1);\n }\n\n let creds: { access_token: string; registry: string };\n try {\n creds = JSON.parse(readFileSync(credPath, \"utf-8\"));\n } catch {\n console.error(\n ` \\x1b[31merror:\\x1b[0m Corrupt credentials file. Run \\`axint login\\` again.`\n );\n process.exit(1);\n }\n\n const registryUrl = creds.registry ?? \"https://registry.axint.ai\";\n\n console.log(` \\x1b[2m⏺\\x1b[0m Publishing to ${registryUrl}…`);\n\n // 5. Publish\n try {\n const res = await fetch(`${registryUrl}/api/v1/publish`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${creds.access_token}`,\n \"X-Axint-Version\": VERSION,\n },\n body: JSON.stringify(payload),\n });\n\n if (!res.ok) {\n const err = (await res.json().catch(() => ({ detail: res.statusText }))) as {\n detail?: string;\n title?: string;\n };\n console.error(\n ` \\x1b[31m✗\\x1b[0m ${err.title ?? \"Publish failed\"}: ${err.detail ?? res.statusText}`\n );\n process.exit(1);\n }\n\n const data = (await res.json()) as { url: string };\n\n console.log(` \\x1b[32m✓\\x1b[0m Published!`);\n console.log();\n console.log(` ${data.url}`);\n console.log();\n console.log(` \\x1b[2mInstall: axint add ${namespace}/${config.slug}\\x1b[0m`);\n console.log();\n } catch (err: unknown) {\n console.error(` \\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n process.exit(1);\n }\n });\n\n// ─── add ────────────────────────────────────────────────────────────\n//\n// Install a template from the Axint Registry.\n// Usage: axint add @namespace/slug[@version] [--to dir]\n\nprogram\n .command(\"add\")\n .description(\"Install a template from the Axint Registry\")\n .argument(\n \"<package>\",\n \"Template to install (e.g., @axintai/create-event or @axintai/create-event@1.0.0)\"\n )\n .option(\"--to <dir>\", \"Target directory\", \"intents\")\n .action(async (pkg: string, options: { to: string }) => {\n console.log();\n console.log(` \\x1b[38;5;208m◆\\x1b[0m \\x1b[1mAxint\\x1b[0m · add`);\n console.log();\n\n // Parse @namespace/slug@version\n const match = pkg.match(/^(@[a-z0-9][a-z0-9-]*)\\/([a-z0-9][a-z0-9-]*)(?:@(.+))?$/);\n if (!match) {\n console.error(\n ` \\x1b[31merror:\\x1b[0m Invalid package format. Expected: @namespace/slug or @namespace/slug@version`\n );\n process.exit(1);\n }\n\n const [, namespace, slug, version] = match;\n const registryUrl = process.env.AXINT_REGISTRY_URL ?? \"https://registry.axint.ai\";\n\n console.log(\n ` \\x1b[2m⏺\\x1b[0m Fetching ${namespace}/${slug}${version ? `@${version}` : \"\"}…`\n );\n\n try {\n const params = new URLSearchParams({ namespace, slug });\n if (version) params.set(\"version\", version);\n\n const res = await fetch(`${registryUrl}/api/v1/install?${params}`, {\n headers: { \"X-Axint-Version\": VERSION },\n });\n\n if (!res.ok) {\n const err = (await res.json().catch(() => ({ detail: res.statusText }))) as {\n detail?: string;\n };\n console.error(\n ` \\x1b[31m✗\\x1b[0m ${err.detail ?? `Template not found (HTTP ${res.status})`}`\n );\n process.exit(1);\n }\n\n const data = (await res.json()) as {\n template: { name: string; full_name: string; primary_language: string };\n version: {\n version: string;\n ts_source?: string;\n py_source?: string;\n swift_output: string;\n };\n bundle_sha256: string;\n };\n\n const targetDir = resolve(options.to, slug);\n mkdirSync(targetDir, { recursive: true });\n\n // Write source files\n const ver = data.version;\n const filesWritten: string[] = [];\n\n if (ver.ts_source) {\n writeFileSync(resolve(targetDir, \"intent.ts\"), ver.ts_source, \"utf-8\");\n filesWritten.push(\"intent.ts\");\n }\n if (ver.py_source) {\n writeFileSync(resolve(targetDir, \"intent.py\"), ver.py_source, \"utf-8\");\n filesWritten.push(\"intent.py\");\n }\n writeFileSync(resolve(targetDir, \"intent.swift\"), ver.swift_output, \"utf-8\");\n filesWritten.push(\"intent.swift\");\n\n console.log(\n ` \\x1b[32m✓\\x1b[0m Installed ${data.template.full_name}@${ver.version}`\n );\n console.log(` → ${targetDir}/`);\n filesWritten.forEach((f) => console.log(` ${f}`));\n console.log();\n console.log(` \\x1b[1mNext:\\x1b[0m`);\n console.log(` axint compile ${options.to}/${slug}/intent.ts --out ios/Intents/`);\n console.log();\n } catch (err: unknown) {\n console.error(` \\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n process.exit(1);\n }\n });\n\n// ─── mcp ─────────────────────────────────────────────────────────────\n//\n// Starts the Axint MCP server over stdio so any MCP-capable client\n// (Claude Code, Claude Desktop, Cursor, Windsurf, Zed, etc.) can call\n// `axint.compile`, `axint.validate`, `axint.scaffold`, and the template\n// tools directly. The server implementation lives in src/mcp/server.ts\n// and is also exposed as the standalone `axint-mcp` bin; this\n// subcommand just routes through the same entry point so users can run\n// `npx -y @axintai/compiler mcp` without a second package install.\n\nprogram\n .command(\"mcp\")\n .description(\n \"Start the Axint MCP server (stdio) for Claude Code, Cursor, Windsurf, Zed, or any MCP client\"\n )\n .action(async () => {\n const { startMCPServer } = await import(\"../mcp/server.js\");\n await startMCPServer();\n });\n\n// Helper used by scaffold to avoid a circular import\nexport function __axintExistsSync(p: string) {\n return existsSync(p);\n}\n\nprogram.parse();\n","/**\n * Axint Eject Module\n *\n * Generates standalone Swift code that has no dependency on Axint.\n * This is useful for teams that want to verify there's no vendor lock-in\n * or for distributing intents without the compilation layer.\n *\n * The eject process:\n * 1. Compiles the TypeScript intent using the standard pipeline\n * 2. Transforms the output to remove Axint markers\n * 3. Optionally generates XCTest stubs\n * 4. Emits all files (Swift, plist, entitlements, test)\n */\n\nimport { compileSource } from \"./compiler.js\";\nimport type { IRIntent } from \"./types.js\";\n\n// ─── Public Interface ────────────────────────────────────────────────\n\nexport interface EjectOptions {\n /** Output directory for ejected files (defaults to \".\") */\n outDir?: string;\n /** Generate a basic XCTest file for the intent */\n includeTests?: boolean;\n /** Format output with swift-format (requires swift-format on PATH) */\n format?: boolean;\n}\n\nexport interface EjectResult {\n /** The primary Swift file */\n swiftFile: {\n path: string;\n content: string;\n };\n /** Optional Info.plist fragment */\n infoPlist?: {\n path: string;\n content: string;\n };\n /** Optional entitlements fragment */\n entitlements?: {\n path: string;\n content: string;\n };\n /** Optional XCTest file */\n testFile?: {\n path: string;\n content: string;\n };\n}\n\n// ─── Main Eject Function ────────────────────────────────────────────\n\n/**\n * Eject an intent from Axint, producing standalone Swift code with no\n * vendor lock-in. The resulting Swift code is production-ready and can\n * be committed directly to version control.\n *\n * @param source The TypeScript intent source\n * @param fileName Display name for diagnostics (e.g., \"intent.ts\")\n * @param options Eject options (outDir, includeTests, format)\n * @returns Ejected files\n */\nexport function ejectIntent(\n source: string,\n fileName: string,\n options: EjectOptions = {}\n): EjectResult {\n // 1. Compile using the standard pipeline\n const compileResult = compileSource(source, fileName, {\n validate: true,\n emitInfoPlist: true,\n emitEntitlements: true,\n });\n\n if (!compileResult.success || !compileResult.output) {\n throw new Error(\n `Compilation failed: ${compileResult.diagnostics\n .filter((d) => d.severity === \"error\")\n .map((d) => d.message)\n .join(\"; \")}`\n );\n }\n\n const { ir, swiftCode, infoPlistFragment, entitlementsFragment } =\n compileResult.output;\n const outDir = options.outDir ?? \".\";\n\n // 2. Transform Swift to remove Axint markers\n const ejectedSwift = transformSwiftForEject(swiftCode, ir);\n\n // 3. Construct file paths\n const intentFileName = `${ir.name}Intent.swift`;\n const swiftPath = `${outDir}/${intentFileName}`;\n const plistPath = infoPlistFragment\n ? `${outDir}/${ir.name}Intent.plist.fragment.xml`\n : null;\n const entitlementsPath = entitlementsFragment\n ? `${outDir}/${ir.name}Intent.entitlements.fragment.xml`\n : null;\n const testPath = options.includeTests\n ? `${outDir}/${ir.name}IntentTests.swift`\n : null;\n\n // 4. Build result object\n const result: EjectResult = {\n swiftFile: {\n path: swiftPath,\n content: ejectedSwift,\n },\n };\n\n if (infoPlistFragment && plistPath) {\n result.infoPlist = {\n path: plistPath,\n content: infoPlistFragment,\n };\n }\n\n if (entitlementsFragment && entitlementsPath) {\n result.entitlements = {\n path: entitlementsPath,\n content: entitlementsFragment,\n };\n }\n\n if (options.includeTests && testPath) {\n result.testFile = {\n path: testPath,\n content: generateTestFile(ir),\n };\n }\n\n return result;\n}\n\n// ─── Swift Transformation ───────────────────────────────────────────\n\n/**\n * Transform generated Swift code to be \"ejected\" — remove Axint markers,\n * update the header comment, and enhance the TODO placeholder.\n */\nfunction transformSwiftForEject(swiftCode: string, ir: IRIntent): string {\n const lines = swiftCode.split(\"\\n\");\n const result: string[] = [];\n\n let inHeader = true;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Replace header comment\n if (inHeader && line.startsWith(\"// \")) {\n if (i === 0) {\n // First line: replace with intent name\n result.push(`// ${ir.name}Intent.swift`);\n } else if (line.includes(\"Generated by Axint\")) {\n // Skip the Axint header\n result.push(\n `// Originally generated by Axint (https://github.com/agenticempire/axint)`\n );\n } else if (line.includes(\"Do not edit manually\")) {\n // Skip the regeneration instruction\n } else {\n result.push(line);\n }\n } else if (line === \"\") {\n inHeader = false;\n result.push(line);\n } else {\n inHeader = false;\n\n // Replace the TODO comment with a more helpful one\n if (line.includes(\"// TODO: Implement your intent logic here.\")) {\n result.push(` // TODO: Implement your intent logic here.`);\n result.push(` //`);\n result.push(\n ` // For more information about App Intents, see:`\n );\n result.push(\n ` // https://developer.apple.com/documentation/appintents`\n );\n } else {\n result.push(line);\n }\n }\n }\n\n return result.join(\"\\n\");\n}\n\n// ─── Test File Generation ───────────────────────────────────────────\n\n/**\n * Generate a basic XCTest file for the intent.\n * This provides a scaffold that users can fill in with their own tests.\n */\nfunction generateTestFile(ir: IRIntent): string {\n const lines: string[] = [];\n\n lines.push(`// ${ir.name}IntentTests.swift`);\n lines.push(`// Ejected from Axint`);\n lines.push(``);\n lines.push(`import XCTest`);\n lines.push(`import AppIntents`);\n lines.push(``);\n lines.push(`final class ${ir.name}IntentTests: XCTestCase {`);\n lines.push(``);\n lines.push(` func testIntentInitialization() throws {`);\n lines.push(` let intent = ${ir.name}Intent()`);\n lines.push(` XCTAssertEqual(${ir.name}Intent.title.stringValue, \"${ir.title}\")`);\n lines.push(` }`);\n lines.push(``);\n lines.push(` func testIntentPerform() async throws {`);\n lines.push(` let intent = ${ir.name}Intent()`);\n lines.push(` // TODO: Set up intent parameters and test perform()`);\n lines.push(` // let result = try await intent.perform()`);\n lines.push(` // XCTAssertNotNil(result)`);\n lines.push(` }`);\n lines.push(``);\n lines.push(`}`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n","/**\n * Project scaffolder — `axint init`\n *\n * Zero-config project creation. Drops a working Axint project on disk:\n *\n * my-app/\n * ├── package.json — pinned to the current Axint version\n * ├── tsconfig.json — strict, ES2022, module NodeNext\n * ├── .gitignore\n * ├── README.md — next-steps guide\n * ├── intents/\n * │ └── <template>.ts — starter intent from the template library\n * ├── ios/\n * │ └── Intents/ — compile output target (created on first run)\n * └── .vscode/\n * └── mcp.json — ready-to-use MCP server config for Cursor/Copilot\n *\n * The scaffolder is deliberately dependency-free at runtime — everything is\n * written with `fs/promises`. It is safe to call against an existing directory\n * as long as that directory is empty (or only contains a .git folder).\n */\n\nimport { mkdir, writeFile, readdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { getTemplate } from \"../templates/index.js\";\n\nexport interface ScaffoldOptions {\n targetDir: string;\n projectName: string;\n template: string;\n version: string;\n install: boolean;\n}\n\nexport interface ScaffoldResult {\n files: string[];\n entryFile: string;\n}\n\nexport async function scaffoldProject(opts: ScaffoldOptions): Promise<ScaffoldResult> {\n const { targetDir, projectName, template, version, install } = opts;\n\n // 1. Resolve template\n const tpl = getTemplate(template);\n if (!tpl) {\n throw new Error(\n `Unknown template \"${template}\". Run \\`axint templates\\` to see available templates.`\n );\n }\n\n // 2. Safety check — refuse to overwrite a populated directory\n if (existsSync(targetDir)) {\n const entries = await readdir(targetDir).catch(() => []);\n const populated = entries.filter((e) => !e.startsWith(\".git\") && e !== \".DS_Store\");\n if (populated.length > 0) {\n throw new Error(\n `Directory \"${targetDir}\" is not empty. Pick an empty folder or use \\`axint init my-new-app\\`.`\n );\n }\n } else {\n await mkdir(targetDir, { recursive: true });\n }\n\n const files: string[] = [];\n const write = async (rel: string, content: string) => {\n const abs = join(targetDir, rel);\n await mkdir(join(abs, \"..\").replace(/[/\\\\][^/\\\\]+$/, \"\"), { recursive: true }).catch(\n () => undefined\n );\n // Ensure parent dir exists using a more reliable approach\n const parent = abs.substring(\n 0,\n abs.lastIndexOf(\"/\") === -1 ? abs.lastIndexOf(\"\\\\\") : abs.lastIndexOf(\"/\")\n );\n if (parent && parent !== abs) {\n await mkdir(parent, { recursive: true }).catch(() => undefined);\n }\n await writeFile(abs, content, \"utf-8\");\n files.push(relative(targetDir, abs));\n };\n\n // 3. package.json\n await write(\n \"package.json\",\n JSON.stringify(\n {\n name: projectName,\n version: \"0.0.1\",\n private: true,\n type: \"module\",\n scripts: {\n compile: `axint compile intents/${template}.ts --out ios/Intents/`,\n \"compile:plist\": `axint compile intents/${template}.ts --out ios/Intents/ --emit-info-plist --emit-entitlements`,\n validate: `axint validate intents/${template}.ts`,\n sandbox: `axint validate intents/${template}.ts --sandbox`,\n },\n dependencies: {\n \"@axintai/compiler\": `^${version}`,\n },\n },\n null,\n 2\n ) + \"\\n\"\n );\n\n // 4. tsconfig.json\n await write(\n \"tsconfig.json\",\n JSON.stringify(\n {\n compilerOptions: {\n target: \"ES2022\",\n module: \"NodeNext\",\n moduleResolution: \"NodeNext\",\n strict: true,\n esModuleInterop: true,\n skipLibCheck: true,\n noEmit: true,\n isolatedModules: true,\n verbatimModuleSyntax: false,\n resolveJsonModule: true,\n },\n include: [\"intents/**/*.ts\"],\n },\n null,\n 2\n ) + \"\\n\"\n );\n\n // 5. .gitignore\n await write(\n \".gitignore\",\n [\"node_modules\", \"dist\", \".DS_Store\", \".axint-sandbox\", \"*.log\", \"\"].join(\"\\n\")\n );\n\n // 6. The starter intent itself — pulled straight from the template library.\n // Templates already use `@axintai/compiler` which resolves against the\n // scaffolded dependency.\n await write(`intents/${template}.ts`, tpl.source);\n\n // 7. .vscode/mcp.json — ready to `npx axint-mcp` from Cursor/Claude Code\n await write(\n \".vscode/mcp.json\",\n JSON.stringify(\n {\n mcpServers: {\n axint: {\n command: \"npx\",\n args: [\"-y\", \"@axintai/compiler\", \"axint-mcp\"],\n },\n },\n },\n null,\n 2\n ) + \"\\n\"\n );\n\n // 8. Project README\n await write(\"README.md\", scaffoldReadme(projectName, template, tpl.title, version));\n\n // 9. ios/Intents — create target dir so `compile` has somewhere to land\n await mkdir(join(targetDir, \"ios\", \"Intents\"), { recursive: true });\n await write(\"ios/Intents/.gitkeep\", \"\");\n\n // 10. Optional npm install\n if (install) {\n await runNpmInstall(targetDir);\n }\n\n return {\n files,\n entryFile: `${template}.ts`,\n };\n}\n\nfunction scaffoldReadme(\n name: string,\n template: string,\n title: string,\n version: string\n): string {\n return `# ${name}\n\nAn [Axint](https://axint.ai) project — write App Intents in TypeScript, ship them to Siri.\n\nGenerated from the **${title}** template, pinned to \\`@axintai/compiler@^${version}\\`.\n\n## Compile it\n\n\\`\\`\\`bash\nnpm install\nnpm run compile\n\\`\\`\\`\n\nOutput lands in \\`ios/Intents/\\`. Drag that folder into your Xcode target and you're done.\n\n## Validate it\n\n\\`\\`\\`bash\nnpm run validate # fast IR + Swift lint\nnpm run sandbox # stage 4: swift build in an SPM sandbox (macOS only)\n\\`\\`\\`\n\n## Use with AI coding tools\n\nThe \\`.vscode/mcp.json\\` file is pre-wired for Cursor, Claude Code, and Windsurf.\nAny agent that supports MCP can now call \\`axint_compile\\`, \\`axint_validate\\`,\n\\`axint_scaffold\\`, and \\`axint_template\\` against this project.\n\n## Next\n\n- Edit \\`intents/${template}.ts\\` — this is your App Intent source of truth.\n- Add more intents in the \\`intents/\\` folder.\n- Run \\`axint templates\\` to see every bundled starter.\n- Read the docs at https://axint.ai/docs\n\n---\n\n_Generated by \\`axint init\\`_\n`;\n}\n\nfunction runNpmInstall(cwd: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"npm\", [\"install\"], { cwd, stdio: \"inherit\" });\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`npm install exited with code ${code}`));\n });\n child.on(\"error\", reject);\n });\n}\n"],"mappings":";;;;;;;;;;;;AA6KO,SAAS,cAAc,MAAsB;AAClD,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,eAAe,KAAK,KAAK;AAAA,IAClC,KAAK;AACH,aAAO,IAAI,cAAc,KAAK,WAAW,CAAC;AAAA,IAC5C,KAAK;AACH,aAAO,GAAG,cAAc,KAAK,SAAS,CAAC;AAAA,IACzC,KAAK;AACH,aAAO,KAAK;AAAA,IACd,KAAK;AACH,aAAO,GAAG,KAAK,UAAU;AAAA,IAC3B,KAAK;AACH,aAAO,yBAAyB,cAAc,KAAK,SAAS,CAAC;AAAA,IAC/D,KAAK;AACH,aAAO,KAAK;AAAA,EAChB;AACF;AA9LA,IA0Ia,aAeA,sBAMA;AA/Jb;AAAA;A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AAM,2BAA4B,IAAc,WAAW,GAAG,EAAE;AACxE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAYH,QACG,QAAQ,KAAK,EACb;AAAA,EACC;AACF,EACC,OAAO,YAAY;AAClB,QAAM,EAAE,gBAAAM,gBAAe,IAAI,MAAM;AACjC,QAAMA,gBAAe;AACvB,CAAC;AAGI,SAAS,kBAAkB,GAAW;AAC3C,SAAOD,YAAW,CAAC;AACrB;AAEA,QAAQ,MAAM;","names":["spawn","writeFile","join","resolve","mkdir","writeFile","existsSync","join","tmpdir","spawn","resolve","toPascalCase","readFileSync","readFileSync","existsSync","resolve","dirname","fileURLToPath","resolve","__dirname","dirname","fileURLToPath","pkg","readFileSync","resolve","formatSwift","sandboxCompile","join","spawn","existsSync","startMCPServer"]}
1
+ {"version":3,"sources":["../../src/core/types.ts","../../src/core/parser.ts","../../src/core/generator.ts","../../src/core/validator.ts","../../src/core/compiler.ts","../../src/core/format.ts","../../src/templates/index.ts","../../src/core/sandbox.ts","../../src/mcp/scaffold.ts","../../src/mcp/server.ts","../../src/cli/index.ts","../../src/core/eject.ts","../../src/cli/scaffold.ts"],"sourcesContent":["/**\n * Axint Core Types\n *\n * Intermediate Representation (IR) and compiler types for the\n * TypeScript → Swift App Intent compilation pipeline.\n */\n\n// ─── IR Types ────────────────────────────────────────────────────────\n\n/** Primitive types supported by App Intents */\nexport type IRPrimitiveType =\n | \"string\"\n | \"int\"\n | \"double\"\n | \"float\"\n | \"boolean\"\n | \"date\"\n | \"duration\"\n | \"url\";\n\n/** Type node in the IR */\nexport type IRType =\n | { kind: \"primitive\"; value: IRPrimitiveType }\n | { kind: \"array\"; elementType: IRType }\n | { kind: \"optional\"; innerType: IRType }\n | { kind: \"entity\"; entityName: string; properties: IRParameter[] }\n | { kind: \"entityQuery\"; entityName: string; queryType: \"all\" | \"id\" | \"string\" | \"property\" }\n | { kind: \"dynamicOptions\"; valueType: IRType; providerName: string }\n | { kind: \"enum\"; name: string; cases: string[] };\n\n/** A single parameter in an intent definition */\nexport interface IRParameter {\n name: string;\n type: IRType;\n title: string;\n description: string;\n isOptional: boolean;\n defaultValue?: unknown;\n}\n\n/**\n * Display representation configuration for an entity.\n * Maps which properties to show in Siri and Shortcuts UI.\n */\nexport interface DisplayRepresentation {\n title: string;\n subtitle?: string;\n image?: string;\n}\n\n/**\n * An App Entity definition for complex, domain-specific data types.\n * Entities can be queried and used as parameter types in intents.\n */\nexport interface IREntity {\n name: string;\n displayRepresentation: DisplayRepresentation;\n properties: IRParameter[];\n queryType: \"all\" | \"id\" | \"string\" | \"property\";\n}\n\n/** The main IR node representing a compiled intent */\nexport interface IRIntent {\n name: string;\n title: string;\n description: string;\n domain?: string;\n category?: string;\n parameters: IRParameter[];\n returnType: IRType;\n sourceFile: string;\n /** Entitlements required by this intent (e.g., \"com.apple.developer.siri\") */\n entitlements?: string[];\n /** Info.plist keys required by this intent (e.g., \"NSCalendarsUsageDescription\") */\n infoPlistKeys?: Record<string, string>;\n /** Whether the intent should be exposed to Spotlight indexing */\n isDiscoverable?: boolean;\n /** App Entities used by this intent */\n entities?: IREntity[];\n /** Whether to donate this intent to Spotlight/Siri when performed */\n donateOnPerform?: boolean;\n /** Custom result type (SwiftUI view or custom struct) to return */\n customResultType?: string;\n}\n\n// ─── Compiler Types ──────────────────────────────────────────────────\n\nexport interface CompilerOptions {\n /** Output directory for generated Swift files */\n outDir: string;\n /** Whether to run validation after generation */\n validate?: boolean;\n /** Target iOS/macOS version */\n target?: \"ios16\" | \"ios17\" | \"ios18\" | \"ios26\" | \"macos13\" | \"macos14\" | \"macos15\" | \"macos26\";\n /** Whether to emit an Info.plist fragment alongside the Swift file */\n emitInfoPlist?: boolean;\n /** Whether to emit an entitlements fragment alongside the Swift file */\n emitEntitlements?: boolean;\n /** Whether to run swift-format on the output (requires swift-format on PATH) */\n format?: boolean;\n}\n\nexport interface CompilerOutput {\n /** Path to the generated Swift file */\n outputPath: string;\n /** The generated Swift source code */\n swiftCode: string;\n /** Info.plist fragment (if emitInfoPlist is true) */\n infoPlistFragment?: string;\n /** Entitlements fragment (if emitEntitlements is true) */\n entitlementsFragment?: string;\n /** The intermediate representation */\n ir: IRIntent;\n /** Validation diagnostics */\n diagnostics: Diagnostic[];\n}\n\n// ─── Diagnostics ─────────────────────────────────────────────────────\n\nexport type DiagnosticSeverity = \"error\" | \"warning\" | \"info\";\n\nexport interface Diagnostic {\n code: string;\n severity: DiagnosticSeverity;\n message: string;\n file?: string;\n line?: number;\n column?: number;\n suggestion?: string;\n}\n\n// ─── Param Type Registry ─────────────────────────────────────────────\n\n/**\n * Canonical set of supported param types.\n * Single source of truth — parser, SDK, and docs all derive from this.\n * To add a new type: add it to IRPrimitiveType, PARAM_TYPES, and SWIFT_TYPE_MAP.\n */\nexport const PARAM_TYPES: ReadonlySet<IRPrimitiveType> = new Set<IRPrimitiveType>([\n \"string\",\n \"int\",\n \"double\",\n \"float\",\n \"boolean\",\n \"date\",\n \"duration\",\n \"url\",\n]);\n\n/**\n * Legacy alias: \"number\" → \"int\" for backwards compatibility with v0.1.x files.\n * Parser will accept \"number\" and rewrite it to \"int\" with a deprecation warning.\n */\nexport const LEGACY_PARAM_ALIASES: Record<string, IRPrimitiveType> = {\n number: \"int\",\n};\n\n// ─── Swift Type Mapping ──────────────────────────────────────────────\n\nexport const SWIFT_TYPE_MAP: Record<IRPrimitiveType, string> = {\n string: \"String\",\n int: \"Int\",\n double: \"Double\",\n float: \"Float\",\n boolean: \"Bool\",\n date: \"Date\",\n duration: \"Measurement<UnitDuration>\",\n url: \"URL\",\n};\n\n/**\n * Convert an IRType to its Swift type string.\n */\nexport function irTypeToSwift(type: IRType): string {\n switch (type.kind) {\n case \"primitive\":\n return SWIFT_TYPE_MAP[type.value];\n case \"array\":\n return `[${irTypeToSwift(type.elementType)}]`;\n case \"optional\":\n return `${irTypeToSwift(type.innerType)}?`;\n case \"entity\":\n return type.entityName;\n case \"entityQuery\":\n return `${type.entityName}Query`;\n case \"dynamicOptions\":\n return `[DynamicOptionsResult<${irTypeToSwift(type.valueType)}>]`;\n case \"enum\":\n return type.name;\n }\n}\n","/**\n * Axint Parser\n *\n * Parses TypeScript intent definitions (using the defineIntent() API)\n * into the Axint Intermediate Representation (IR).\n *\n * Approach: Real TypeScript compiler API AST walker. We create a\n * SourceFile, find defineIntent() CallExpressions, and extract the\n * ObjectLiteralExpression properties using the actual TS AST.\n *\n * The previous v0.1.x parser used regex matching. That approach was\n * replaced in v0.2.0 to support enums, arrays, entities, and accurate\n * return-type inference.\n */\n\nimport ts from \"typescript\";\nimport type {\n IRIntent,\n IRParameter,\n IRType,\n IRPrimitiveType,\n IREntity,\n DisplayRepresentation,\n} from \"./types.js\";\nimport { PARAM_TYPES, LEGACY_PARAM_ALIASES } from \"./types.js\";\n\n/**\n * Parse a TypeScript source file containing defineIntent() and/or\n * defineEntity() calls and return the IR representation.\n */\nexport function parseIntentSource(\n source: string,\n filePath: string = \"<stdin>\"\n): IRIntent {\n const sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.Latest,\n true, // setParentNodes\n ts.ScriptKind.TS\n );\n\n // Parse all entity definitions first, so they can be referenced by intents\n const entities = findDefineEntityCalls(sourceFile).map((call) =>\n parseEntityDefinition(call, filePath, sourceFile)\n );\n\n const defineIntentCall = findDefineIntentCall(sourceFile);\n if (!defineIntentCall) {\n throw new ParserError(\n \"AX001\",\n `No defineIntent() call found in ${filePath}`,\n filePath,\n undefined,\n \"Ensure your file contains a `defineIntent({ ... })` call.\"\n );\n }\n\n const arg = defineIntentCall.arguments[0];\n if (!arg || !ts.isObjectLiteralExpression(arg)) {\n throw new ParserError(\n \"AX001\",\n \"defineIntent() must be called with an object literal\",\n filePath,\n posOf(sourceFile, defineIntentCall),\n \"Pass an object: defineIntent({ name, title, description, params, perform })\"\n );\n }\n\n const props = propertyMap(arg);\n\n const name = readStringLiteral(props.get(\"name\"));\n const title = readStringLiteral(props.get(\"title\"));\n const description = readStringLiteral(props.get(\"description\"));\n const domain = readStringLiteral(props.get(\"domain\"));\n const category = readStringLiteral(props.get(\"category\"));\n const isDiscoverable = readBooleanLiteral(props.get(\"isDiscoverable\"));\n\n if (!name) {\n throw new ParserError(\n \"AX002\",\n \"Missing required field: name\",\n filePath,\n posOf(sourceFile, arg),\n 'Add a name field: name: \"MyIntent\"'\n );\n }\n if (!title) {\n throw new ParserError(\n \"AX003\",\n \"Missing required field: title\",\n filePath,\n posOf(sourceFile, arg),\n 'Add a title field: title: \"My Intent Title\"'\n );\n }\n if (!description) {\n throw new ParserError(\n \"AX004\",\n \"Missing required field: description\",\n filePath,\n posOf(sourceFile, arg),\n 'Add a description field: description: \"What this intent does\"'\n );\n }\n\n const paramsNode = props.get(\"params\");\n const parameters: IRParameter[] = paramsNode\n ? extractParameters(paramsNode, filePath, sourceFile)\n : [];\n\n // Return-type inference from the perform() function signature.\n const performNode = props.get(\"perform\");\n const returnType = inferReturnType(performNode);\n\n // Entitlements (optional array of strings)\n const entitlementsNode = props.get(\"entitlements\");\n const entitlements = readStringArray(entitlementsNode);\n\n // Info.plist keys (optional object literal of { key: \"description\" })\n const infoPlistNode = props.get(\"infoPlistKeys\");\n const infoPlistKeys = readStringRecord(infoPlistNode);\n\n // Intent donation (optional boolean)\n const donateOnPerformNode = props.get(\"donateOnPerform\");\n const donateOnPerform = readBooleanLiteral(donateOnPerformNode);\n\n // Custom result type (optional string)\n const customResultTypeNode = props.get(\"customResultType\");\n const customResultType = readStringLiteral(customResultTypeNode);\n\n return {\n name,\n title,\n description,\n domain: domain || undefined,\n category: category || undefined,\n parameters,\n returnType,\n sourceFile: filePath,\n entitlements: entitlements.length > 0 ? entitlements : undefined,\n infoPlistKeys:\n Object.keys(infoPlistKeys).length > 0 ? infoPlistKeys : undefined,\n isDiscoverable: isDiscoverable ?? undefined,\n entities: entities.length > 0 ? entities : undefined,\n donateOnPerform: donateOnPerform ?? undefined,\n customResultType: customResultType ?? undefined,\n };\n}\n\n// ─── AST Walkers ─────────────────────────────────────────────────────\n\n/**\n * Find the first defineIntent() call in the AST.\n */\nfunction findDefineIntentCall(\n node: ts.Node\n): ts.CallExpression | undefined {\n let found: ts.CallExpression | undefined;\n const visit = (n: ts.Node): void => {\n if (found) return;\n if (\n ts.isCallExpression(n) &&\n ts.isIdentifier(n.expression) &&\n n.expression.text === \"defineIntent\"\n ) {\n found = n;\n return;\n }\n ts.forEachChild(n, visit);\n };\n visit(node);\n return found;\n}\n\n/**\n * Find all defineEntity() calls in the AST.\n */\nfunction findDefineEntityCalls(node: ts.Node): ts.CallExpression[] {\n const found: ts.CallExpression[] = [];\n const visit = (n: ts.Node): void => {\n if (\n ts.isCallExpression(n) &&\n ts.isIdentifier(n.expression) &&\n n.expression.text === \"defineEntity\"\n ) {\n found.push(n);\n return;\n }\n ts.forEachChild(n, visit);\n };\n visit(node);\n return found;\n}\n\nfunction propertyMap(\n obj: ts.ObjectLiteralExpression\n): Map<string, ts.Expression> {\n const map = new Map<string, ts.Expression>();\n for (const prop of obj.properties) {\n if (ts.isPropertyAssignment(prop)) {\n const key = propertyKeyName(prop.name);\n if (key) map.set(key, prop.initializer);\n } else if (ts.isShorthandPropertyAssignment(prop)) {\n map.set(prop.name.text, prop.name);\n } else if (ts.isMethodDeclaration(prop)) {\n const key = propertyKeyName(prop.name);\n if (key) map.set(key, prop as unknown as ts.Expression);\n }\n }\n return map;\n}\n\nfunction propertyKeyName(name: ts.PropertyName): string | undefined {\n if (ts.isIdentifier(name)) return name.text;\n if (ts.isStringLiteral(name)) return name.text;\n if (ts.isNumericLiteral(name)) return name.text;\n return undefined;\n}\n\nfunction readStringLiteral(node: ts.Expression | undefined): string | null {\n if (!node) return null;\n if (ts.isStringLiteral(node)) return node.text;\n if (ts.isNoSubstitutionTemplateLiteral(node)) return node.text;\n return null;\n}\n\nfunction readBooleanLiteral(\n node: ts.Expression | undefined\n): boolean | undefined {\n if (!node) return undefined;\n if (node.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (node.kind === ts.SyntaxKind.FalseKeyword) return false;\n return undefined;\n}\n\nfunction readStringArray(node: ts.Expression | undefined): string[] {\n if (!node || !ts.isArrayLiteralExpression(node)) return [];\n const out: string[] = [];\n for (const el of node.elements) {\n const s = readStringLiteral(el);\n if (s !== null) out.push(s);\n }\n return out;\n}\n\nfunction readStringRecord(\n node: ts.Expression | undefined\n): Record<string, string> {\n if (!node || !ts.isObjectLiteralExpression(node)) return {};\n const rec: Record<string, string> = {};\n for (const prop of node.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const key = propertyKeyName(prop.name);\n const val = readStringLiteral(prop.initializer);\n if (key && val !== null) rec[key] = val;\n }\n return rec;\n}\n\n// ─── Entity Definition Parsing ───────────────────────────────────────\n\n/**\n * Parse a defineEntity() call into an IREntity.\n */\nfunction parseEntityDefinition(\n call: ts.CallExpression,\n filePath: string,\n sourceFile: ts.SourceFile\n): IREntity {\n const arg = call.arguments[0];\n if (!arg || !ts.isObjectLiteralExpression(arg)) {\n throw new ParserError(\n \"AX015\",\n \"defineEntity() must be called with an object literal\",\n filePath,\n posOf(sourceFile, call),\n \"Pass an object: defineEntity({ name, display, properties, query })\"\n );\n }\n\n const props = propertyMap(arg);\n\n const name = readStringLiteral(props.get(\"name\"));\n if (!name) {\n throw new ParserError(\n \"AX016\",\n \"Entity definition missing required field: name\",\n filePath,\n posOf(sourceFile, arg),\n 'Add a name field: name: \"Task\"'\n );\n }\n\n const displayNode = props.get(\"display\");\n if (!displayNode || !ts.isObjectLiteralExpression(displayNode)) {\n throw new ParserError(\n \"AX017\",\n \"Entity definition missing required field: display\",\n filePath,\n posOf(sourceFile, arg),\n 'Add display field: display: { title: \"name\", subtitle: \"status\" }'\n );\n }\n\n const displayProps = propertyMap(displayNode);\n const displayRepresentation: DisplayRepresentation = {\n title: readStringLiteral(displayProps.get(\"title\")) || \"name\",\n subtitle: readStringLiteral(displayProps.get(\"subtitle\")) || undefined,\n image: readStringLiteral(displayProps.get(\"image\")) || undefined,\n };\n\n const propertiesNode = props.get(\"properties\");\n const properties = propertiesNode\n ? extractParameters(propertiesNode, filePath, sourceFile)\n : [];\n\n const queryTypeNode = props.get(\"query\");\n const queryTypeStr = readStringLiteral(queryTypeNode);\n const queryType = validateQueryType(queryTypeStr, filePath, sourceFile, queryTypeNode);\n\n return {\n name,\n displayRepresentation,\n properties,\n queryType,\n };\n}\n\n/**\n * Validate and normalize query type string.\n */\nfunction validateQueryType(\n value: string | null,\n filePath: string,\n sourceFile: ts.SourceFile,\n node: ts.Expression | undefined\n): \"all\" | \"id\" | \"string\" | \"property\" {\n if (!value) {\n throw new ParserError(\n \"AX018\",\n \"Entity definition missing required field: query\",\n filePath,\n node ? posOf(sourceFile, node) : undefined,\n 'Add query field: query: \"string\" (or \"all\", \"id\", \"property\")'\n );\n }\n const valid = [\"all\", \"id\", \"string\", \"property\"] as const;\n if (!valid.includes(value as any)) {\n throw new ParserError(\n \"AX019\",\n `Invalid query type: \"${value}\". Must be one of: all, id, string, property`,\n filePath,\n node ? posOf(sourceFile, node) : undefined\n );\n }\n return value as \"all\" | \"id\" | \"string\" | \"property\";\n}\n\n// ─── Parameter Extraction ────────────────────────────────────────────\n\nfunction extractParameters(\n node: ts.Expression,\n filePath: string,\n sourceFile: ts.SourceFile\n): IRParameter[] {\n if (!ts.isObjectLiteralExpression(node)) {\n throw new ParserError(\n \"AX006\",\n \"`params` must be an object literal\",\n filePath,\n posOf(sourceFile, node),\n \"Use params: { name: param.string(...), ... }\"\n );\n }\n\n const params: IRParameter[] = [];\n for (const prop of node.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const paramName = propertyKeyName(prop.name);\n if (!paramName) continue;\n\n const { typeName, description, configObject, callExpr } = extractParamCall(\n prop.initializer,\n filePath,\n sourceFile\n );\n\n const resolvedType = resolveParamType(typeName, filePath, sourceFile, prop, callExpr);\n\n const isOptional = configObject\n ? readBooleanLiteral(configObject.get(\"required\")) === false\n : false;\n\n const defaultExpr = configObject?.get(\"default\");\n const defaultValue = defaultExpr ? evaluateLiteral(defaultExpr) : undefined;\n\n const titleFromConfig = configObject\n ? readStringLiteral(configObject.get(\"title\"))\n : null;\n\n const irType: IRType = isOptional\n ? {\n kind: \"optional\",\n innerType: resolvedType,\n }\n : resolvedType;\n\n params.push({\n name: paramName,\n type: irType,\n title: titleFromConfig || prettyTitle(paramName),\n description,\n isOptional,\n defaultValue,\n });\n }\n\n return params;\n}\n\ninterface ParamCallInfo {\n typeName: string;\n description: string;\n configObject: Map<string, ts.Expression> | null;\n callExpr: ts.CallExpression;\n}\n\n/**\n * Extract param type, description, and config from a param.* call.\n * For param.entity() and param.dynamicOptions(), the structure is different.\n */\nfunction extractParamCall(\n expr: ts.Expression,\n filePath: string,\n sourceFile: ts.SourceFile\n): ParamCallInfo {\n if (!ts.isCallExpression(expr)) {\n throw new ParserError(\n \"AX007\",\n \"Parameter value must be a call to a param.* helper\",\n filePath,\n posOf(sourceFile, expr),\n \"Use param.string(...), param.int(...), param.date(...), etc.\"\n );\n }\n\n // Expect: param.<type>(description?, config?)\n if (\n !ts.isPropertyAccessExpression(expr.expression) ||\n !ts.isIdentifier(expr.expression.expression) ||\n expr.expression.expression.text !== \"param\"\n ) {\n throw new ParserError(\n \"AX007\",\n \"Parameter value must be a call to a param.* helper\",\n filePath,\n posOf(sourceFile, expr),\n \"Use param.string(...), param.int(...), param.date(...), etc.\"\n );\n }\n\n const typeName = expr.expression.name.text;\n\n // For entity and dynamicOptions, the structure differs:\n // - param.entity(\"EntityName\", \"description\", config?)\n // - param.dynamicOptions(\"Provider\", param.string(...), \"description\", config?)\n let descriptionArg: ts.Expression | undefined;\n let configArg: ts.Expression | undefined;\n\n if (typeName === \"entity\" && expr.arguments.length >= 2) {\n descriptionArg = expr.arguments[1];\n configArg = expr.arguments[2];\n } else if (typeName === \"dynamicOptions\" && expr.arguments.length >= 3) {\n descriptionArg = expr.arguments[2];\n configArg = expr.arguments[3];\n } else {\n descriptionArg = expr.arguments[0];\n configArg = expr.arguments[1];\n }\n\n const description = descriptionArg ? readStringLiteral(descriptionArg) : null;\n if (description === null) {\n throw new ParserError(\n \"AX008\",\n `param.${typeName}() requires a string description`,\n filePath,\n posOf(sourceFile, expr),\n `Example: param.${typeName}(\"Human-readable description\")`\n );\n }\n\n const configObject =\n configArg && ts.isObjectLiteralExpression(configArg)\n ? propertyMap(configArg)\n : null;\n\n return { typeName, description, configObject, callExpr: expr };\n}\n\n/**\n * Resolve a param type name into an IRType.\n * Supports primitives, entity references, and dynamic options.\n */\nfunction resolveParamType(\n typeName: string,\n filePath: string,\n sourceFile: ts.SourceFile,\n node: ts.Node,\n callExpr?: ts.CallExpression\n): IRType {\n // Primitive types\n if (PARAM_TYPES.has(typeName as IRPrimitiveType)) {\n return { kind: \"primitive\", value: typeName as IRPrimitiveType };\n }\n\n // Legacy aliases\n if (typeName in LEGACY_PARAM_ALIASES) {\n return {\n kind: \"primitive\",\n value: LEGACY_PARAM_ALIASES[typeName],\n };\n }\n\n // Entity types: param.entity(\"EntityName\")\n if (typeName === \"entity\") {\n if (!callExpr || callExpr.arguments.length === 0) {\n throw new ParserError(\n \"AX020\",\n \"param.entity() requires the entity name as the first argument\",\n filePath,\n posOf(sourceFile, node),\n 'Example: param.entity(\"Task\", \"Reference an entity\")'\n );\n }\n const entityName = readStringLiteral(callExpr.arguments[0]);\n if (!entityName) {\n throw new ParserError(\n \"AX021\",\n \"param.entity() requires a string entity name\",\n filePath,\n posOf(sourceFile, node)\n );\n }\n return {\n kind: \"entity\",\n entityName,\n properties: [],\n };\n }\n\n // Dynamic options: param.dynamicOptions(\"ProviderName\", innerType)\n if (typeName === \"dynamicOptions\") {\n if (!callExpr || callExpr.arguments.length < 2) {\n throw new ParserError(\n \"AX022\",\n \"param.dynamicOptions() requires (providerName, paramType)\",\n filePath,\n posOf(sourceFile, node),\n 'Example: param.dynamicOptions(\"PlaylistProvider\", param.string(...))'\n );\n }\n const providerName = readStringLiteral(callExpr.arguments[0]);\n if (!providerName) {\n throw new ParserError(\n \"AX023\",\n \"param.dynamicOptions() provider name must be a string\",\n filePath,\n posOf(sourceFile, node)\n );\n }\n // TODO: Extract inner param type from the second argument\n const valueType: IRType = { kind: \"primitive\", value: \"string\" };\n return {\n kind: \"dynamicOptions\",\n valueType,\n providerName,\n };\n }\n\n throw new ParserError(\n \"AX005\",\n `Unknown param type: param.${typeName}`,\n filePath,\n posOf(sourceFile, node),\n `Supported types: ${[...PARAM_TYPES].join(\", \")}, entity, dynamicOptions`\n );\n}\n\n// ─── Literal Evaluation ──────────────────────────────────────────────\n\nfunction evaluateLiteral(node: ts.Expression): unknown {\n if (ts.isStringLiteral(node)) return node.text;\n if (ts.isNoSubstitutionTemplateLiteral(node)) return node.text;\n if (ts.isNumericLiteral(node)) return Number(node.text);\n if (node.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (node.kind === ts.SyntaxKind.FalseKeyword) return false;\n if (node.kind === ts.SyntaxKind.NullKeyword) return null;\n if (\n ts.isPrefixUnaryExpression(node) &&\n node.operator === ts.SyntaxKind.MinusToken &&\n ts.isNumericLiteral(node.operand)\n ) {\n return -Number(node.operand.text);\n }\n return undefined;\n}\n\n// ─── Return-Type Inference ───────────────────────────────────────────\n\nfunction inferReturnType(performNode: ts.Expression | undefined): IRType {\n // Default when we can't infer anything.\n const defaultType: IRType = { kind: \"primitive\", value: \"string\" };\n if (!performNode) return defaultType;\n\n // Handle method shorthand: perform() { ... }\n if (ts.isMethodDeclaration(performNode)) {\n return inferFromReturnStatements(performNode.body);\n }\n\n // Handle arrow function: perform: async () => { ... }\n if (ts.isArrowFunction(performNode)) {\n if (performNode.body && ts.isBlock(performNode.body)) {\n return inferFromReturnStatements(performNode.body);\n }\n // Single-expression arrow: perform: async (p) => \"literal\"\n return inferFromExpression(performNode.body as ts.Expression);\n }\n\n // Handle function expression: perform: async function() { ... }\n if (ts.isFunctionExpression(performNode)) {\n return inferFromReturnStatements(performNode.body);\n }\n\n return defaultType;\n}\n\nfunction inferFromReturnStatements(block: ts.Block | undefined): IRType {\n const defaultType: IRType = { kind: \"primitive\", value: \"string\" };\n if (!block) return defaultType;\n\n let inferred: IRType | undefined;\n const visit = (n: ts.Node): void => {\n if (inferred) return;\n if (ts.isReturnStatement(n) && n.expression) {\n inferred = inferFromExpression(n.expression);\n return;\n }\n // Don't walk into nested functions — only the top-level perform() body.\n if (\n ts.isFunctionDeclaration(n) ||\n ts.isFunctionExpression(n) ||\n ts.isArrowFunction(n)\n ) {\n return;\n }\n ts.forEachChild(n, visit);\n };\n visit(block);\n return inferred ?? defaultType;\n}\n\nfunction inferFromExpression(expr: ts.Expression): IRType {\n if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) {\n return { kind: \"primitive\", value: \"string\" };\n }\n if (ts.isNumericLiteral(expr)) {\n return expr.text.includes(\".\")\n ? { kind: \"primitive\", value: \"double\" }\n : { kind: \"primitive\", value: \"int\" };\n }\n if (\n expr.kind === ts.SyntaxKind.TrueKeyword ||\n expr.kind === ts.SyntaxKind.FalseKeyword\n ) {\n return { kind: \"primitive\", value: \"boolean\" };\n }\n // Default fallback\n return { kind: \"primitive\", value: \"string\" };\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction prettyTitle(name: string): string {\n const spaced = name.replace(/([A-Z])/g, \" $1\").trim();\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n\nfunction posOf(\n sourceFile: ts.SourceFile,\n node: ts.Node\n): number | undefined {\n try {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n return line + 1;\n } catch {\n return undefined;\n }\n}\n\n// ─── Error Class ─────────────────────────────────────────────────────\n\nexport class ParserError extends Error {\n constructor(\n public code: string,\n message: string,\n public file: string,\n public line?: number,\n public suggestion?: string\n ) {\n super(message);\n this.name = \"ParserError\";\n }\n\n format(): string {\n let output = `\\n error[${this.code}]: ${this.message}\\n`;\n if (this.file) output += ` --> ${this.file}`;\n if (this.line) output += `:${this.line}`;\n output += \"\\n\";\n if (this.suggestion) {\n output += ` = help: ${this.suggestion}\\n`;\n }\n return output;\n }\n}\n","/**\n * Axint Swift Code Generator\n *\n * Transforms the IR into clean, idiomatic Swift App Intent source code.\n * Uses string templates for readability and maintainability.\n *\n * In addition to the primary Swift file, this module can emit two\n * companion fragments:\n * - an Info.plist XML fragment, listing the keys the intent requires\n * - an .entitlements XML fragment, listing the entitlements the\n * intent requires\n *\n * Both fragments are designed to be merged into the host Xcode project\n * by the user (or a future axint-link command).\n */\n\nimport type { IRIntent, IRParameter, IRType, IREntity } from \"./types.js\";\nimport { irTypeToSwift } from \"./types.js\";\n\n// ─── String Escaping ─────────────────────────────────────────────────\n\n/**\n * Escape a string for safe interpolation into Swift string literals.\n * Prevents code injection via user-controlled titles/descriptions.\n */\nexport function escapeSwiftString(s: string): string {\n return s\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\t/g, \"\\\\t\");\n}\n\n/**\n * Escape a string for safe interpolation into XML (Info.plist or\n * .entitlements). Plist XML uses the same rules as general XML.\n */\nexport function escapeXml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&apos;\");\n}\n\n// ─── Primary Swift Generator ─────────────────────────────────────────\n\n/**\n * Generate a Swift App Intent source file from an IR intent.\n * If entities are present, they are generated first, followed by the intent.\n */\nexport function generateSwift(intent: IRIntent): string {\n const lines: string[] = [];\n\n // File header\n lines.push(`// ${intent.name}Intent.swift`);\n lines.push(`// Generated by Axint — https://github.com/agenticempire/axint`);\n lines.push(`// Do not edit manually. Re-run \\`axint compile\\` to regenerate.`);\n lines.push(``);\n lines.push(`import AppIntents`);\n lines.push(`import Foundation`);\n lines.push(``);\n\n // Generate entities before the intent\n if (intent.entities && intent.entities.length > 0) {\n for (const entity of intent.entities) {\n lines.push(generateEntity(entity));\n lines.push(``);\n lines.push(generateEntityQuery(entity));\n lines.push(``);\n }\n }\n\n // Struct declaration\n lines.push(`struct ${intent.name}Intent: AppIntent {`);\n\n // Static metadata\n lines.push(\n ` static let title: LocalizedStringResource = \"${escapeSwiftString(intent.title)}\"`\n );\n lines.push(\n ` static let description: IntentDescription = IntentDescription(\"${escapeSwiftString(intent.description)}\")`\n );\n if (intent.isDiscoverable !== undefined) {\n lines.push(` static let isDiscoverable: Bool = ${intent.isDiscoverable}`);\n }\n lines.push(``);\n\n // Parameters\n for (const param of intent.parameters) {\n lines.push(generateParameter(param));\n }\n\n if (intent.parameters.length > 0) {\n lines.push(``);\n }\n\n // Perform function with return-type aware signature\n const returnTypeSignature = generateReturnSignature(\n intent.returnType,\n intent.customResultType\n );\n lines.push(` func perform() async throws -> ${returnTypeSignature} {`);\n lines.push(` // TODO: Implement your intent logic here.`);\n\n if (intent.parameters.length > 0) {\n const paramList = intent.parameters.map((p) => `\\\\(${p.name})`).join(\", \");\n lines.push(` // Parameters available: ${paramList}`);\n }\n\n // Add intent donation if enabled\n if (intent.donateOnPerform) {\n lines.push(` `);\n lines.push(` // Donate this intent to Siri and Spotlight`);\n lines.push(` try? await IntentDonationManager.shared.donate(intent: self)`);\n }\n\n lines.push(generatePerformReturn(intent.returnType, intent.customResultType));\n lines.push(` }`);\n lines.push(`}`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Entity Generation ───────────────────────────────────────────────\n\n/**\n * Generate an AppEntity struct from an IREntity definition.\n */\nexport function generateEntity(entity: IREntity): string {\n const lines: string[] = [];\n const propertyNames = new Set(entity.properties.map((p) => p.name));\n\n lines.push(`struct ${entity.name}: AppEntity {`);\n lines.push(` static var defaultQuery = ${entity.name}Query()`);\n lines.push(``);\n\n // Apple requires AppEntity to have an id property\n const hasId = propertyNames.has(\"id\");\n if (!hasId) {\n lines.push(` var id: String`);\n }\n\n // Properties\n for (const prop of entity.properties) {\n const swiftType = irTypeToSwift(prop.type);\n lines.push(` var ${prop.name}: ${swiftType}`);\n }\n\n lines.push(``);\n\n // Type display representation\n lines.push(\n ` static let typeDisplayRepresentation: TypeDisplayRepresentation = TypeDisplayRepresentation(`\n );\n lines.push(\n ` name: LocalizedStringResource(\"${escapeSwiftString(entity.name)}\")`\n );\n lines.push(` )`);\n lines.push(``);\n\n // Display representation computed property — title/subtitle are property\n // name references, so we emit Swift string interpolation \\(propName)\n lines.push(` var displayRepresentation: DisplayRepresentation {`);\n lines.push(` DisplayRepresentation(`);\n lines.push(\n ` title: \"\\\\(${entity.displayRepresentation.title})\"${entity.displayRepresentation.subtitle || entity.displayRepresentation.image ? \",\" : \"\"}`\n );\n if (entity.displayRepresentation.subtitle) {\n const hasImage = !!entity.displayRepresentation.image;\n lines.push(\n ` subtitle: \"\\\\(${entity.displayRepresentation.subtitle})\"${hasImage ? \",\" : \"\"}`\n );\n }\n if (entity.displayRepresentation.image) {\n lines.push(\n ` image: .init(systemName: \"${escapeSwiftString(entity.displayRepresentation.image)}\")`\n );\n }\n lines.push(` )`);\n lines.push(` }`);\n\n lines.push(`}`);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate an EntityQuery conformance struct based on the entity's query type.\n */\nexport function generateEntityQuery(entity: IREntity): string {\n const lines: string[] = [];\n const queryType = entity.queryType;\n\n lines.push(`struct ${entity.name}Query: EntityQuery {`);\n lines.push(\n ` func entities(for identifiers: [${entity.name}.ID]) async throws -> [${entity.name}] {`\n );\n lines.push(` // TODO: Fetch entities by IDs`);\n lines.push(` return []`);\n lines.push(` }`);\n lines.push(``);\n\n // Generate appropriate query method based on queryType\n if (queryType === \"all\") {\n lines.push(` func allEntities() async throws -> [${entity.name}] {`);\n lines.push(` // TODO: Return all entities`);\n lines.push(` return []`);\n lines.push(` }`);\n } else if (queryType === \"id\") {\n // ID-based query is handled by entities(for:) above\n lines.push(` // ID-based query is provided by the entities(for:) method above`);\n } else if (queryType === \"string\") {\n lines.push(\n ` func entities(matching string: String) async throws -> [${entity.name}] {`\n );\n lines.push(` // TODO: Search entities by string`);\n lines.push(` return []`);\n lines.push(` }`);\n } else if (queryType === \"property\") {\n // Property-based query requires additional configuration\n lines.push(` // Property-based query: implement using EntityPropertyQuery`);\n lines.push(` // Example: property.where { \\\\$0.status == \"active\" }`);\n }\n\n lines.push(`}`);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Info.plist Fragment Generator ───────────────────────────────────\n\n/**\n * Generate an Info.plist XML fragment from the intent's declared keys.\n * Returns `undefined` if the intent declares no Info.plist keys.\n *\n * The fragment is a bare `<dict>`-less sequence of `<key>…</key>` /\n * `<string>…</string>` pairs, ready to be merged into an existing\n * Info.plist. A commented header identifies the source intent so users\n * can audit provenance.\n */\nexport function generateInfoPlistFragment(intent: IRIntent): string | undefined {\n const keys = intent.infoPlistKeys;\n if (!keys || Object.keys(keys).length === 0) return undefined;\n\n const lines: string[] = [];\n lines.push(`<?xml version=\"1.0\" encoding=\"UTF-8\"?>`);\n lines.push(`<!-- Info.plist fragment generated by Axint for ${intent.name}Intent -->`);\n lines.push(`<!-- Merge these keys into your app's Info.plist. -->`);\n lines.push(`<plist version=\"1.0\">`);\n lines.push(`<dict>`);\n for (const [key, desc] of Object.entries(keys)) {\n lines.push(` <key>${escapeXml(key)}</key>`);\n lines.push(` <string>${escapeXml(desc)}</string>`);\n }\n lines.push(`</dict>`);\n lines.push(`</plist>`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Entitlements Fragment Generator ─────────────────────────────────\n\n/**\n * Generate a `.entitlements` XML fragment from the intent's declared\n * entitlements. Returns `undefined` if the intent declares none.\n *\n * Axint only knows the entitlement identifiers, so all entries are\n * emitted as `<true/>` boolean entitlements. If an entitlement requires\n * a typed value (string, array), users must edit the fragment after\n * generation — a TODO comment is emitted to flag this.\n */\nexport function generateEntitlementsFragment(intent: IRIntent): string | undefined {\n const ents = intent.entitlements;\n if (!ents || ents.length === 0) return undefined;\n\n const lines: string[] = [];\n lines.push(`<?xml version=\"1.0\" encoding=\"UTF-8\"?>`);\n lines.push(\n `<!-- Entitlements fragment generated by Axint for ${intent.name}Intent -->`\n );\n lines.push(`<!-- Merge these into your target's .entitlements file. -->`);\n lines.push(`<!-- Note: entitlements requiring typed values (string/array) -->`);\n lines.push(`<!-- need manual adjustment — defaults below are boolean true. -->`);\n lines.push(\n `<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">`\n );\n lines.push(`<plist version=\"1.0\">`);\n lines.push(`<dict>`);\n for (const ent of ents) {\n lines.push(` <key>${escapeXml(ent)}</key>`);\n lines.push(` <true/>`);\n }\n lines.push(`</dict>`);\n lines.push(`</plist>`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction generateParameter(param: IRParameter): string {\n const swiftType = irTypeToSwift(param.type);\n const lines: string[] = [];\n\n // Build @Parameter decorator\n const attrs: string[] = [];\n attrs.push(`title: \"${escapeSwiftString(param.title)}\"`);\n if (param.description) {\n attrs.push(`description: \"${escapeSwiftString(param.description)}\"`);\n }\n\n const decorator = ` @Parameter(${attrs.join(\", \")})`;\n lines.push(decorator);\n\n // Property declaration\n if (param.defaultValue !== undefined) {\n const defaultStr = formatSwiftDefault(param.defaultValue, param.type);\n lines.push(` var ${param.name}: ${swiftType} = ${defaultStr}`);\n } else {\n lines.push(` var ${param.name}: ${swiftType}`);\n }\n\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Choose the Swift return-type signature for the generated perform().\n * We map the inferred IR return type to an App Intents `IntentResult`\n * shape. For primitive return types we use `some ReturnsValue<T>`;\n * for custom result types we use the custom type; otherwise we fall\n * back to `some IntentResult`.\n */\nfunction generateReturnSignature(type: IRType, customResultType?: string): string {\n if (customResultType) {\n return customResultType;\n }\n if (type.kind === \"primitive\") {\n const swift = irTypeToSwift(type);\n return `some IntentResult & ReturnsValue<${swift}>`;\n }\n if (type.kind === \"optional\" && type.innerType.kind === \"primitive\") {\n const swift = irTypeToSwift(type.innerType);\n return `some IntentResult & ReturnsValue<${swift}>`;\n }\n return `some IntentResult`;\n}\n\n/**\n * Emit the `return .result(...)` line that matches the return signature\n * produced by `generateReturnSignature`. When the return type is a\n * primitive we return a well-typed default placeholder the user can\n * replace; otherwise we emit a plain `.result()`.\n */\nfunction generatePerformReturn(type: IRType, customResultType?: string): string {\n const indent = \" \";\n if (customResultType) {\n // For custom result types, the user must provide the implementation\n return `${indent}// TODO: Return a ${customResultType} instance`;\n }\n if (type.kind === \"primitive\") {\n return `${indent}return .result(value: ${defaultLiteralFor(type.value)})`;\n }\n if (type.kind === \"optional\" && type.innerType.kind === \"primitive\") {\n return `${indent}return .result(value: ${defaultLiteralFor(type.innerType.value)})`;\n }\n return `${indent}return .result()`;\n}\n\nfunction defaultLiteralFor(primitive: string): string {\n switch (primitive) {\n case \"string\":\n return `\"\"`;\n case \"int\":\n return `0`;\n case \"double\":\n return `0.0`;\n case \"float\":\n return `Float(0)`;\n case \"boolean\":\n return `false`;\n case \"date\":\n return `Date()`;\n case \"duration\":\n return `Measurement<UnitDuration>(value: 0, unit: .seconds)`;\n case \"url\":\n return `URL(string: \"about:blank\")!`;\n default:\n return `\"\"`;\n }\n}\n\nfunction formatSwiftDefault(value: unknown, _type: IRType): string {\n if (typeof value === \"string\") return `\"${escapeSwiftString(value)}\"`;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) return `0`; // Guard against NaN/Infinity\n return `${value}`;\n }\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n return `\"${escapeSwiftString(String(value))}\"`; // Safe fallback\n}\n","/**\n * Axint Validator\n *\n * Validates generated Swift App Intent code against Apple's API surface.\n * Returns diagnostics with error codes, locations, and fix suggestions.\n */\n\nimport type { Diagnostic, IRIntent, IREntity } from \"./types.js\";\n\n/** Apple-recommended maximum parameters per intent for usability */\nconst MAX_PARAMETERS = 10;\n\n/** Maximum title length before Siri may truncate display */\nconst MAX_TITLE_LENGTH = 60;\n\n/**\n * Validate an IR intent for App Intents framework compliance.\n */\nexport function validateIntent(intent: IRIntent): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n\n // Rule: Intent name must be PascalCase and non-empty\n if (!intent.name || !/^[A-Z][a-zA-Z0-9]*$/.test(intent.name)) {\n diagnostics.push({\n code: \"AX100\",\n severity: \"error\",\n message: `Intent name \"${intent.name}\" must be PascalCase (e.g., \"CreateEvent\")`,\n file: intent.sourceFile,\n suggestion: `Rename to \"${toPascalCase(intent.name)}\"`,\n });\n }\n\n // Rule: Title must not be empty\n if (!intent.title || intent.title.trim().length === 0) {\n diagnostics.push({\n code: \"AX101\",\n severity: \"error\",\n message: \"Intent title must not be empty\",\n file: intent.sourceFile,\n suggestion: \"Add a human-readable title for Siri and Shortcuts display\",\n });\n }\n\n // Rule: Description must not be empty\n if (!intent.description || intent.description.trim().length === 0) {\n diagnostics.push({\n code: \"AX102\",\n severity: \"error\",\n message: \"Intent description must not be empty\",\n file: intent.sourceFile,\n suggestion: \"Add a description explaining what this intent does\",\n });\n }\n\n // Rule: Parameter names must be valid Swift identifiers\n for (const param of intent.parameters) {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(param.name)) {\n diagnostics.push({\n code: \"AX103\",\n severity: \"error\",\n message: `Parameter name \"${param.name}\" is not a valid Swift identifier`,\n file: intent.sourceFile,\n suggestion: `Rename to \"${param.name.replace(/[^a-zA-Z0-9_]/g, \"_\")}\"`,\n });\n }\n\n // Rule: Parameter description should not be empty\n if (!param.description || param.description.trim().length === 0) {\n diagnostics.push({\n code: \"AX104\",\n severity: \"warning\",\n message: `Parameter \"${param.name}\" has no description — Siri will display it without context`,\n file: intent.sourceFile,\n suggestion: \"Add a description for better Siri/Shortcuts display\",\n });\n }\n }\n\n // Rule: Max 10 parameters per intent (App Intents recommendation)\n if (intent.parameters.length > MAX_PARAMETERS) {\n diagnostics.push({\n code: \"AX105\",\n severity: \"warning\",\n message: `Intent has ${intent.parameters.length} parameters. Apple recommends ${MAX_PARAMETERS} or fewer for usability.`,\n file: intent.sourceFile,\n suggestion:\n \"Consider splitting into multiple intents or grouping parameters into an entity\",\n });\n }\n\n // Rule: Title should not exceed 60 characters (Siri display constraint)\n if (intent.title && intent.title.length > MAX_TITLE_LENGTH) {\n diagnostics.push({\n code: \"AX106\",\n severity: \"warning\",\n message: `Intent title is ${intent.title.length} characters. Siri display may truncate titles over ${MAX_TITLE_LENGTH} characters.`,\n file: intent.sourceFile,\n });\n }\n\n // Rule: Parameter names must be unique within an intent\n const seen = new Set<string>();\n for (const param of intent.parameters) {\n if (seen.has(param.name)) {\n diagnostics.push({\n code: \"AX107\",\n severity: \"error\",\n message: `Duplicate parameter name \"${param.name}\"`,\n file: intent.sourceFile,\n suggestion: \"Each parameter in a single intent must have a unique name\",\n });\n }\n seen.add(param.name);\n }\n\n // Rule: Entitlement strings must look like reverse-DNS identifiers\n for (const ent of intent.entitlements ?? []) {\n if (!/^[a-zA-Z0-9._-]+$/.test(ent) || !ent.includes(\".\")) {\n diagnostics.push({\n code: \"AX108\",\n severity: \"warning\",\n message: `Entitlement \"${ent}\" does not look like a valid reverse-DNS identifier`,\n file: intent.sourceFile,\n suggestion:\n 'Use reverse-DNS, e.g., \"com.apple.developer.siri\" or \"com.apple.security.app-sandbox\"',\n });\n }\n }\n\n // Rule: Info.plist keys must start with \"NS\" or other known prefixes\n for (const key of Object.keys(intent.infoPlistKeys ?? {})) {\n if (!/^(NS|UI|LS|CF|CA|CK)[A-Za-z0-9]+$/.test(key)) {\n diagnostics.push({\n code: \"AX109\",\n severity: \"warning\",\n message: `Info.plist key \"${key}\" does not match Apple's usual naming conventions`,\n file: intent.sourceFile,\n suggestion:\n 'Apple keys generally start with \"NS\" (e.g., \"NSCalendarsUsageDescription\")',\n });\n }\n }\n\n // Validate all entities\n if (intent.entities) {\n for (const entity of intent.entities) {\n diagnostics.push(...validateEntity(entity, intent.sourceFile));\n }\n }\n\n return diagnostics;\n}\n\n/**\n * Validate an IREntity for App Intents framework compliance.\n */\nexport function validateEntity(entity: IREntity, sourceFile: string): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n\n // Rule AX110: Entity name must be PascalCase\n if (!entity.name || !/^[A-Z][a-zA-Z0-9]*$/.test(entity.name)) {\n diagnostics.push({\n code: \"AX110\",\n severity: \"error\",\n message: `Entity name \"${entity.name}\" must be PascalCase (e.g., \"Task\", \"Playlist\")`,\n file: sourceFile,\n suggestion: `Rename to \"${toPascalCase(entity.name)}\"`,\n });\n }\n\n // Rule AX111: Entity must have at least one property\n if (entity.properties.length === 0) {\n diagnostics.push({\n code: \"AX111\",\n severity: \"error\",\n message: `Entity \"${entity.name}\" must have at least one property`,\n file: sourceFile,\n suggestion: \"Add properties to define the entity's structure\",\n });\n }\n\n // Rule AX112: Display title must reference an existing property\n const titleProp = entity.displayRepresentation.title;\n const propertyNames = new Set(entity.properties.map((p) => p.name));\n if (titleProp && !propertyNames.has(titleProp)) {\n diagnostics.push({\n code: \"AX112\",\n severity: \"warning\",\n message: `Display title \"${titleProp}\" does not reference an existing property`,\n file: sourceFile,\n suggestion: `Available properties: ${[...propertyNames].join(\", \")}`,\n });\n }\n\n // Rule AX113: Query type must be valid\n const validQueryTypes = [\"all\", \"id\", \"string\", \"property\"];\n if (!validQueryTypes.includes(entity.queryType)) {\n diagnostics.push({\n code: \"AX113\",\n severity: \"error\",\n message: `Entity query type \"${entity.queryType}\" is not valid`,\n file: sourceFile,\n suggestion: `Use one of: ${validQueryTypes.join(\", \")}`,\n });\n }\n\n return diagnostics;\n}\n\n/**\n * Validate generated Swift source code for basic correctness.\n */\nexport function validateSwiftSource(swift: string): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n\n // Check for required import\n if (!swift.includes(\"import AppIntents\")) {\n diagnostics.push({\n code: \"AX200\",\n severity: \"error\",\n message: 'Generated Swift is missing \"import AppIntents\"',\n });\n }\n\n // Check for AppIntent conformance\n if (!swift.includes(\": AppIntent\")) {\n diagnostics.push({\n code: \"AX201\",\n severity: \"error\",\n message: \"Generated struct does not conform to AppIntent protocol\",\n });\n }\n\n // Check for perform function\n if (!swift.includes(\"func perform()\")) {\n diagnostics.push({\n code: \"AX202\",\n severity: \"error\",\n message: \"Generated struct is missing the perform() function\",\n });\n }\n\n return diagnostics;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction toPascalCase(s: string): string {\n if (!s) return \"UnnamedIntent\";\n return s\n .replace(/[-_\\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : \"\"))\n .replace(/^(.)/, (c) => c.toUpperCase());\n}\n","/**\n * Axint Compiler\n *\n * Orchestrates the full compilation pipeline:\n * 1. Parse TypeScript intent definition → IR\n * 2. Validate IR against App Intents constraints\n * 3. Generate Swift source code\n * 4. Validate generated Swift\n * 5. Optionally emit Info.plist and entitlements fragments\n *\n * This is the main entry point for the compilation process.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parseIntentSource, ParserError } from \"./parser.js\";\nimport {\n generateSwift,\n generateInfoPlistFragment,\n generateEntitlementsFragment,\n} from \"./generator.js\";\nimport { validateIntent, validateSwiftSource } from \"./validator.js\";\nimport type {\n CompilerOutput,\n CompilerOptions,\n Diagnostic,\n IRIntent,\n IRType,\n IRParameter,\n IRPrimitiveType,\n} from \"./types.js\";\n\nexport interface CompileResult {\n success: boolean;\n output?: CompilerOutput;\n diagnostics: Diagnostic[];\n}\n\n/**\n * Compile a TypeScript intent definition file into Swift.\n */\nexport function compileFile(\n filePath: string,\n options: Partial<CompilerOptions> = {}\n): CompileResult {\n // 1. Read source\n let source: string;\n try {\n source = readFileSync(filePath, \"utf-8\");\n } catch (_err) {\n return {\n success: false,\n diagnostics: [\n {\n code: \"AX000\",\n severity: \"error\",\n message: `Cannot read file: ${filePath}`,\n file: filePath,\n },\n ],\n };\n }\n\n return compileSource(source, filePath, options);\n}\n\n/**\n * Compile a TypeScript source string directly (no file I/O).\n * Useful for MCP server and testing.\n */\nexport function compileSource(\n source: string,\n fileName: string = \"<stdin>\",\n options: Partial<CompilerOptions> = {}\n): CompileResult {\n // 1. Parse → IR (catch ParserError as a diagnostic so the caller\n // sees a clean error list instead of an uncaught exception)\n let ir;\n try {\n ir = parseIntentSource(source, fileName);\n } catch (err) {\n if (err instanceof ParserError) {\n return {\n success: false,\n diagnostics: [\n {\n code: err.code,\n severity: \"error\",\n message: err.message,\n file: err.file,\n line: err.line,\n suggestion: err.suggestion,\n },\n ],\n };\n }\n throw err;\n }\n\n return compileFromIR(ir, options);\n}\n\n/**\n * Compile from a pre-built IR (skips parsing). This is the bridge\n * that allows any frontend language (Python, Rust, Go) to emit an\n * IRIntent JSON and feed it directly into the Swift generator.\n *\n * Used by:\n * - `compileSource()` after its own parse step\n * - `axint compile --from-ir <file.json>` for cross-language pipelines\n * - The Python SDK's `axintai compile` command\n */\nexport function compileFromIR(\n ir: IRIntent,\n options: Partial<CompilerOptions> = {}\n): CompileResult {\n const diagnostics: Diagnostic[] = [];\n\n // 1. Validate IR\n const irDiagnostics = validateIntent(ir);\n diagnostics.push(...irDiagnostics);\n\n if (irDiagnostics.some((d) => d.severity === \"error\")) {\n return { success: false, diagnostics };\n }\n\n // 2. Generate Swift\n const swiftCode = generateSwift(ir);\n\n // 3. Validate generated Swift\n if (options.validate !== false) {\n const swiftDiagnostics = validateSwiftSource(swiftCode);\n diagnostics.push(...swiftDiagnostics);\n\n if (swiftDiagnostics.some((d) => d.severity === \"error\")) {\n return { success: false, diagnostics };\n }\n }\n\n // 4. Optional fragments\n const infoPlistFragment = options.emitInfoPlist\n ? generateInfoPlistFragment(ir)\n : undefined;\n const entitlementsFragment = options.emitEntitlements\n ? generateEntitlementsFragment(ir)\n : undefined;\n\n // 5. Build output\n const intentFileName = `${ir.name}Intent.swift`;\n const outputPath = options.outDir\n ? `${options.outDir}/${intentFileName}`\n : intentFileName;\n\n return {\n success: true,\n output: {\n outputPath,\n swiftCode,\n infoPlistFragment,\n entitlementsFragment,\n ir,\n diagnostics,\n },\n diagnostics,\n };\n}\n\n// ─── Cross-Language IR Bridge ───────────────────────────────────────\n\n/** Valid primitive type strings from any SDK */\nconst VALID_PRIMITIVES = new Set<string>([\n \"string\",\n \"int\",\n \"double\",\n \"float\",\n \"boolean\",\n \"date\",\n \"duration\",\n \"url\",\n]);\n\n/**\n * Parse a raw JSON object into a typed IRIntent. Accepts the flat\n * format that the Python SDK's `IntentIR.to_dict()` produces, where\n * parameter types are plain strings rather than `{ kind, value }` objects.\n *\n * This is the key function that bridges the Python → TypeScript gap.\n */\nexport function irFromJSON(data: Record<string, unknown>): IRIntent {\n const parameters: IRParameter[] = ((data.parameters as unknown[]) ?? []).map(\n (p: unknown) => {\n const param = p as Record<string, unknown>;\n return {\n name: param.name as string,\n type: normalizeIRType(param.type),\n title: (param.title as string) ?? (param.description as string) ?? \"\",\n description: (param.description as string) ?? \"\",\n isOptional: (param.optional as boolean) ?? (param.isOptional as boolean) ?? false,\n defaultValue: param.default ?? param.defaultValue,\n };\n }\n );\n\n return {\n name: data.name as string,\n title: data.title as string,\n description: data.description as string,\n domain: data.domain as string | undefined,\n parameters,\n returnType: data.returnType\n ? normalizeIRType(data.returnType)\n : { kind: \"primitive\", value: \"string\" },\n sourceFile: (data.sourceFile as string) ?? undefined,\n entitlements: (data.entitlements as string[]) ?? undefined,\n infoPlistKeys: (data.infoPlistKeys as Record<string, string>) ?? undefined,\n isDiscoverable: (data.isDiscoverable as boolean) ?? true,\n };\n}\n\n/**\n * Normalize a type value from JSON. The Python SDK sends types as\n * plain strings (\"string\", \"int\", etc.) while the TS IR uses\n * `{ kind: \"primitive\", value: \"string\" }`. This function handles both.\n */\nfunction normalizeIRType(type: unknown): IRType {\n if (typeof type === \"string\") {\n const normalized = type === \"number\" ? \"int\" : type;\n if (VALID_PRIMITIVES.has(normalized)) {\n return { kind: \"primitive\", value: normalized as IRPrimitiveType };\n }\n return { kind: \"primitive\", value: \"string\" };\n }\n if (type && typeof type === \"object\") {\n const t = type as Record<string, unknown>;\n if (t.kind === \"primitive\") return type as IRType;\n if (t.kind === \"array\")\n return { kind: \"array\", elementType: normalizeIRType(t.elementType) };\n if (t.kind === \"optional\")\n return { kind: \"optional\", innerType: normalizeIRType(t.innerType) };\n if (t.kind === \"entity\") return type as IRType;\n if (t.kind === \"enum\") return type as IRType;\n }\n // Default fallback\n return { kind: \"primitive\", value: \"string\" };\n}\n","/**\n * swift-format integration (optional post-processor)\n *\n * After codegen, optionally pipe the emitted Swift through Apple's\n * `swift-format` tool with a house style file that mirrors Apple's own\n * codebase. This is the last stage of the pipeline that runs before\n * writing to disk.\n *\n * `swift-format` ships with the Swift toolchain on macOS. If the binary\n * isn't on $PATH (Linux CI, Windows, containers) we log a warning and\n * return the source unchanged rather than failing the build — the\n * generator already emits valid, well-indented Swift without it.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { writeFile, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { tmpdir } from \"node:os\";\n\nexport interface FormatOptions {\n /** Hard timeout in ms for the swift-format call (default 8s) */\n timeoutMs?: number;\n /** Throw on failure instead of returning the original source */\n strict?: boolean;\n}\n\nexport interface FormatResult {\n formatted: string;\n ran: boolean;\n reason?: string;\n}\n\n/** The house style file — tracks Apple's swift-format defaults + Axint tweaks. */\nexport const SWIFT_FORMAT_CONFIG = {\n version: 1,\n lineLength: 100,\n indentation: { spaces: 4 },\n tabWidth: 4,\n maximumBlankLines: 1,\n respectsExistingLineBreaks: true,\n lineBreakBeforeControlFlowKeywords: false,\n lineBreakBeforeEachArgument: false,\n lineBreakBeforeEachGenericRequirement: false,\n prioritizeKeepingFunctionOutputTogether: false,\n indentConditionalCompilationBlocks: true,\n lineBreakAroundMultilineExpressionChainComponents: false,\n fileScopedDeclarationPrivacy: { accessLevel: \"private\" },\n rules: {\n AllPublicDeclarationsHaveDocumentation: false,\n AlwaysUseLowerCamelCase: true,\n AmbiguousTrailingClosureOverload: true,\n BeginDocumentationCommentWithOneLineSummary: false,\n DoNotUseSemicolons: true,\n DontRepeatTypeInStaticProperties: true,\n FileScopedDeclarationPrivacy: true,\n FullyIndirectEnum: true,\n GroupNumericLiterals: true,\n IdentifiersMustBeASCII: true,\n NeverForceUnwrap: false,\n NeverUseForceTry: false,\n NeverUseImplicitlyUnwrappedOptionals: false,\n NoBlockComments: false,\n NoCasesWithOnlyFallthrough: true,\n NoEmptyTrailingClosureParentheses: true,\n NoLabelsInCasePatterns: true,\n NoLeadingUnderscores: false,\n NoParensAroundConditions: true,\n NoVoidReturnOnFunctionSignature: true,\n OneCasePerLine: true,\n OneVariableDeclarationPerLine: true,\n OnlyOneTrailingClosureArgument: true,\n OrderedImports: true,\n ReturnVoidInsteadOfEmptyTuple: true,\n UseEarlyExits: false,\n UseLetInEveryBoundCaseVariable: true,\n UseShorthandTypeNames: true,\n UseSingleLinePropertyGetter: true,\n UseSynthesizedInitializer: true,\n UseTripleSlashForDocumentationComments: true,\n UseWhereClausesInForLoops: false,\n ValidateDocumentationComments: false,\n },\n} as const;\n\n/**\n * Run swift-format against a Swift source string and return the formatted\n * output. Falls back to the original source if swift-format is unavailable.\n */\nexport async function formatSwift(\n source: string,\n options: FormatOptions = {}\n): Promise<FormatResult> {\n const available = await hasSwiftFormat();\n if (!available) {\n if (options.strict) {\n throw new Error(\n \"swift-format not found on $PATH. Install Xcode + Command Line Tools, or drop --format.\"\n );\n }\n return {\n formatted: source,\n ran: false,\n reason: \"swift-format not found on $PATH\",\n };\n }\n\n const configPath = join(\n tmpdir(),\n `axint-swift-format-${Date.now()}-${Math.random().toString(36).slice(2)}.json`\n );\n await writeFile(configPath, JSON.stringify(SWIFT_FORMAT_CONFIG, null, 2));\n\n try {\n const result = await runSwiftFormat(source, configPath, options.timeoutMs ?? 8_000);\n if (result.code === 0) {\n return { formatted: result.stdout, ran: true };\n }\n if (options.strict) {\n throw new Error(`swift-format failed: ${result.stderr}`);\n }\n return {\n formatted: source,\n ran: false,\n reason: `swift-format exited ${result.code}: ${result.stderr}`,\n };\n } finally {\n await unlink(configPath).catch(() => undefined);\n }\n}\n\nfunction hasSwiftFormat(): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(\"swift-format\", [\"--version\"], { stdio: \"pipe\" });\n child.on(\"error\", () => resolve(false));\n child.on(\"exit\", (code) => resolve(code === 0));\n });\n}\n\nfunction runSwiftFormat(\n source: string,\n configPath: string,\n timeoutMs: number\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolve) => {\n const child = spawn(\"swift-format\", [\"format\", \"--configuration\", configPath], {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (d) => (stdout += d.toString()));\n child.stderr?.on(\"data\", (d) => (stderr += d.toString()));\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n resolve({\n stdout,\n stderr: stderr + `\\n[format] killed after ${timeoutMs}ms`,\n code: 124,\n });\n }, timeoutMs);\n child.on(\"exit\", (code) => {\n clearTimeout(timer);\n resolve({ stdout, stderr, code: code ?? 1 });\n });\n child.stdin?.write(source);\n child.stdin?.end();\n });\n}\n","/**\n * Intent Template Registry\n *\n * Pre-built reference templates for common App Intent patterns across\n * every major Apple domain. Each template is a complete, runnable\n * TypeScript file that compiles cleanly with `axint compile`.\n *\n * Templates are exposed through the MCP server (`axint_list_templates`,\n * `axint_template`) and the CLI (`axint new --template <id>`).\n */\n\nexport interface IntentTemplate {\n /** Unique template identifier, kebab-case */\n id: string;\n /** Short kebab/camel name (kept for backwards compat) */\n name: string;\n /** Human-readable display title */\n title: string;\n /** Apple App Intent domain */\n domain: string;\n /** Category for filtering — usually mirrors domain */\n category: string;\n /** Description of what this template generates */\n description: string;\n /** The TypeScript source template (uses defineIntent API) */\n source: string;\n}\n\n// ─── Template definitions ────────────────────────────────────────────\n\nconst sendMessage: IntentTemplate = {\n id: \"send-message\",\n name: \"send-message\",\n title: \"Send Message\",\n domain: \"messaging\",\n category: \"messaging\",\n description: \"Send a text message to a contact.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"SendMessage\",\n title: \"Send Message\",\n description: \"Sends a message to a specified contact.\",\n domain: \"messaging\",\n params: {\n recipient: param.string(\"Who to send the message to\"),\n body: param.string(\"The message content\"),\n },\n perform: async ({ recipient, body }) => {\n // TODO: Integrate with your messaging backend\n return { sent: true };\n },\n});\n`,\n};\n\nconst createEvent: IntentTemplate = {\n id: \"create-event\",\n name: \"create-event\",\n title: \"Create Calendar Event\",\n domain: \"productivity\",\n category: \"productivity\",\n description: \"Create a calendar event with a title, date, and duration.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"CreateEvent\",\n title: \"Create Calendar Event\",\n description: \"Creates a new event in the user's calendar.\",\n domain: \"productivity\",\n entitlements: [\"com.apple.developer.siri\"],\n infoPlistKeys: {\n NSCalendarsUsageDescription: \"Access to your calendar to create events.\",\n },\n params: {\n title: param.string(\"Event title\"),\n date: param.date(\"Event date\"),\n durationMinutes: param.int(\"Duration in minutes\", { default: 30 }),\n allDay: param.boolean(\"All-day event\", { required: false }),\n },\n perform: async ({ title, date }) => {\n return { eventId: \"evt_placeholder\" };\n },\n});\n`,\n};\n\nconst bookRide: IntentTemplate = {\n id: \"book-ride\",\n name: \"book-ride\",\n title: \"Book a Ride\",\n domain: \"navigation\",\n category: \"navigation\",\n description: \"Request a ride from a pickup location to a destination.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"BookRide\",\n title: \"Book a Ride\",\n description: \"Requests a ride from a pickup location to a destination.\",\n domain: \"navigation\",\n params: {\n pickup: param.string(\"Pickup location\"),\n destination: param.string(\"Destination address\"),\n passengers: param.int(\"Number of passengers\", { default: 1 }),\n },\n perform: async ({ pickup, destination }) => {\n return { rideId: \"ride_placeholder\", eta: 300 };\n },\n});\n`,\n};\n\nconst getDirections: IntentTemplate = {\n id: \"get-directions\",\n name: \"get-directions\",\n title: \"Get Directions\",\n domain: \"navigation\",\n category: \"navigation\",\n description: \"Get turn-by-turn directions to a destination.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"GetDirections\",\n title: \"Get Directions\",\n description: \"Returns turn-by-turn directions to a destination.\",\n domain: \"navigation\",\n params: {\n destination: param.string(\"Where to navigate to\"),\n mode: param.string(\"Travel mode (driving, walking, transit)\", {\n default: \"driving\",\n }),\n },\n perform: async ({ destination }) => {\n return { routeId: \"route_placeholder\" };\n },\n});\n`,\n};\n\nconst playTrack: IntentTemplate = {\n id: \"play-track\",\n name: \"play-track\",\n title: \"Play Track\",\n domain: \"media\",\n category: \"media\",\n description: \"Play a specific track or song.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"PlayTrack\",\n title: \"Play Track\",\n description: \"Plays a specific track by title and artist.\",\n domain: \"media\",\n params: {\n track: param.string(\"Track title\"),\n artist: param.string(\"Artist name\", { required: false }),\n shuffle: param.boolean(\"Shuffle mode\", { required: false }),\n },\n perform: async ({ track }) => {\n return { playing: true };\n },\n});\n`,\n};\n\nconst createNote: IntentTemplate = {\n id: \"create-note\",\n name: \"create-note\",\n title: \"Create Note\",\n domain: \"productivity\",\n category: \"productivity\",\n description: \"Create a new note with a title and body.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"CreateNote\",\n title: \"Create Note\",\n description: \"Creates a new note with a title and body.\",\n domain: \"productivity\",\n params: {\n title: param.string(\"Note title\"),\n body: param.string(\"Note body\"),\n pinned: param.boolean(\"Pin the note\", { required: false }),\n },\n perform: async ({ title, body }) => {\n return { noteId: \"note_placeholder\" };\n },\n});\n`,\n};\n\nconst logExpense: IntentTemplate = {\n id: \"log-expense\",\n name: \"log-expense\",\n title: \"Log Expense\",\n domain: \"finance\",\n category: \"finance\",\n description: \"Log a financial expense with amount, category, and note.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"LogExpense\",\n title: \"Log Expense\",\n description: \"Logs a financial expense with amount, category, and note.\",\n domain: \"finance\",\n params: {\n amount: param.double(\"Expense amount\"),\n currency: param.string(\"ISO currency code (e.g., USD)\", {\n default: \"USD\",\n }),\n category: param.string(\"Expense category\"),\n note: param.string(\"Optional note\", { required: false }),\n },\n perform: async ({ amount, category }) => {\n return { expenseId: \"exp_placeholder\" };\n },\n});\n`,\n};\n\nconst logWorkout: IntentTemplate = {\n id: \"log-workout\",\n name: \"log-workout\",\n title: \"Log Workout\",\n domain: \"health\",\n category: \"health\",\n description: \"Log a workout with duration, type, and calories burned.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"LogWorkout\",\n title: \"Log Workout\",\n description: \"Logs a workout with duration, type, and calories burned.\",\n domain: \"health\",\n entitlements: [\"com.apple.developer.healthkit\"],\n infoPlistKeys: {\n NSHealthShareUsageDescription: \"Read workout history to track progress.\",\n NSHealthUpdateUsageDescription: \"Save new workouts you log.\",\n },\n params: {\n type: param.string(\"Workout type (e.g., running, cycling)\"),\n duration: param.duration(\"Workout duration\"),\n calories: param.int(\"Calories burned\", { required: false }),\n },\n perform: async ({ type, duration }) => {\n return { workoutId: \"wo_placeholder\" };\n },\n});\n`,\n};\n\nconst setThermostat: IntentTemplate = {\n id: \"set-thermostat\",\n name: \"set-thermostat\",\n title: \"Set Thermostat\",\n domain: \"smart-home\",\n category: \"smart-home\",\n description: \"Set a smart-home thermostat to a target temperature.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"SetThermostat\",\n title: \"Set Thermostat\",\n description: \"Sets a smart-home thermostat to a target temperature.\",\n domain: \"smart-home\",\n params: {\n room: param.string(\"Which room\"),\n temperature: param.double(\"Target temperature\"),\n unit: param.string(\"Temperature unit (F or C)\", { default: \"F\" }),\n },\n perform: async ({ room, temperature }) => {\n return { set: true };\n },\n});\n`,\n};\n\nconst placeOrder: IntentTemplate = {\n id: \"place-order\",\n name: \"place-order\",\n title: \"Place Order\",\n domain: \"commerce\",\n category: \"commerce\",\n description: \"Place a commerce order for a product.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"PlaceOrder\",\n title: \"Place Order\",\n description: \"Places an order for a product.\",\n domain: \"commerce\",\n params: {\n productId: param.string(\"Product identifier\"),\n quantity: param.int(\"Quantity\", { default: 1 }),\n shippingAddress: param.string(\"Shipping address\", { required: false }),\n },\n perform: async ({ productId, quantity }) => {\n return { orderId: \"ord_placeholder\", total: 0 };\n },\n});\n`,\n};\n\nconst searchTasks: IntentTemplate = {\n id: \"search-tasks\",\n name: \"search-tasks\",\n title: \"Search Tasks\",\n domain: \"productivity\",\n category: \"productivity\",\n description: \"Search for tasks using EntityQuery with string-based search.\",\n source: `import { defineIntent, defineEntity, param } from \"@axintai/compiler\";\n\ndefineEntity({\n name: \"Task\",\n display: {\n title: \"name\",\n subtitle: \"status\",\n },\n properties: {\n id: param.string(\"Unique task identifier\"),\n name: param.string(\"Task name\"),\n status: param.string(\"Task status (todo, in-progress, done)\"),\n dueDate: param.date(\"Due date\"),\n },\n query: \"string\",\n});\n\nexport default defineIntent({\n name: \"SearchTasks\",\n title: \"Search Tasks\",\n description: \"Search for tasks by name or status.\",\n domain: \"productivity\",\n params: {\n query: param.string(\"Search query\"),\n status: param.string(\"Filter by status (optional)\", { required: false }),\n },\n donateOnPerform: true,\n perform: async ({ query, status }) => {\n // TODO: Search your task database with the query\n // Use status filter if provided\n return { found: true, results: 0 };\n },\n});\n`,\n};\n\nconst dynamicPlaylist: IntentTemplate = {\n id: \"dynamic-playlist\",\n name: \"dynamic-playlist\",\n title: \"Dynamic Playlist\",\n domain: \"media\",\n category: \"media\",\n description: \"Create a playlist by name, mood, and track count.\",\n source: `import { defineIntent, param } from \"@axintai/compiler\";\n\nexport default defineIntent({\n name: \"DynamicPlaylist\",\n title: \"Create Dynamic Playlist\",\n description: \"Create a playlist with a given mood or genre.\",\n domain: \"media\",\n params: {\n name: param.string(\"Playlist name\"),\n mood: param.string(\"Mood or genre (e.g., chill, workout, focus)\"),\n trackCount: param.int(\"Number of tracks\", { default: 20 }),\n },\n perform: async ({ name, mood }) => {\n return { playlistId: \"playlist_placeholder\" };\n },\n});\n`,\n};\n\n// ─── Registry ────────────────────────────────────────────────────────\n\nexport const TEMPLATES: IntentTemplate[] = [\n sendMessage,\n createEvent,\n bookRide,\n getDirections,\n playTrack,\n createNote,\n logExpense,\n logWorkout,\n setThermostat,\n placeOrder,\n searchTasks,\n dynamicPlaylist,\n];\n\n/** @deprecated Use TEMPLATES. Kept for v0.1.x import compatibility. */\nexport const templates = TEMPLATES;\n\nexport function getTemplate(id: string): IntentTemplate | undefined {\n return TEMPLATES.find((t) => t.id === id);\n}\n\nexport function listTemplates(category?: string): IntentTemplate[] {\n if (category) {\n return TEMPLATES.filter((t) => t.category === category);\n }\n return TEMPLATES;\n}\n","/**\n * Stage 4 Validator — SPM Sandbox Compile\n *\n * The \"prove the Swift actually builds\" stage. Generated Swift is dropped into\n * a throwaway Swift Package Manager project and compiled with `swift build`.\n * If it builds cleanly, we've proven the intent file is Xcode-ready.\n *\n * This stage is macOS-only (requires `swift` in PATH and the App Intents\n * framework from the Xcode SDK). It's wired behind the `--sandbox` flag so\n * Linux/Windows CI stays green without it.\n *\n * The sandbox lives in a deterministic directory inside os.tmpdir() so that\n * repeated invocations can reuse the `.build/` cache — typical per-intent\n * compile time is ~1.2s warm, ~4s cold on an M-series Mac.\n */\n\nimport { mkdir, writeFile, rm } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { tmpdir } from \"node:os\";\nimport { spawn } from \"node:child_process\";\n\nexport interface SandboxOptions {\n intentName: string;\n /** Override the sandbox root (default: $TMPDIR/axint-sandbox) */\n rootDir?: string;\n /** Keep the sandbox on disk after the run (default: false) */\n keep?: boolean;\n /** Hard timeout in ms for the `swift build` call (default: 60s) */\n timeoutMs?: number;\n}\n\nexport interface SandboxResult {\n ok: boolean;\n stdout: string;\n stderr: string;\n durationMs: number;\n sandboxPath: string;\n}\n\nconst PACKAGE_SWIFT = (name: string) => `// swift-tools-version:5.9\nimport PackageDescription\n\nlet package = Package(\n name: \"${name}Sandbox\",\n platforms: [\n .iOS(.v16),\n .macOS(.v13),\n ],\n products: [\n .library(name: \"${name}Sandbox\", targets: [\"${name}Sandbox\"]),\n ],\n targets: [\n .target(\n name: \"${name}Sandbox\",\n path: \"Sources/${name}Sandbox\"\n ),\n ]\n)\n`;\n\n/**\n * Compile a Swift source string inside a throwaway SPM project and return\n * the result. Does not throw on build failure — the caller inspects `ok`.\n */\nexport async function sandboxCompile(\n swiftSource: string,\n options: SandboxOptions\n): Promise<SandboxResult> {\n const start = Date.now();\n\n // Check that swift is available before we touch disk\n const available = await hasSwiftToolchain();\n if (!available) {\n throw new Error(\n \"Swift toolchain not found. Install Xcode + Command Line Tools, or run without `--sandbox`.\"\n );\n }\n\n const root = options.rootDir ?? join(tmpdir(), \"axint-sandbox\", options.intentName);\n const srcDir = join(root, \"Sources\", `${options.intentName}Sandbox`);\n\n try {\n await mkdir(srcDir, { recursive: true });\n await writeFile(join(root, \"Package.swift\"), PACKAGE_SWIFT(options.intentName));\n await writeFile(join(srcDir, `${options.intentName}Intent.swift`), swiftSource);\n } catch (err) {\n return {\n ok: false,\n stdout: \"\",\n stderr: `Failed to stage sandbox: ${(err as Error).message}`,\n durationMs: Date.now() - start,\n sandboxPath: root,\n };\n }\n\n const { stdout, stderr, code } = await runSwiftBuild(root, options.timeoutMs ?? 60_000);\n\n if (!options.keep && code === 0) {\n // Only tear down on success — keep failures for post-mortem.\n await rm(root, { recursive: true, force: true }).catch(() => undefined);\n }\n\n return {\n ok: code === 0,\n stdout,\n stderr,\n durationMs: Date.now() - start,\n sandboxPath: root,\n };\n}\n\nasync function hasSwiftToolchain(): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(\"swift\", [\"--version\"], { stdio: \"pipe\" });\n child.on(\"error\", () => resolve(false));\n child.on(\"exit\", (code) => resolve(code === 0));\n });\n}\n\nfunction runSwiftBuild(\n cwd: string,\n timeoutMs: number\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolve) => {\n const child = spawn(\"swift\", [\"build\", \"-c\", \"debug\"], {\n cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (d) => (stdout += d.toString()));\n child.stderr?.on(\"data\", (d) => (stderr += d.toString()));\n\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n resolve({\n stdout,\n stderr: stderr + `\\n[sandbox] killed after ${timeoutMs}ms`,\n code: 124,\n });\n }, timeoutMs);\n\n child.on(\"exit\", (code) => {\n clearTimeout(timer);\n resolve({ stdout, stderr, code: code ?? 1 });\n });\n });\n}\n\n/** Helper for tests: check whether the sandbox dir exists */\nexport function sandboxExists(intentName: string): boolean {\n return existsSync(join(tmpdir(), \"axint-sandbox\", intentName));\n}\n","/**\n * Scaffold generator for the axint MCP server.\n *\n * Produces a ready-to-save TypeScript intent file from a small set of\n * inputs. This is the \"blank canvas\" AI assistants hit when a user says\n * \"create a new App Intent for X\" — instead of guessing, the assistant\n * calls axint_scaffold and writes the result straight to disk.\n */\n\nimport {\n PARAM_TYPES,\n LEGACY_PARAM_ALIASES,\n type IRPrimitiveType,\n} from \"../core/types.js\";\n\nexport interface ScaffoldInput {\n name: string;\n description: string;\n domain?: string;\n params?: Array<{ name: string; type: string; description: string }>;\n}\n\n/**\n * Generate a starter TypeScript intent file from the given inputs.\n * The result is valid input to `axint compile` — it uses the public\n * defineIntent() / param.* API and includes a TODO in the perform body.\n */\nexport function scaffoldIntent(input: ScaffoldInput): string {\n const name = toPascalCase(input.name);\n const title = humanize(name);\n const desc = sanitize(input.description);\n const domain = input.domain ? sanitize(input.domain) : undefined;\n\n const paramLines: string[] = [];\n const destructureNames: string[] = [];\n for (const p of input.params ?? []) {\n const type = resolveType(p.type);\n const safeName = toCamelCase(p.name);\n destructureNames.push(safeName);\n paramLines.push(\n ` ${safeName}: param.${type}(${JSON.stringify(sanitize(p.description))}),`\n );\n }\n\n const paramsBlock = paramLines.length > 0 ? `\\n${paramLines.join(\"\\n\")}\\n ` : \"\";\n const destructure =\n destructureNames.length > 0 ? `{ ${destructureNames.join(\", \")} }` : \"_\";\n\n const lines: string[] = [];\n lines.push(`/**`);\n lines.push(` * ${name}Intent`);\n lines.push(` *`);\n lines.push(` * ${desc}`);\n lines.push(` *`);\n lines.push(` * Generated by axint_scaffold. Edit freely, then run:`);\n lines.push(` * npx axint compile src/intents/${kebab(name)}.ts`);\n lines.push(` */`);\n lines.push(`import { defineIntent, param } from \"@axintai/compiler\";`);\n lines.push(``);\n lines.push(`export default defineIntent({`);\n lines.push(` name: ${JSON.stringify(name)},`);\n lines.push(` title: ${JSON.stringify(title)},`);\n lines.push(` description: ${JSON.stringify(desc)},`);\n if (domain) lines.push(` domain: ${JSON.stringify(domain)},`);\n lines.push(` params: {${paramsBlock}},`);\n lines.push(` perform: async (${destructure}) => {`);\n lines.push(` // TODO: Implement ${name}`);\n lines.push(` return { success: true };`);\n lines.push(` },`);\n lines.push(`});`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction resolveType(raw: string): IRPrimitiveType {\n const lc = raw.toLowerCase();\n if (PARAM_TYPES.has(lc as IRPrimitiveType)) return lc as IRPrimitiveType;\n if (lc in LEGACY_PARAM_ALIASES) return LEGACY_PARAM_ALIASES[lc];\n // Fall back to string — keeps scaffolding from throwing on unknown\n // types. Users can edit the file if they wanted something more exotic.\n return \"string\";\n}\n\nfunction toPascalCase(s: string): string {\n if (!s) return \"UnnamedIntent\";\n return s\n .replace(/[-_\\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : \"\"))\n .replace(/^(.)/, (c) => c.toUpperCase());\n}\n\nfunction toCamelCase(s: string): string {\n const pascal = toPascalCase(s);\n return pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n\nfunction humanize(pascal: string): string {\n return pascal.replace(/([A-Z])/g, \" $1\").trim();\n}\n\nfunction kebab(pascal: string): string {\n return pascal\n .replace(/([a-z])([A-Z])/g, \"$1-$2\")\n .replace(/\\s+/g, \"-\")\n .toLowerCase();\n}\n\n/**\n * Keep user-provided strings safe for interpolation. We strip control\n * chars and collapse runs of whitespace — this prevents scaffold output\n * from getting garbled by rogue newlines or tabs in a description.\n */\nfunction sanitize(s: string): string {\n return s\n .replace(/[\\x00-\\x1f\\x7f]+/g, \" \") // eslint-disable-line no-control-regex\n .replace(/\\s+/g, \" \")\n .trim();\n}\n","/**\n * Axint MCP Server\n *\n * Exposes Axint capabilities as MCP tools that AI coding assistants\n * (Claude Code, Cursor, Windsurf, Zed, any MCP client) can call\n * automatically.\n *\n * Tools:\n * - axint_scaffold: Generate a starter TypeScript intent file\n * - axint_compile: Compile TypeScript intent → Swift App Intent\n * (optionally with Info.plist and entitlements)\n * - axint_validate: Validate an intent definition without codegen\n * - axint_list_templates: List bundled reference templates\n * - axint_template: Return the source of a specific template\n */\n\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { compileSource } from \"../core/compiler.js\";\nimport { scaffoldIntent } from \"./scaffold.js\";\nimport { TEMPLATES, getTemplate } from \"../templates/index.js\";\n\n// Read version from package.json so it stays in sync\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(\n readFileSync(resolve(__dirname, \"../../package.json\"), \"utf-8\")\n);\n\ntype CompileArgs = {\n source: string;\n fileName?: string;\n emitInfoPlist?: boolean;\n emitEntitlements?: boolean;\n};\n\ntype ScaffoldArgs = {\n name: string;\n description: string;\n domain?: string;\n params?: Array<{ name: string; type: string; description: string }>;\n};\n\ntype TemplateArgs = { id: string };\n\nexport async function startMCPServer(): Promise<void> {\n const server = new Server(\n { name: \"axint\", version: pkg.version },\n { capabilities: { tools: {} } }\n );\n\n // List available tools\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [\n {\n name: \"axint_scaffold\",\n description:\n \"Generate a starter TypeScript intent file using the axint SDK. \" +\n \"Pass a PascalCase name, a description, and optionally a domain \" +\n \"(messaging, productivity, health, finance, commerce, media, \" +\n \"navigation, smart-home) and a list of parameters. Returns ready-\" +\n \"to-save source code that compiles with `axint compile`.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n name: {\n type: \"string\",\n description: \"PascalCase name for the intent, e.g., 'CreateEvent'\",\n },\n description: {\n type: \"string\",\n description: \"Human-readable description of what the intent does\",\n },\n domain: {\n type: \"string\",\n description:\n \"Optional Apple App Intent domain (messaging, productivity, \" +\n \"health, finance, commerce, media, navigation, smart-home)\",\n },\n params: {\n type: \"array\",\n description:\n \"Optional initial parameters. Each item: { name, type, description }. \" +\n \"Supported types: string, int, double, float, boolean, date, duration, url.\",\n items: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n type: { type: \"string\" },\n description: { type: \"string\" },\n },\n required: [\"name\", \"type\", \"description\"],\n },\n },\n },\n required: [\"name\", \"description\"],\n },\n },\n {\n name: \"axint_compile\",\n description:\n \"Compile a TypeScript intent definition into a native Swift App \" +\n \"Intent. Optionally emits Info.plist and entitlements fragments \" +\n \"alongside the Swift file. Pass the full TypeScript source code \" +\n \"using the defineIntent() API.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n source: {\n type: \"string\",\n description: \"TypeScript source code containing a defineIntent() call\",\n },\n fileName: {\n type: \"string\",\n description: \"Optional file name for error messages\",\n },\n emitInfoPlist: {\n type: \"boolean\",\n description:\n \"When true, also returns an Info.plist XML fragment for the \" +\n \"intent's declared infoPlistKeys\",\n },\n emitEntitlements: {\n type: \"boolean\",\n description:\n \"When true, also returns an .entitlements XML fragment for \" +\n \"the intent's declared entitlements\",\n },\n },\n required: [\"source\"],\n },\n },\n {\n name: \"axint_validate\",\n description:\n \"Validate a TypeScript intent definition without generating Swift \" +\n \"output. Returns diagnostics with error codes and fix suggestions.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n source: {\n type: \"string\",\n description: \"TypeScript source code containing a defineIntent() call\",\n },\n },\n required: [\"source\"],\n },\n },\n {\n name: \"axint_list_templates\",\n description:\n \"List the bundled reference templates. Use `axint_template` to \" +\n \"fetch the full source of a specific template by id.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"axint_template\",\n description:\n \"Return the full TypeScript source code of a bundled reference \" +\n \"template by id. Use `axint_list_templates` to discover valid ids.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n id: {\n type: \"string\",\n description: \"Template id (e.g., 'send-message', 'create-event')\",\n },\n },\n required: [\"id\"],\n },\n },\n ],\n }));\n\n // Handle tool calls\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n try {\n if (name === \"axint_scaffold\") {\n const a = args as unknown as ScaffoldArgs;\n const source = scaffoldIntent({\n name: a.name,\n description: a.description,\n domain: a.domain,\n params: a.params,\n });\n return { content: [{ type: \"text\" as const, text: source }] };\n }\n\n if (name === \"axint_compile\") {\n const a = args as unknown as CompileArgs;\n const result = compileSource(a.source, a.fileName || \"<mcp>\", {\n emitInfoPlist: a.emitInfoPlist,\n emitEntitlements: a.emitEntitlements,\n });\n\n if (result.success && result.output) {\n const parts: string[] = [\n \"// ─── Swift ──────────────────────────\",\n result.output.swiftCode,\n ];\n if (result.output.infoPlistFragment) {\n parts.push(\"// ─── Info.plist fragment ────────────\");\n parts.push(result.output.infoPlistFragment);\n }\n if (result.output.entitlementsFragment) {\n parts.push(\"// ─── .entitlements fragment ─────────\");\n parts.push(result.output.entitlementsFragment);\n }\n return {\n content: [{ type: \"text\" as const, text: parts.join(\"\\n\") }],\n };\n }\n\n const errorText = result.diagnostics\n .map((d) => `[${d.code}] ${d.severity}: ${d.message}`)\n .join(\"\\n\");\n return {\n content: [{ type: \"text\" as const, text: errorText }],\n isError: true,\n };\n }\n\n if (name === \"axint_validate\") {\n const a = args as unknown as { source: string };\n const result = compileSource(a.source, \"<validate>\");\n const text =\n result.diagnostics.length > 0\n ? result.diagnostics\n .map((d) => `[${d.code}] ${d.severity}: ${d.message}`)\n .join(\"\\n\")\n : \"Valid intent definition. No issues found.\";\n return { content: [{ type: \"text\" as const, text }] };\n }\n\n if (name === \"axint_list_templates\") {\n const list = TEMPLATES.map(\n (t) => `${t.id} — ${t.title}${t.domain ? ` [${t.domain}]` : \"\"}`\n ).join(\"\\n\");\n return {\n content: [\n {\n type: \"text\" as const,\n text: list || \"No templates registered.\",\n },\n ],\n };\n }\n\n if (name === \"axint_template\") {\n const a = args as unknown as TemplateArgs;\n const tpl = getTemplate(a.id);\n if (!tpl) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Unknown template id: ${a.id}. Use axint_list_templates to see available ids.`,\n },\n ],\n isError: true,\n };\n }\n return { content: [{ type: \"text\" as const, text: tpl.source }] };\n }\n\n return {\n content: [{ type: \"text\" as const, text: `Unknown tool: ${name}` }],\n isError: true,\n };\n } catch (err: unknown) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Tool error: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n isError: true,\n };\n }\n });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n","/**\n * Axint CLI\n *\n * The command-line interface for the Axint compiler.\n *\n * axint init [dir] Scaffold a new Axint project\n * axint compile <file> Compile TS intent → Swift App Intent\n * axint validate <file> Validate a compiled intent\n * axint eject <file> Eject intent to standalone Swift (no vendor lock-in)\n * axint templates List bundled intent templates\n * axint login Authenticate with the Axint Registry\n * axint publish Publish an intent to the Registry\n * axint add <package> Install a template from the Registry\n * axint search [query] Search the Axint Registry for intent templates\n * axint watch <file|dir> Watch intent files and recompile on change\n * axint mcp Start the MCP server (stdio)\n * axint --version Show version\n */\n\nimport { Command } from \"commander\";\nimport {\n readFileSync,\n writeFileSync,\n mkdirSync,\n existsSync,\n watch as fsWatch,\n statSync,\n} from \"node:fs\";\nimport { resolve, dirname, basename } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\nimport { compileFile, compileFromIR, irFromJSON } from \"../core/compiler.js\";\nimport { ejectIntent } from \"../core/eject.js\";\nimport { scaffoldProject } from \"./scaffold.js\";\nimport { listTemplates, getTemplate } from \"../templates/index.js\";\n\n// Read version from package.json so it stays in sync\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(resolve(__dirname, \"../../package.json\"), \"utf-8\"));\nconst VERSION = pkg.version as string;\n\nconst program = new Command();\n\nprogram\n .name(\"axint\")\n .description(\n \"The open-source compiler that transforms AI agent definitions into native Apple App Intents.\"\n )\n .version(VERSION);\n\n// ─── init ────────────────────────────────────────────────────────────\n\nprogram\n .command(\"init\")\n .description(\"Scaffold a new Axint project (zero-config, ready to compile)\")\n .argument(\"[dir]\", \"Project directory (defaults to current dir)\", \".\")\n .option(\n \"-t, --template <name>\",\n \"Starter template (send-message, create-event, book-ride, ...)\",\n \"create-event\"\n )\n .option(\"--no-install\", \"Skip running `npm install`\")\n .option(\"--name <name>\", \"Project name (defaults to the directory name)\")\n .action(\n async (\n dir: string,\n options: { template: string; install: boolean; name?: string }\n ) => {\n const targetDir = resolve(dir);\n const projectName = options.name ?? basename(targetDir);\n\n try {\n const result = await scaffoldProject({\n targetDir,\n projectName,\n template: options.template,\n version: VERSION,\n install: options.install,\n });\n\n console.log();\n console.log(` \\x1b[38;5;208m◆\\x1b[0m \\x1b[1mAxint\\x1b[0m · project ready`);\n console.log();\n console.log(\n ` \\x1b[2m${result.files.length} files written to ${targetDir}\\x1b[0m`\n );\n console.log();\n console.log(` \\x1b[1mNext:\\x1b[0m`);\n if (dir !== \".\") console.log(` cd ${dir}`);\n if (options.install) {\n console.log(\n ` npx axint compile intents/${result.entryFile} --out ios/Intents/`\n );\n } else {\n console.log(` npm install`);\n console.log(\n ` npx axint compile intents/${result.entryFile} --out ios/Intents/`\n );\n }\n console.log();\n console.log(\n ` \\x1b[2mDocs: https://github.com/agenticempire/axint#readme\\x1b[0m`\n );\n console.log(\n ` \\x1b[2mMCP: npx axint-mcp (add to Claude Code, Cursor, Windsurf)\\x1b[0m`\n );\n console.log();\n } catch (err: unknown) {\n console.error(`\\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n process.exit(1);\n }\n }\n );\n\n// ─── compile ─────────────────────────────────────────────────────────\n\nprogram\n .command(\"compile\")\n .description(\"Compile a TypeScript intent definition into Swift\")\n .argument(\"<file>\", \"Path to the TypeScript intent definition\")\n .option(\"-o, --out <dir>\", \"Output directory for generated Swift\", \".\")\n .option(\"--no-validate\", \"Skip validation of generated Swift\")\n .option(\"--stdout\", \"Print generated Swift to stdout instead of writing a file\")\n .option(\"--json\", \"Output result as JSON (machine-readable)\")\n .option(\n \"--emit-info-plist\",\n \"Emit a <Name>.plist.fragment.xml with NSAppIntentsDomains next to the Swift file\"\n )\n .option(\n \"--emit-entitlements\",\n \"Emit a <Name>.entitlements.fragment.xml next to the Swift file\"\n )\n .option(\n \"--sandbox\",\n \"Run stage 4 validation: swift build in an SPM sandbox (macOS only)\"\n )\n .option(\n \"--format\",\n \"Pipe generated Swift through swift-format with the Axint house style (macOS/Linux if swift-format is on $PATH)\"\n )\n .option(\n \"--strict-format\",\n \"Fail the build if swift-format is missing or errors (implies --format)\"\n )\n .option(\n \"--from-ir\",\n \"Treat <file> as IR JSON (from Python SDK or any language) instead of TypeScript. Use - to read from stdin.\"\n )\n .action(\n async (\n file: string,\n options: {\n out: string;\n validate: boolean;\n stdout: boolean;\n json: boolean;\n emitInfoPlist: boolean;\n emitEntitlements: boolean;\n sandbox: boolean;\n format: boolean;\n strictFormat: boolean;\n fromIr: boolean;\n }\n ) => {\n const filePath = resolve(file);\n\n try {\n let result;\n\n if (options.fromIr) {\n // Cross-language bridge: read IR JSON and skip the TS parser\n let irRaw: string;\n if (file === \"-\") {\n // Read from stdin\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n irRaw = Buffer.concat(chunks).toString(\"utf-8\");\n } else {\n irRaw = readFileSync(filePath, \"utf-8\");\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(irRaw);\n } catch {\n console.error(`\\x1b[31merror:\\x1b[0m Invalid JSON in ${file}`);\n process.exit(1);\n }\n\n // Accept both a single IR object and an array (Python SDK emits arrays)\n const irData = Array.isArray(parsed)\n ? (parsed[0] as Record<string, unknown>)\n : (parsed as Record<string, unknown>);\n if (!irData || typeof irData !== \"object\") {\n console.error(\n `\\x1b[31merror:\\x1b[0m Expected an IR object or array in ${file}`\n );\n process.exit(1);\n }\n\n const ir = irFromJSON(irData);\n result = compileFromIR(ir, {\n outDir: options.out,\n validate: options.validate,\n emitInfoPlist: options.emitInfoPlist,\n emitEntitlements: options.emitEntitlements,\n });\n } else {\n result = compileFile(filePath, {\n outDir: options.out,\n validate: options.validate,\n emitInfoPlist: options.emitInfoPlist,\n emitEntitlements: options.emitEntitlements,\n });\n }\n\n // JSON mode — output everything as structured JSON and exit\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n success: result.success,\n swift: result.output?.swiftCode ?? null,\n outputPath: result.output?.outputPath ?? null,\n infoPlistFragment: result.output?.infoPlistFragment ?? null,\n entitlementsFragment: result.output?.entitlementsFragment ?? null,\n diagnostics: result.diagnostics.map((d) => ({\n code: d.code,\n severity: d.severity,\n message: d.message,\n file: d.file,\n line: d.line,\n suggestion: d.suggestion,\n })),\n },\n null,\n 2\n )\n );\n if (!result.success) process.exit(1);\n return;\n }\n\n // Print diagnostics\n for (const d of result.diagnostics) {\n const prefix =\n d.severity === \"error\"\n ? \"\\x1b[31merror\\x1b[0m\"\n : d.severity === \"warning\"\n ? \"\\x1b[33mwarning\\x1b[0m\"\n : \"\\x1b[36minfo\\x1b[0m\";\n\n console.error(` ${prefix}[${d.code}]: ${d.message}`);\n if (d.file) console.error(` --> ${d.file}${d.line ? `:${d.line}` : \"\"}`);\n if (d.suggestion) console.error(` = help: ${d.suggestion}`);\n console.error();\n }\n\n if (!result.success || !result.output) {\n console.error(\n `\\x1b[31mCompilation failed with ${result.diagnostics.filter((d) => d.severity === \"error\").length} error(s)\\x1b[0m`\n );\n process.exit(1);\n }\n\n // Optional swift-format pass — mutate the swiftCode in place before writing\n if (options.format || options.strictFormat) {\n try {\n const { formatSwift } = await import(\"../core/format.js\");\n const fmt = await formatSwift(result.output.swiftCode, {\n strict: options.strictFormat,\n });\n if (fmt.ran) {\n result.output.swiftCode = fmt.formatted;\n } else if (!options.json) {\n console.error(\n `\\x1b[33mwarning:\\x1b[0m swift-format skipped — ${fmt.reason}`\n );\n }\n } catch (fmtErr: unknown) {\n if (options.strictFormat) {\n console.error(`\\x1b[31merror:\\x1b[0m ${(fmtErr as Error).message}`);\n process.exit(1);\n }\n console.error(\n `\\x1b[33mwarning:\\x1b[0m swift-format skipped — ${(fmtErr as Error).message}`\n );\n }\n }\n\n if (options.stdout) {\n console.log(result.output.swiftCode);\n } else {\n const outPath = resolve(result.output.outputPath);\n mkdirSync(dirname(outPath), { recursive: true });\n writeFileSync(outPath, result.output.swiftCode, \"utf-8\");\n console.log(`\\x1b[32m✓\\x1b[0m Compiled ${result.output.ir.name} → ${outPath}`);\n\n // Emit optional fragments next to the Swift file\n if (options.emitInfoPlist && result.output.infoPlistFragment) {\n const plistPath = outPath.replace(/\\.swift$/, \".plist.fragment.xml\");\n writeFileSync(plistPath, result.output.infoPlistFragment, \"utf-8\");\n console.log(`\\x1b[32m✓\\x1b[0m Info.plist fragment → ${plistPath}`);\n }\n\n if (options.emitEntitlements && result.output.entitlementsFragment) {\n const entPath = outPath.replace(/\\.swift$/, \".entitlements.fragment.xml\");\n writeFileSync(entPath, result.output.entitlementsFragment, \"utf-8\");\n console.log(`\\x1b[32m✓\\x1b[0m Entitlements fragment → ${entPath}`);\n }\n }\n\n // Stage 4 validation: SPM sandbox compile\n if (options.sandbox && !options.stdout) {\n try {\n const { sandboxCompile } = await import(\"../core/sandbox.js\");\n console.log();\n console.log(`\\x1b[36m→\\x1b[0m Stage 4: SPM sandbox compile...`);\n const sandboxResult = await sandboxCompile(result.output.swiftCode, {\n intentName: result.output.ir.name,\n });\n if (sandboxResult.ok) {\n console.log(\n `\\x1b[32m✓\\x1b[0m Swift builds cleanly (${sandboxResult.durationMs}ms in ${sandboxResult.sandboxPath})`\n );\n } else {\n console.error(\n `\\x1b[31m✗\\x1b[0m Sandbox compile failed:\\n${sandboxResult.stderr}`\n );\n process.exit(1);\n }\n } catch (sbErr: unknown) {\n console.error(\n `\\x1b[33mwarning:\\x1b[0m sandbox compile skipped — ${(sbErr as Error).message}`\n );\n }\n }\n\n const warnings = result.diagnostics.filter(\n (d) => d.severity === \"warning\"\n ).length;\n if (warnings > 0) {\n console.log(` ${warnings} warning(s)`);\n }\n } catch (err: unknown) {\n if (\n err &&\n typeof err === \"object\" &&\n \"format\" in err &&\n typeof (err as Record<string, unknown>).format === \"function\"\n ) {\n console.error((err as { format: () => string }).format());\n } else {\n console.error(`\\x1b[31merror:\\x1b[0m ${err}`);\n }\n process.exit(1);\n }\n }\n );\n\n// ─── validate ────────────────────────────────────────────────────────\n\nprogram\n .command(\"validate\")\n .description(\"Validate a TypeScript intent definition without generating output\")\n .argument(\"<file>\", \"Path to the TypeScript intent definition\")\n .option(\n \"--sandbox\",\n \"Run stage 4 validation: swift build in an SPM sandbox (macOS only)\"\n )\n .action(async (file: string, options: { sandbox: boolean }) => {\n const filePath = resolve(file);\n\n try {\n const result = compileFile(filePath, { validate: true });\n\n for (const d of result.diagnostics) {\n const prefix =\n d.severity === \"error\"\n ? \"\\x1b[31merror\\x1b[0m\"\n : d.severity === \"warning\"\n ? \"\\x1b[33mwarning\\x1b[0m\"\n : \"\\x1b[36minfo\\x1b[0m\";\n console.error(` ${prefix}[${d.code}]: ${d.message}`);\n if (d.suggestion) console.error(` = help: ${d.suggestion}`);\n }\n\n if (!result.success) {\n process.exit(1);\n }\n\n if (options.sandbox && result.output) {\n const { sandboxCompile } = await import(\"../core/sandbox.js\");\n console.log(`\\x1b[36m→\\x1b[0m Stage 4: SPM sandbox compile...`);\n const sandboxResult = await sandboxCompile(result.output.swiftCode, {\n intentName: result.output.ir.name,\n });\n if (!sandboxResult.ok) {\n console.error(`\\x1b[31m✗\\x1b[0m ${sandboxResult.stderr}`);\n process.exit(1);\n }\n console.log(\n `\\x1b[32m✓\\x1b[0m Valid intent definition (sandbox-verified, ${sandboxResult.durationMs}ms)`\n );\n } else {\n console.log(`\\x1b[32m✓\\x1b[0m Valid intent definition`);\n }\n } catch (err: unknown) {\n if (\n err &&\n typeof err === \"object\" &&\n \"format\" in err &&\n typeof (err as Record<string, unknown>).format === \"function\"\n ) {\n console.error((err as { format: () => string }).format());\n } else {\n console.error(`\\x1b[31merror:\\x1b[0m ${err}`);\n }\n process.exit(1);\n }\n });\n\n// ─── eject ──────────────────────────────────────────────────────────\n\nprogram\n .command(\"eject\")\n .description(\"Eject an intent to standalone Swift with no Axint dependency\")\n .argument(\"<file>\", \"Path to the TypeScript intent definition\")\n .option(\"-o, --out <dir>\", \"Output directory for ejected files\", \".\")\n .option(\"--include-tests\", \"Generate a basic XCTest file alongside the Swift\")\n .option(\n \"--format\",\n \"Pipe generated Swift through swift-format with the Axint house style (macOS/Linux if swift-format is on $PATH)\"\n )\n .action(\n async (\n file: string,\n options: {\n out: string;\n includeTests: boolean;\n format: boolean;\n }\n ) => {\n const filePath = resolve(file);\n\n try {\n // Read source\n let source: string;\n try {\n source = readFileSync(filePath, \"utf-8\");\n } catch (_err) {\n console.error(`\\x1b[31merror:\\x1b[0m Cannot read file: ${filePath}`);\n process.exit(1);\n }\n\n // Eject\n const result = await ejectIntent(source, basename(filePath), {\n outDir: options.out,\n includeTests: options.includeTests,\n format: options.format,\n });\n\n // Write all files\n const filesWritten: string[] = [];\n\n // Swift file\n mkdirSync(dirname(result.swiftFile.path), { recursive: true });\n writeFileSync(result.swiftFile.path, result.swiftFile.content, \"utf-8\");\n filesWritten.push(\"Swift\");\n\n // Optional Info.plist fragment\n if (result.infoPlist) {\n writeFileSync(result.infoPlist.path, result.infoPlist.content, \"utf-8\");\n filesWritten.push(\"Info.plist fragment\");\n }\n\n // Optional entitlements fragment\n if (result.entitlements) {\n writeFileSync(result.entitlements.path, result.entitlements.content, \"utf-8\");\n filesWritten.push(\"entitlements fragment\");\n }\n\n // Optional test file\n if (result.testFile) {\n writeFileSync(result.testFile.path, result.testFile.content, \"utf-8\");\n filesWritten.push(\"XCTest file\");\n }\n\n // Success message\n console.log();\n console.log(\n `\\x1b[32m✓\\x1b[0m Ejected → ${filesWritten.length} file(s) (${filesWritten.join(\", \")})`\n );\n console.log();\n console.log(` \\x1b[1mOutput directory:\\x1b[0m ${resolve(options.out)}`);\n console.log();\n console.log(` These files are now standalone and have no Axint dependency.`);\n console.log(\n ` You can commit them to version control and use them in your project.`\n );\n console.log();\n } catch (err: unknown) {\n if (\n err &&\n typeof err === \"object\" &&\n \"format\" in err &&\n typeof (err as Record<string, unknown>).format === \"function\"\n ) {\n console.error((err as { format: () => string }).format());\n } else {\n console.error(`\\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n }\n process.exit(1);\n }\n }\n );\n\n// ─── templates ───────────────────────────────────────────────────────\n\nprogram\n .command(\"templates\")\n .description(\"List bundled intent templates\")\n .argument(\"[name]\", \"Template name to print (omit to list all)\")\n .option(\"--json\", \"Output as JSON\")\n .action((name: string | undefined, options: { json: boolean }) => {\n if (!name) {\n const list = listTemplates();\n if (options.json) {\n console.log(JSON.stringify(list, null, 2));\n return;\n }\n console.log(` \\x1b[1mBundled templates\\x1b[0m (${list.length})`);\n console.log();\n for (const t of list) {\n console.log(\n ` \\x1b[38;5;208m◆\\x1b[0m ${t.name} \\x1b[2m— ${t.description}\\x1b[0m`\n );\n }\n console.log();\n console.log(\n ` \\x1b[2mUse: axint templates <name> or axint init -t <name>\\x1b[0m`\n );\n return;\n }\n\n const tpl = getTemplate(name);\n if (!tpl) {\n console.error(`\\x1b[31merror:\\x1b[0m template \"${name}\" not found`);\n process.exit(1);\n }\n if (options.json) {\n console.log(JSON.stringify(tpl, null, 2));\n return;\n }\n console.log(tpl.source);\n });\n\n// ─── login ──────────────────────────────────────────────────────────\n//\n// Device-code flow for CLI auth against registry.axint.ai.\n// Opens the browser to complete GitHub OAuth, polls for the token,\n// stores it in ~/.axint/credentials.json.\n\nprogram\n .command(\"login\")\n .description(\"Authenticate with the Axint Registry via GitHub\")\n .action(async () => {\n const { homedir } = await import(\"node:os\");\n const { join } = await import(\"node:path\");\n const { spawn } = await import(\"node:child_process\");\n\n const configDir = join(homedir(), \".axint\");\n const credPath = join(configDir, \"credentials.json\");\n const registryUrl = process.env.AXINT_REGISTRY_URL ?? \"https://registry.axint.ai\";\n\n console.log();\n console.log(` \\x1b[38;5;208m◆\\x1b[0m \\x1b[1mAxint\\x1b[0m · login`);\n console.log();\n\n try {\n // Request a device code from the registry\n const res = await fetch(`${registryUrl}/api/v1/auth/device-code`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: \"axint-cli\" }),\n });\n\n if (!res.ok) {\n console.error(\n `\\x1b[31merror:\\x1b[0m Failed to start login flow (HTTP ${res.status})`\n );\n process.exit(1);\n }\n\n const { device_code, user_code, verification_uri, interval } =\n (await res.json()) as {\n device_code: string;\n user_code: string;\n verification_uri: string;\n interval: number;\n };\n\n console.log(` Open this URL in your browser:`);\n console.log();\n console.log(` \\x1b[1;4m${verification_uri}\\x1b[0m`);\n console.log();\n console.log(` And enter this code: \\x1b[1;38;5;208m${user_code}\\x1b[0m`);\n console.log();\n console.log(` \\x1b[2mWaiting for authorization…\\x1b[0m`);\n\n // Best-effort browser open — spawn with array args to avoid shell injection\n try {\n const openCmd =\n process.platform === \"darwin\"\n ? \"open\"\n : process.platform === \"win32\"\n ? \"start\"\n : \"xdg-open\";\n spawn(openCmd, [verification_uri], { stdio: \"ignore\", detached: true }).unref();\n } catch {\n // non-blocking — user can open the URL manually\n }\n\n // Poll for the token\n const pollInterval = (interval ?? 5) * 1000;\n let token: string | null = null;\n\n for (let i = 0; i < 60; i++) {\n await new Promise((r) => setTimeout(r, pollInterval));\n\n const pollRes = await fetch(`${registryUrl}/api/v1/auth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ device_code, grant_type: \"device_code\" }),\n });\n\n if (pollRes.ok) {\n const data = (await pollRes.json()) as { access_token: string };\n token = data.access_token;\n break;\n }\n\n const err = (await pollRes.json()) as { error?: string };\n if (err.error === \"authorization_pending\") continue;\n if (err.error === \"slow_down\") {\n await new Promise((r) => setTimeout(r, 5000));\n continue;\n }\n if (err.error === \"expired_token\") {\n console.error(\n `\\x1b[31merror:\\x1b[0m Login timed out. Run \\`axint login\\` again.`\n );\n process.exit(1);\n }\n console.error(`\\x1b[31merror:\\x1b[0m ${err.error ?? \"Unknown error\"}`);\n process.exit(1);\n }\n\n if (!token) {\n console.error(`\\x1b[31merror:\\x1b[0m Login timed out after 5 minutes.`);\n process.exit(1);\n }\n\n // Save credentials\n mkdirSync(configDir, { recursive: true });\n writeFileSync(\n credPath,\n JSON.stringify({ access_token: token, registry: registryUrl }, null, 2),\n \"utf-8\"\n );\n\n console.log(\n ` \\x1b[32m✓\\x1b[0m Logged in! Credentials saved to \\x1b[2m${credPath}\\x1b[0m`\n );\n console.log();\n } catch (err: unknown) {\n console.error(`\\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n process.exit(1);\n }\n });\n\n// ─── publish ────────────────────────────────────────────────────────\n//\n// Reads axint.json from the current directory, compiles the intent,\n// and publishes it to registry.axint.ai.\n\nprogram\n .command(\"publish\")\n .description(\"Publish an intent to the Axint Registry\")\n .option(\"--dry-run\", \"Validate and show what would be published without uploading\")\n .option(\"--tag <tags...>\", \"Override tags\")\n .action(async (options: { dryRun?: boolean; tag?: string[] }) => {\n const cwd = process.cwd();\n const configPath = resolve(cwd, \"axint.json\");\n\n console.log();\n console.log(` \\x1b[38;5;208m◆\\x1b[0m \\x1b[1mAxint\\x1b[0m · publish`);\n console.log();\n\n // 1. Read axint.json\n if (!existsSync(configPath)) {\n console.error(` \\x1b[31merror:\\x1b[0m No axint.json found in ${cwd}`);\n console.error(` \\x1b[2mRun \\`axint init\\` to create one.\\x1b[0m`);\n process.exit(1);\n }\n\n let config: {\n name: string;\n namespace: string;\n slug: string;\n version: string;\n description?: string;\n primary_language?: string;\n surface_areas?: string[];\n tags?: string[];\n license?: string;\n homepage?: string;\n repository?: string;\n entry?: string;\n readme?: string;\n siri_phrases?: string[];\n permissions?: string[];\n };\n\n try {\n config = JSON.parse(readFileSync(configPath, \"utf-8\"));\n } catch {\n console.error(` \\x1b[31merror:\\x1b[0m Failed to parse axint.json`);\n process.exit(1);\n }\n\n const entryFile = config.entry ?? \"intent.ts\";\n const entryPath = resolve(cwd, entryFile);\n\n if (!existsSync(entryPath)) {\n console.error(` \\x1b[31merror:\\x1b[0m Entry file not found: ${entryFile}`);\n process.exit(1);\n }\n\n console.log(` \\x1b[2m⏺\\x1b[0m Compiling ${entryFile}…`);\n\n // 2. Compile\n let result: Awaited<ReturnType<typeof compileFile>>;\n try {\n result = await compileFile(entryPath, {});\n } catch (err: unknown) {\n console.error(` \\x1b[31m✗\\x1b[0m Compilation failed: ${(err as Error).message}`);\n process.exit(1);\n }\n\n if (!result.success || !result.output) {\n console.error(` \\x1b[31m✗\\x1b[0m Compilation failed`);\n for (const d of result.diagnostics) {\n console.error(` [${d.code}] ${d.message}`);\n }\n process.exit(1);\n }\n\n console.log(\n ` \\x1b[32m✓\\x1b[0m Compiled → ${result.output.swiftCode.split(\"\\n\").length} lines of Swift`\n );\n\n // 3. Read optional files\n let readme: string | undefined;\n const readmePath = resolve(cwd, config.readme ?? \"README.md\");\n if (existsSync(readmePath)) {\n readme = readFileSync(readmePath, \"utf-8\");\n }\n\n let pySource: string | undefined;\n const pyPath = resolve(cwd, entryFile.replace(/\\.ts$/, \".py\"));\n if (existsSync(pyPath)) {\n pySource = readFileSync(pyPath, \"utf-8\");\n }\n\n const tags = options.tag ?? config.tags ?? [];\n const namespace = config.namespace.startsWith(\"@\")\n ? config.namespace\n : `@${config.namespace}`;\n\n const payload = {\n namespace,\n slug: config.slug,\n name: config.name,\n version: config.version,\n description: config.description,\n readme,\n primary_language: config.primary_language ?? (pySource ? \"both\" : \"typescript\"),\n surface_areas: config.surface_areas ?? [],\n tags,\n license: config.license ?? \"Apache-2.0\",\n homepage: config.homepage,\n repository: config.repository,\n ts_source: readFileSync(entryPath, \"utf-8\"),\n py_source: pySource,\n swift_output: result.output.swiftCode,\n plist_fragment: result.output.infoPlistFragment ?? null,\n ir: result.output.ir ?? {},\n compiler_version: VERSION,\n };\n\n if (options.dryRun) {\n console.log(` \\x1b[32m✓\\x1b[0m Validation passed`);\n console.log();\n console.log(\n ` Would publish: \\x1b[1m${namespace}/${config.slug}@${config.version}\\x1b[0m`\n );\n console.log(\n ` Bundle size: ${Buffer.from(JSON.stringify(payload)).byteLength} bytes`\n );\n console.log(` Tags: ${tags.join(\", \") || \"(none)\"}`);\n console.log();\n return;\n }\n\n // 4. Load credentials\n const { homedir } = await import(\"node:os\");\n const { join } = await import(\"node:path\");\n const credPath = join(homedir(), \".axint\", \"credentials.json\");\n\n if (!existsSync(credPath)) {\n console.error(` \\x1b[31merror:\\x1b[0m Not logged in. Run \\`axint login\\` first.`);\n process.exit(1);\n }\n\n let creds: { access_token: string; registry: string };\n try {\n creds = JSON.parse(readFileSync(credPath, \"utf-8\"));\n } catch {\n console.error(\n ` \\x1b[31merror:\\x1b[0m Corrupt credentials file. Run \\`axint login\\` again.`\n );\n process.exit(1);\n }\n\n const registryUrl = creds.registry ?? \"https://registry.axint.ai\";\n\n console.log(` \\x1b[2m⏺\\x1b[0m Publishing to ${registryUrl}…`);\n\n // 5. Publish\n try {\n const res = await fetch(`${registryUrl}/api/v1/publish`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${creds.access_token}`,\n \"X-Axint-Version\": VERSION,\n },\n body: JSON.stringify(payload),\n });\n\n if (!res.ok) {\n const err = (await res.json().catch(() => ({ detail: res.statusText }))) as {\n detail?: string;\n title?: string;\n };\n console.error(\n ` \\x1b[31m✗\\x1b[0m ${err.title ?? \"Publish failed\"}: ${err.detail ?? res.statusText}`\n );\n process.exit(1);\n }\n\n const data = (await res.json()) as { url: string };\n\n console.log(` \\x1b[32m✓\\x1b[0m Published!`);\n console.log();\n console.log(` ${data.url}`);\n console.log();\n console.log(` \\x1b[2mInstall: axint add ${namespace}/${config.slug}\\x1b[0m`);\n console.log();\n } catch (err: unknown) {\n console.error(` \\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n process.exit(1);\n }\n });\n\n// ─── add ────────────────────────────────────────────────────────────\n//\n// Install a template from the Axint Registry.\n// Usage: axint add @namespace/slug[@version] [--to dir]\n\nprogram\n .command(\"add\")\n .description(\"Install a template from the Axint Registry\")\n .argument(\n \"<package>\",\n \"Template to install (e.g., @axintai/create-event or @axintai/create-event@1.0.0)\"\n )\n .option(\"--to <dir>\", \"Target directory\", \"intents\")\n .action(async (pkg: string, options: { to: string }) => {\n console.log();\n console.log(` \\x1b[38;5;208m◆\\x1b[0m \\x1b[1mAxint\\x1b[0m · add`);\n console.log();\n\n // Parse @namespace/slug@version\n const match = pkg.match(/^(@[a-z0-9][a-z0-9-]*)\\/([a-z0-9][a-z0-9-]*)(?:@(.+))?$/);\n if (!match) {\n console.error(\n ` \\x1b[31merror:\\x1b[0m Invalid package format. Expected: @namespace/slug or @namespace/slug@version`\n );\n process.exit(1);\n }\n\n const [, namespace, slug, version] = match;\n const registryUrl = process.env.AXINT_REGISTRY_URL ?? \"https://registry.axint.ai\";\n\n console.log(\n ` \\x1b[2m⏺\\x1b[0m Fetching ${namespace}/${slug}${version ? `@${version}` : \"\"}…`\n );\n\n try {\n const params = new URLSearchParams({ namespace, slug });\n if (version) params.set(\"version\", version);\n\n const res = await fetch(`${registryUrl}/api/v1/install?${params}`, {\n headers: { \"X-Axint-Version\": VERSION },\n });\n\n if (!res.ok) {\n const err = (await res.json().catch(() => ({ detail: res.statusText }))) as {\n detail?: string;\n };\n console.error(\n ` \\x1b[31m✗\\x1b[0m ${err.detail ?? `Template not found (HTTP ${res.status})`}`\n );\n process.exit(1);\n }\n\n const data = (await res.json()) as {\n template: { name: string; full_name: string; primary_language: string };\n version: {\n version: string;\n ts_source?: string;\n py_source?: string;\n swift_output: string;\n };\n bundle_sha256: string;\n };\n\n const targetDir = resolve(options.to, slug);\n mkdirSync(targetDir, { recursive: true });\n\n // Write source files\n const ver = data.version;\n const filesWritten: string[] = [];\n\n if (ver.ts_source) {\n writeFileSync(resolve(targetDir, \"intent.ts\"), ver.ts_source, \"utf-8\");\n filesWritten.push(\"intent.ts\");\n }\n if (ver.py_source) {\n writeFileSync(resolve(targetDir, \"intent.py\"), ver.py_source, \"utf-8\");\n filesWritten.push(\"intent.py\");\n }\n writeFileSync(resolve(targetDir, \"intent.swift\"), ver.swift_output, \"utf-8\");\n filesWritten.push(\"intent.swift\");\n\n console.log(\n ` \\x1b[32m✓\\x1b[0m Installed ${data.template.full_name}@${ver.version}`\n );\n console.log(` → ${targetDir}/`);\n filesWritten.forEach((f) => console.log(` ${f}`));\n console.log();\n console.log(` \\x1b[1mNext:\\x1b[0m`);\n console.log(` axint compile ${options.to}/${slug}/intent.ts --out ios/Intents/`);\n console.log();\n } catch (err: unknown) {\n console.error(` \\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n process.exit(1);\n }\n });\n\n// ─── search ──────────────────────────────────────────────────────────\n\nprogram\n .command(\"search\")\n .description(\"Search the Axint Registry for intent templates\")\n .argument(\"[query]\", \"Search term (lists popular packages if omitted)\")\n .option(\"--limit <n>\", \"Max results\", \"20\")\n .option(\"--json\", \"Output as JSON\")\n .action(\n async (query: string | undefined, options: { limit: string; json: boolean }) => {\n const registryUrl = process.env.AXINT_REGISTRY_URL ?? \"https://registry.axint.ai\";\n const limit = Math.max(1, Math.min(100, parseInt(options.limit, 10) || 20));\n\n console.log();\n if (!options.json) {\n console.log(\n ` \\x1b[38;5;208m◆\\x1b[0m \\x1b[1mAxint\\x1b[0m · search ${query ? `\"${query}\"` : \"\"}`\n );\n console.log();\n }\n\n try {\n const params = new URLSearchParams({ limit: String(limit) });\n if (query) params.set(\"q\", query);\n\n const res = await fetch(`${registryUrl}/api/v1/search?${params}`, {\n headers: { \"X-Axint-Version\": VERSION },\n });\n\n if (!res.ok) {\n console.error(`\\x1b[31merror:\\x1b[0m Search failed (HTTP ${res.status})`);\n process.exit(1);\n }\n\n const data = (await res.json()) as {\n results: {\n package_name: string;\n name: string;\n description: string;\n downloads: number;\n }[];\n total: number;\n };\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2));\n return;\n }\n\n if (data.results.length === 0) {\n console.log(` No packages found`);\n console.log();\n return;\n }\n\n for (const pkg of data.results) {\n const downloads = pkg.downloads > 0 ? `▼ ${pkg.downloads}` : \"\";\n const dl = downloads ? ` \\x1b[2m${downloads}\\x1b[0m` : \"\";\n console.log(\n ` \\x1b[38;5;208m◆\\x1b[0m ${pkg.package_name.padEnd(30)} ${pkg.description.substring(0, 35).padEnd(35)}${dl}`\n );\n }\n console.log();\n console.log(\n ` ${data.results.length} package${data.results.length === 1 ? \"\" : \"s\"} found`\n );\n console.log();\n console.log(\n ` \\x1b[2mInstall:\\x1b[0m axint add ${data.results[0]?.package_name ?? \"@namespace/slug\"}`\n );\n console.log();\n } catch (err: unknown) {\n console.error(`\\x1b[31merror:\\x1b[0m ${(err as Error).message ?? err}`);\n process.exit(1);\n }\n }\n );\n\n// ─── watch ───────────────────────────────────────────────────────────\n\nasync function runSwiftBuild(projectPath: string): Promise<boolean> {\n return new Promise((resolve) => {\n const t0 = performance.now();\n const proc = spawn(\"swift\", [\"build\"], {\n cwd: projectPath,\n stdio: [\"ignore\", \"inherit\", \"inherit\"],\n });\n\n proc.on(\"close\", (code) => {\n if (code === 0) {\n const dt = (performance.now() - t0).toFixed(0);\n console.log();\n console.log(`\\x1b[38;5;208m─ swift build\\x1b[0m`);\n console.log(`\\x1b[32m✓\\x1b[0m Build succeeded \\x1b[90m(${dt}ms)\\x1b[0m`);\n console.log();\n resolve(true);\n } else {\n console.log();\n console.log(`\\x1b[38;5;208m─ swift build\\x1b[0m`);\n console.log(`\\x1b[31m✗\\x1b[0m Build failed (exit code: ${code})`);\n console.log(\"\\x1b[90mContinuing to watch for changes…\\x1b[0m\");\n console.log();\n resolve(false);\n }\n });\n\n proc.on(\"error\", (err) => {\n console.log();\n console.log(`\\x1b[38;5;208m─ swift build\\x1b[0m`);\n console.error(`\\x1b[31m✗\\x1b[0m Error: ${err.message}`);\n console.log(\"\\x1b[90mContinuing to watch for changes…\\x1b[0m\");\n console.log();\n resolve(false);\n });\n });\n}\n\nprogram\n .command(\"watch\")\n .description(\"Watch intent files and recompile on change\")\n .argument(\"<file>\", \"Path to a TypeScript intent file or directory of intents\")\n .option(\"-o, --out <dir>\", \"Output directory for generated Swift\", \".\")\n .option(\"--no-validate\", \"Skip validation of generated Swift\")\n .option(\"--emit-info-plist\", \"Emit Info.plist fragments alongside Swift files\")\n .option(\"--emit-entitlements\", \"Emit entitlements fragments alongside Swift files\")\n .option(\"--format\", \"Pipe generated Swift through swift-format\")\n .option(\n \"--strict-format\",\n \"Fail if swift-format is missing or errors (implies --format)\"\n )\n .option(\n \"--swift-build\",\n \"Run `swift build` in the project after successful compilation\"\n )\n .option(\n \"--swift-project <path>\",\n \"Path to the Swift project root (defaults to --out parent directory)\"\n )\n .action(\n async (\n file: string,\n options: {\n out: string;\n validate: boolean;\n emitInfoPlist: boolean;\n emitEntitlements: boolean;\n format: boolean;\n strictFormat: boolean;\n swiftBuild: boolean;\n swiftProject?: string;\n }\n ) => {\n const target = resolve(file);\n const isDir = existsSync(target) && statSync(target).isDirectory();\n const filesToWatch: string[] = [];\n\n if (isDir) {\n // Collect all .ts files in the directory (non-recursive, skip .d.ts)\n const { readdirSync } = await import(\"node:fs\");\n for (const entry of readdirSync(target)) {\n if (entry.endsWith(\".ts\") && !entry.endsWith(\".d.ts\")) {\n filesToWatch.push(resolve(target, entry));\n }\n }\n if (filesToWatch.length === 0) {\n console.error(`\\x1b[31merror:\\x1b[0m No .ts files found in ${target}`);\n process.exit(1);\n }\n } else {\n if (!existsSync(target)) {\n console.error(`\\x1b[31merror:\\x1b[0m File not found: ${target}`);\n process.exit(1);\n }\n filesToWatch.push(target);\n }\n\n // Determine swift project path\n const swiftProjectPath = options.swiftProject ?? dirname(resolve(options.out));\n\n function compileOne(filePath: string): boolean {\n const t0 = performance.now();\n const result = compileFile(filePath, {\n outDir: options.out,\n validate: options.validate,\n emitInfoPlist: options.emitInfoPlist,\n emitEntitlements: options.emitEntitlements,\n });\n\n for (const d of result.diagnostics) {\n const prefix =\n d.severity === \"error\"\n ? \"\\x1b[31merror\\x1b[0m\"\n : d.severity === \"warning\"\n ? \"\\x1b[33mwarning\\x1b[0m\"\n : \"\\x1b[36minfo\\x1b[0m\";\n console.error(` ${prefix}[${d.code}]: ${d.message}`);\n if (d.file) console.error(` --> ${d.file}${d.line ? `:${d.line}` : \"\"}`);\n if (d.suggestion) console.error(` = help: ${d.suggestion}`);\n }\n\n if (!result.success || !result.output) {\n const errors = result.diagnostics.filter((d) => d.severity === \"error\").length;\n console.error(`\\x1b[31m✗\\x1b[0m ${basename(filePath)} — ${errors} error(s)`);\n return false;\n }\n\n const swiftCode = result.output.swiftCode;\n\n // Apply swift-format synchronously if requested (async import cached after first run)\n if (options.format || options.strictFormat) {\n // swift-format is async — we handle it in the wrapper\n }\n\n const outPath = resolve(result.output.outputPath);\n mkdirSync(dirname(outPath), { recursive: true });\n writeFileSync(outPath, swiftCode, \"utf-8\");\n\n if (options.emitInfoPlist && result.output.infoPlistFragment) {\n const plistPath = outPath.replace(/\\.swift$/, \".plist.fragment.xml\");\n writeFileSync(plistPath, result.output.infoPlistFragment, \"utf-8\");\n }\n if (options.emitEntitlements && result.output.entitlementsFragment) {\n const entPath = outPath.replace(/\\.swift$/, \".entitlements.fragment.xml\");\n writeFileSync(entPath, result.output.entitlementsFragment, \"utf-8\");\n }\n\n const dt = (performance.now() - t0).toFixed(1);\n console.log(\n `\\x1b[32m✓\\x1b[0m ${result.output.ir.name} → ${outPath} \\x1b[90m(${dt}ms)\\x1b[0m`\n );\n return true;\n }\n\n async function compileWithFormat(filePath: string): Promise<boolean> {\n if (!options.format && !options.strictFormat) {\n return compileOne(filePath);\n }\n\n // For format mode, compile then format the output file\n const t0 = performance.now();\n const result = compileFile(filePath, {\n outDir: options.out,\n validate: options.validate,\n emitInfoPlist: options.emitInfoPlist,\n emitEntitlements: options.emitEntitlements,\n });\n\n for (const d of result.diagnostics) {\n const prefix =\n d.severity === \"error\"\n ? \"\\x1b[31merror\\x1b[0m\"\n : d.severity === \"warning\"\n ? \"\\x1b[33mwarning\\x1b[0m\"\n : \"\\x1b[36minfo\\x1b[0m\";\n console.error(` ${prefix}[${d.code}]: ${d.message}`);\n if (d.file) console.error(` --> ${d.file}${d.line ? `:${d.line}` : \"\"}`);\n if (d.suggestion) console.error(` = help: ${d.suggestion}`);\n }\n\n if (!result.success || !result.output) {\n const errors = result.diagnostics.filter((d) => d.severity === \"error\").length;\n console.error(`\\x1b[31m✗\\x1b[0m ${basename(filePath)} — ${errors} error(s)`);\n return false;\n }\n\n let swiftCode = result.output.swiftCode;\n try {\n const { formatSwift } = await import(\"../core/format.js\");\n const fmt = await formatSwift(swiftCode, { strict: options.strictFormat });\n if (fmt.ran) swiftCode = fmt.formatted;\n } catch (fmtErr: unknown) {\n if (options.strictFormat) {\n console.error(`\\x1b[31merror:\\x1b[0m ${(fmtErr as Error).message}`);\n return false;\n }\n }\n\n const outPath = resolve(result.output.outputPath);\n mkdirSync(dirname(outPath), { recursive: true });\n writeFileSync(outPath, swiftCode, \"utf-8\");\n\n if (options.emitInfoPlist && result.output.infoPlistFragment) {\n writeFileSync(\n outPath.replace(/\\.swift$/, \".plist.fragment.xml\"),\n result.output.infoPlistFragment,\n \"utf-8\"\n );\n }\n if (options.emitEntitlements && result.output.entitlementsFragment) {\n writeFileSync(\n outPath.replace(/\\.swift$/, \".entitlements.fragment.xml\"),\n result.output.entitlementsFragment,\n \"utf-8\"\n );\n }\n\n const dt = (performance.now() - t0).toFixed(1);\n console.log(\n `\\x1b[32m✓\\x1b[0m ${result.output.ir.name} → ${outPath} \\x1b[90m(${dt}ms)\\x1b[0m`\n );\n return true;\n }\n\n // Initial compile pass\n console.log(`\\x1b[1maxint watch\\x1b[0m — ${filesToWatch.length} file(s)\\n`);\n let ok = 0;\n let fail = 0;\n for (const f of filesToWatch) {\n if (await compileWithFormat(f)) {\n ok++;\n } else {\n fail++;\n }\n }\n console.log();\n if (fail > 0) {\n console.log(\n `\\x1b[33m⚠\\x1b[0m ${ok} compiled, ${fail} failed — watching for changes…\\n`\n );\n } else {\n console.log(`\\x1b[32m✓\\x1b[0m ${ok} compiled — watching for changes…\\n`);\n if (options.swiftBuild) {\n await runSwiftBuild(swiftProjectPath);\n }\n }\n\n // Set up file watchers with debounce\n const pending = new Map<string, ReturnType<typeof setTimeout>>();\n const DEBOUNCE_MS = 150;\n let batchInProgress = false;\n\n function onFileChange(filePath: string) {\n const existing = pending.get(filePath);\n if (existing) clearTimeout(existing);\n pending.set(\n filePath,\n setTimeout(async () => {\n pending.delete(filePath);\n if (batchInProgress) return;\n\n batchInProgress = true;\n try {\n const now = new Date().toLocaleTimeString();\n console.log(`\\x1b[90m[${now}]\\x1b[0m ${basename(filePath)} changed`);\n const compiled = await compileWithFormat(filePath);\n console.log();\n if (compiled && options.swiftBuild) {\n await runSwiftBuild(swiftProjectPath);\n }\n } finally {\n batchInProgress = false;\n }\n }, DEBOUNCE_MS)\n );\n }\n\n if (isDir) {\n // Watch the entire directory for .ts file changes\n const dirWatcher = fsWatch(target, { persistent: true }, (_event, filename) => {\n if (\n filename &&\n typeof filename === \"string\" &&\n filename.endsWith(\".ts\") &&\n !filename.endsWith(\".d.ts\")\n ) {\n onFileChange(resolve(target, filename));\n }\n });\n dirWatcher.on(\"error\", (err) => {\n console.error(`\\x1b[31m✗\\x1b[0m watcher error: ${err.message}`);\n });\n } else {\n // Watch individual file — also watch its parent dir as a fallback\n // since some editors do atomic writes (delete + create)\n const parentDir = dirname(target);\n const targetBase = basename(target);\n const fileWatcher = fsWatch(\n parentDir,\n { persistent: true },\n (_event, filename) => {\n if (filename === targetBase) {\n onFileChange(target);\n }\n }\n );\n fileWatcher.on(\"error\", (err) => {\n console.error(`\\x1b[31m✗\\x1b[0m watcher error: ${err.message}`);\n });\n }\n\n // Keep process alive, clean exit on SIGINT\n process.on(\"SIGINT\", () => {\n console.log(\"\\n\\x1b[90mStopped watching.\\x1b[0m\");\n process.exit(0);\n });\n }\n );\n\n// ─── mcp ─────────────────────────────────────────────────────────────\n//\n// Starts the Axint MCP server over stdio so any MCP-capable client\n// (Claude Code, Claude Desktop, Cursor, Windsurf, Zed, etc.) can call\n// `axint.compile`, `axint.validate`, `axint.scaffold`, and the template\n// tools directly. The server implementation lives in src/mcp/server.ts\n// and is also exposed as the standalone `axint-mcp` bin; this\n// subcommand just routes through the same entry point so users can run\n// `npx -y @axintai/compiler mcp` without a second package install.\n\nprogram\n .command(\"mcp\")\n .description(\n \"Start the Axint MCP server (stdio) for Claude Code, Cursor, Windsurf, Zed, or any MCP client\"\n )\n .action(async () => {\n const { startMCPServer } = await import(\"../mcp/server.js\");\n await startMCPServer();\n });\n\n// Helper used by scaffold to avoid a circular import\nexport function __axintExistsSync(p: string) {\n return existsSync(p);\n}\n\nprogram.parse();\n","/**\n * Axint Eject Module\n *\n * Generates standalone Swift code that has no dependency on Axint.\n * This is useful for teams that want to verify there's no vendor lock-in\n * or for distributing intents without the compilation layer.\n *\n * The eject process:\n * 1. Compiles the TypeScript intent using the standard pipeline\n * 2. Transforms the output to remove Axint markers\n * 3. Optionally generates XCTest stubs\n * 4. Emits all files (Swift, plist, entitlements, test)\n */\n\nimport { compileSource } from \"./compiler.js\";\nimport { formatSwift } from \"./format.js\";\nimport type { IRIntent } from \"./types.js\";\n\n// ─── Public Interface ────────────────────────────────────────────────\n\nexport interface EjectOptions {\n /** Output directory for ejected files (defaults to \".\") */\n outDir?: string;\n /** Generate a basic XCTest file for the intent */\n includeTests?: boolean;\n /** Format output with swift-format (requires swift-format on PATH) */\n format?: boolean;\n}\n\nexport interface EjectResult {\n /** The primary Swift file */\n swiftFile: {\n path: string;\n content: string;\n };\n /** Optional Info.plist fragment */\n infoPlist?: {\n path: string;\n content: string;\n };\n /** Optional entitlements fragment */\n entitlements?: {\n path: string;\n content: string;\n };\n /** Optional XCTest file */\n testFile?: {\n path: string;\n content: string;\n };\n}\n\n// ─── Main Eject Function ────────────────────────────────────────────\n\n/**\n * Eject an intent from Axint, producing standalone Swift code with no\n * vendor lock-in. The resulting Swift code is production-ready and can\n * be committed directly to version control.\n *\n * @param source The TypeScript intent source\n * @param fileName Display name for diagnostics (e.g., \"intent.ts\")\n * @param options Eject options (outDir, includeTests, format)\n * @returns Ejected files\n */\nexport async function ejectIntent(\n source: string,\n fileName: string,\n options: EjectOptions = {}\n): Promise<EjectResult> {\n // 1. Compile using the standard pipeline\n const compileResult = compileSource(source, fileName, {\n validate: true,\n emitInfoPlist: true,\n emitEntitlements: true,\n });\n\n if (!compileResult.success || !compileResult.output) {\n throw new Error(\n `Compilation failed: ${compileResult.diagnostics\n .filter((d) => d.severity === \"error\")\n .map((d) => d.message)\n .join(\"; \")}`\n );\n }\n\n const { ir, swiftCode, infoPlistFragment, entitlementsFragment } = compileResult.output;\n const outDir = options.outDir ?? \".\";\n\n // 2. Transform Swift to remove Axint markers\n let ejectedSwift = transformSwiftForEject(swiftCode, ir);\n\n // 2b. Optionally run swift-format\n if (options.format) {\n const { formatted, ran } = await formatSwift(ejectedSwift);\n if (ran) ejectedSwift = formatted;\n }\n\n // 3. Construct file paths\n const intentFileName = `${ir.name}Intent.swift`;\n const swiftPath = `${outDir}/${intentFileName}`;\n const plistPath = infoPlistFragment\n ? `${outDir}/${ir.name}Intent.plist.fragment.xml`\n : null;\n const entitlementsPath = entitlementsFragment\n ? `${outDir}/${ir.name}Intent.entitlements.fragment.xml`\n : null;\n const testPath = options.includeTests ? `${outDir}/${ir.name}IntentTests.swift` : null;\n\n // 4. Build result object\n const result: EjectResult = {\n swiftFile: {\n path: swiftPath,\n content: ejectedSwift,\n },\n };\n\n if (infoPlistFragment && plistPath) {\n result.infoPlist = {\n path: plistPath,\n content: infoPlistFragment,\n };\n }\n\n if (entitlementsFragment && entitlementsPath) {\n result.entitlements = {\n path: entitlementsPath,\n content: entitlementsFragment,\n };\n }\n\n if (options.includeTests && testPath) {\n result.testFile = {\n path: testPath,\n content: generateTestFile(ir),\n };\n }\n\n return result;\n}\n\n// ─── Swift Transformation ───────────────────────────────────────────\n\n/**\n * Transform generated Swift code to be \"ejected\" — remove Axint markers,\n * update the header comment, and enhance the TODO placeholder.\n */\nfunction transformSwiftForEject(swiftCode: string, ir: IRIntent): string {\n const lines = swiftCode.split(\"\\n\");\n const result: string[] = [];\n\n let inHeader = true;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Replace header comment\n if (inHeader && line.startsWith(\"// \")) {\n if (i === 0) {\n // First line: replace with intent name\n result.push(`// ${ir.name}Intent.swift`);\n } else if (line.includes(\"Generated by Axint\")) {\n // Skip the Axint header\n result.push(\n `// Originally generated by Axint (https://github.com/agenticempire/axint)`\n );\n } else if (line.includes(\"Do not edit manually\")) {\n // Skip the regeneration instruction\n } else {\n result.push(line);\n }\n } else if (line === \"\") {\n inHeader = false;\n result.push(line);\n } else {\n inHeader = false;\n\n // Replace the TODO comment with a more helpful one\n if (line.includes(\"// TODO: Implement your intent logic here.\")) {\n result.push(` // TODO: Implement your intent logic here.`);\n result.push(` //`);\n result.push(` // For more information about App Intents, see:`);\n result.push(` // https://developer.apple.com/documentation/appintents`);\n } else {\n result.push(line);\n }\n }\n }\n\n return result.join(\"\\n\");\n}\n\n// ─── Test File Generation ───────────────────────────────────────────\n\n/**\n * Generate a basic XCTest file for the intent.\n * This provides a scaffold that users can fill in with their own tests.\n */\nfunction generateTestFile(ir: IRIntent): string {\n const lines: string[] = [];\n\n lines.push(`// ${ir.name}IntentTests.swift`);\n lines.push(`// Ejected from Axint`);\n lines.push(``);\n lines.push(`import XCTest`);\n lines.push(`import AppIntents`);\n lines.push(``);\n lines.push(`final class ${ir.name}IntentTests: XCTestCase {`);\n lines.push(``);\n lines.push(` func testIntentInitialization() throws {`);\n lines.push(` let intent = ${ir.name}Intent()`);\n lines.push(` XCTAssertEqual(${ir.name}Intent.title.stringValue, \"${ir.title}\")`);\n lines.push(` }`);\n lines.push(``);\n lines.push(` func testIntentPerform() async throws {`);\n lines.push(` let intent = ${ir.name}Intent()`);\n lines.push(` // TODO: Set up intent parameters and test perform()`);\n lines.push(` // let result = try await intent.perform()`);\n lines.push(` // XCTAssertNotNil(result)`);\n lines.push(` }`);\n lines.push(``);\n lines.push(`}`);\n lines.push(``);\n\n return lines.join(\"\\n\");\n}\n","/**\n * Project scaffolder — `axint init`\n *\n * Zero-config project creation. Drops a working Axint project on disk:\n *\n * my-app/\n * ├── package.json — pinned to the current Axint version\n * ├── tsconfig.json — strict, ES2022, module NodeNext\n * ├── .gitignore\n * ├── README.md — next-steps guide\n * ├── intents/\n * │ └── <template>.ts — starter intent from the template library\n * ├── ios/\n * │ └── Intents/ — compile output target (created on first run)\n * └── .vscode/\n * └── mcp.json — ready-to-use MCP server config for Cursor/Copilot\n *\n * The scaffolder is deliberately dependency-free at runtime — everything is\n * written with `fs/promises`. It is safe to call against an existing directory\n * as long as that directory is empty (or only contains a .git folder).\n */\n\nimport { mkdir, writeFile, readdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { getTemplate } from \"../templates/index.js\";\n\nexport interface ScaffoldOptions {\n targetDir: string;\n projectName: string;\n template: string;\n version: string;\n install: boolean;\n}\n\nexport interface ScaffoldResult {\n files: string[];\n entryFile: string;\n}\n\nexport async function scaffoldProject(opts: ScaffoldOptions): Promise<ScaffoldResult> {\n const { targetDir, projectName, template, version, install } = opts;\n\n // 1. Resolve template\n const tpl = getTemplate(template);\n if (!tpl) {\n throw new Error(\n `Unknown template \"${template}\". Run \\`axint templates\\` to see available templates.`\n );\n }\n\n // 2. Safety check — refuse to overwrite a populated directory\n if (existsSync(targetDir)) {\n const entries = await readdir(targetDir).catch(() => []);\n const populated = entries.filter((e) => !e.startsWith(\".git\") && e !== \".DS_Store\");\n if (populated.length > 0) {\n throw new Error(\n `Directory \"${targetDir}\" is not empty. Pick an empty folder or use \\`axint init my-new-app\\`.`\n );\n }\n } else {\n await mkdir(targetDir, { recursive: true });\n }\n\n const files: string[] = [];\n const write = async (rel: string, content: string) => {\n const abs = join(targetDir, rel);\n await mkdir(join(abs, \"..\").replace(/[/\\\\][^/\\\\]+$/, \"\"), { recursive: true }).catch(\n () => undefined\n );\n // Ensure parent dir exists using a more reliable approach\n const parent = abs.substring(\n 0,\n abs.lastIndexOf(\"/\") === -1 ? abs.lastIndexOf(\"\\\\\") : abs.lastIndexOf(\"/\")\n );\n if (parent && parent !== abs) {\n await mkdir(parent, { recursive: true }).catch(() => undefined);\n }\n await writeFile(abs, content, \"utf-8\");\n files.push(relative(targetDir, abs));\n };\n\n // 3. package.json\n await write(\n \"package.json\",\n JSON.stringify(\n {\n name: projectName,\n version: \"0.0.1\",\n private: true,\n type: \"module\",\n scripts: {\n compile: `axint compile intents/${template}.ts --out ios/Intents/`,\n \"compile:plist\": `axint compile intents/${template}.ts --out ios/Intents/ --emit-info-plist --emit-entitlements`,\n validate: `axint validate intents/${template}.ts`,\n sandbox: `axint validate intents/${template}.ts --sandbox`,\n },\n dependencies: {\n \"@axintai/compiler\": `^${version}`,\n },\n },\n null,\n 2\n ) + \"\\n\"\n );\n\n // 4. tsconfig.json\n await write(\n \"tsconfig.json\",\n JSON.stringify(\n {\n compilerOptions: {\n target: \"ES2022\",\n module: \"NodeNext\",\n moduleResolution: \"NodeNext\",\n strict: true,\n esModuleInterop: true,\n skipLibCheck: true,\n noEmit: true,\n isolatedModules: true,\n verbatimModuleSyntax: false,\n resolveJsonModule: true,\n },\n include: [\"intents/**/*.ts\"],\n },\n null,\n 2\n ) + \"\\n\"\n );\n\n // 5. .gitignore\n await write(\n \".gitignore\",\n [\"node_modules\", \"dist\", \".DS_Store\", \".axint-sandbox\", \"*.log\", \"\"].join(\"\\n\")\n );\n\n // 6. The starter intent itself — pulled straight from the template library.\n // Templates already use `@axintai/compiler` which resolves against the\n // scaffolded dependency.\n await write(`intents/${template}.ts`, tpl.source);\n\n // 7. .vscode/mcp.json — ready to `npx axint-mcp` from Cursor/Claude Code\n await write(\n \".vscode/mcp.json\",\n JSON.stringify(\n {\n mcpServers: {\n axint: {\n command: \"npx\",\n args: [\"-y\", \"@axintai/compiler\", \"axint-mcp\"],\n },\n },\n },\n null,\n 2\n ) + \"\\n\"\n );\n\n // 8. Project README\n await write(\"README.md\", scaffoldReadme(projectName, template, tpl.title, version));\n\n // 9. ios/Intents — create target dir so `compile` has somewhere to land\n await mkdir(join(targetDir, \"ios\", \"Intents\"), { recursive: true });\n await write(\"ios/Intents/.gitkeep\", \"\");\n\n // 10. Optional npm install\n if (install) {\n await runNpmInstall(targetDir);\n }\n\n return {\n files,\n entryFile: `${template}.ts`,\n };\n}\n\nfunction scaffoldReadme(\n name: string,\n template: string,\n title: string,\n version: string\n): string {\n return `# ${name}\n\nAn [Axint](https://axint.ai) project — write App Intents in TypeScript, ship them to Siri.\n\nGenerated from the **${title}** template, pinned to \\`@axintai/compiler@^${version}\\`.\n\n## Compile it\n\n\\`\\`\\`bash\nnpm install\nnpm run compile\n\\`\\`\\`\n\nOutput lands in \\`ios/Intents/\\`. Drag that folder into your Xcode target and you're done.\n\n## Validate it\n\n\\`\\`\\`bash\nnpm run validate # fast IR + Swift lint\nnpm run sandbox # stage 4: swift build in an SPM sandbox (macOS only)\n\\`\\`\\`\n\n## Use with AI coding tools\n\nThe \\`.vscode/mcp.json\\` file is pre-wired for Cursor, Claude Code, and Windsurf.\nAny agent that supports MCP can now call \\`axint_compile\\`, \\`axint_validate\\`,\n\\`axint_scaffold\\`, and \\`axint_template\\` against this project.\n\n## Next\n\n- Edit \\`intents/${template}.ts\\` — this is your App Intent source of truth.\n- Add more intents in the \\`intents/\\` folder.\n- Run \\`axint templates\\` to see every bundled starter.\n- Read the docs at https://github.com/agenticempire/axint#readme\n\n---\n\n_Generated by \\`axint init\\`_\n`;\n}\n\nfunction runNpmInstall(cwd: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"npm\", [\"install\"], { cwd, stdio: \"inherit\" });\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`npm install exited with code ${code}`));\n });\n child.on(\"error\", reject);\n });\n}\n"],"mappings":";;;;;;;;;;;;AA6KO,SAAS,cAAc,MAAsB;AAClD,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,eAAe,KAAK,KAAK;AAAA,IAClC,KAAK;AACH,aAAO,IAAI,cAAc,KAAK,WAAW,CAAC;AAAA,IAC5C,KAAK;AACH,aAAO,GAAG,cAAc,KAAK,SAAS,CAAC;AAAA,IACzC,KAAK;AACH,aAAO,KAAK;AAAA,IACd,KAAK;AACH,aAAO,GAAG,KAAK,UAAU;AAAA,IAC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ACA,OAAO,aAAa,YACpB,SAAS,SAAS,KAAK,KACvB,CAAC,SAAS,SAAS,OAAO,GAC1B;AACA,uBAAaN,SAAQ,QAAQ,QAAQ,CAAC;AAAA,QACxC;AAAA,MACF,CAAC;AACD,iBAAW,GAAG,SAAS,CAAC,QAAQ;AAC9B,gBAAQ,MAAM,wCAAmC,IAAI,OAAO,EAAE;AAAA,MAChE,CAAC;AAAA,IACH,OAAO;AAGL,YAAM,YAAYJ,SAAQ,MAAM;AAChC,YAAM,aAAa,SAAS,MAAM;AAClC,YAAM,cAAc;AAAA,QAClB;AAAA,QACA,EAAE,YAAY,KAAK;AAAA,QACnB,CAAC,QAAQ,aAAa;AACpB,cAAI,aAAa,YAAY;AAC3B,yBAAa,MAAM;AAAA,UACrB;AAAA,QACF;AAAA,MACF;AACA,kBAAY,GAAG,SAAS,CAAC,QAAQ;AAC/B,gBAAQ,MAAM,wCAAmC,IAAI,OAAO,EAAE;AAAA,MAChE,CAAC;AAAA,IACH;AAGA,YAAQ,GAAG,UAAU,MAAM;AACzB,cAAQ,IAAI,oCAAoC;AAChD,cAAQ,KAAK,CAAC;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AAYF,QACG,QAAQ,KAAK,EACb;AAAA,EACC;AACF,EACC,OAAO,YAAY;AAClB,QAAM,EAAE,gBAAAW,gBAAe,IAAI,MAAM;AACjC,QAAMA,gBAAe;AACvB,CAAC;AAGI,SAAS,kBAAkB,GAAW;AAC3C,SAAOF,YAAW,CAAC;AACrB;AAEA,QAAQ,MAAM;","names":["resolve","mkdir","writeFile","existsSync","join","tmpdir","spawn","resolve","toPascalCase","readFileSync","readFileSync","existsSync","resolve","dirname","spawn","fileURLToPath","writeFile","join","spawn","resolve","__dirname","dirname","fileURLToPath","pkg","readFileSync","resolve","formatSwift","sandboxCompile","join","spawn","existsSync","runSwiftBuild","startMCPServer"]}