@noormdev/sdk 1.0.0-alpha.19 → 1.0.0-alpha.20

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.
Files changed (50) hide show
  1. package/dist/chunk-3UDETNWW.js +943 -0
  2. package/dist/chunk-3UDETNWW.js.map +1 -0
  3. package/dist/chunk-D2XW2UOP.js +42 -0
  4. package/dist/chunk-D2XW2UOP.js.map +1 -0
  5. package/dist/chunk-TBRUDUBQ.js +1099 -0
  6. package/dist/chunk-TBRUDUBQ.js.map +1 -0
  7. package/dist/chunk-UDUDHOIB.js +3136 -0
  8. package/dist/chunk-UDUDHOIB.js.map +1 -0
  9. package/dist/chunk-UOFJT5PY.js +1499 -0
  10. package/dist/chunk-UOFJT5PY.js.map +1 -0
  11. package/dist/chunk-YJBKNUTP.js +7233 -0
  12. package/dist/chunk-YJBKNUTP.js.map +1 -0
  13. package/dist/{chunk-HB3JXUJV.js → chunk-ZKYTJJIF.js} +6 -4
  14. package/dist/chunk-ZKYTJJIF.js.map +1 -0
  15. package/dist/csv-T5P3IN4K.js +7 -0
  16. package/dist/csv-T5P3IN4K.js.map +1 -0
  17. package/dist/engine-27DNMF4T.js +11 -0
  18. package/dist/{engine-3J25GVCU.js.map → engine-27DNMF4T.js.map} +1 -1
  19. package/dist/index.d.ts +77 -0
  20. package/dist/index.js +14793 -596
  21. package/dist/index.js.map +1 -1
  22. package/dist/json5-LNT3RGJ7.js +7 -0
  23. package/dist/json5-LNT3RGJ7.js.map +1 -0
  24. package/dist/{mssql-65M7MY4Q.js → mssql-3NNVV77C.js} +5 -3
  25. package/dist/mssql-3NNVV77C.js.map +1 -0
  26. package/dist/{mysql-C2DR4TF7.js → mysql-UPMQUBLE.js} +5 -3
  27. package/dist/mysql-UPMQUBLE.js.map +1 -0
  28. package/dist/{postgres-SIDJBSIT.js → postgres-CPVTCR7W.js} +5 -3
  29. package/dist/postgres-CPVTCR7W.js.map +1 -0
  30. package/dist/{sqlite-5VZTBN5J.js → sqlite-F3ZSSDUM.js} +5 -3
  31. package/dist/sqlite-F3ZSSDUM.js.map +1 -0
  32. package/dist/{sqlite-bun-AV7LHRJK.js → sqlite-bun-LMHUMGQI.js} +5 -3
  33. package/dist/sqlite-bun-LMHUMGQI.js.map +1 -0
  34. package/dist/storage-TZNQBIX3.js +8 -0
  35. package/dist/{storage-WTYJE355.js.map → storage-TZNQBIX3.js.map} +1 -1
  36. package/dist/yaml-XI7RQ2D5.js +7 -0
  37. package/dist/yaml-XI7RQ2D5.js.map +1 -0
  38. package/package.json +1 -1
  39. package/dist/chunk-BP4PMFJF.js +0 -11
  40. package/dist/chunk-BP4PMFJF.js.map +0 -1
  41. package/dist/chunk-HB3JXUJV.js.map +0 -1
  42. package/dist/chunk-UZARPCOH.js +0 -482
  43. package/dist/chunk-UZARPCOH.js.map +0 -1
  44. package/dist/engine-3J25GVCU.js +0 -4
  45. package/dist/mssql-65M7MY4Q.js.map +0 -1
  46. package/dist/mysql-C2DR4TF7.js.map +0 -1
  47. package/dist/postgres-SIDJBSIT.js.map +0 -1
  48. package/dist/sqlite-5VZTBN5J.js.map +0 -1
  49. package/dist/sqlite-bun-AV7LHRJK.js.map +0 -1
  50. package/dist/storage-WTYJE355.js +0 -4
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/eta/src/err.ts","../../../node_modules/eta/src/file-handling.ts","../../../node_modules/eta/src/compile.ts","../../../node_modules/eta/src/compile-string.ts","../../../node_modules/eta/src/utils.ts","../../../node_modules/eta/src/config.ts","../../../node_modules/eta/src/parse.ts","../../../node_modules/eta/src/render.ts","../../../node_modules/eta/src/storage.ts","../../../node_modules/eta/src/internal.ts","../../../node_modules/eta/src/index.ts","../../../src/core/template/types.ts","../../../src/core/template/loaders/js.ts","../../../src/core/template/helpers.ts","../../../src/core/template/loaders/sql.ts","../../../src/core/dt/constants.ts","../../../src/core/dt/crypto.ts","../../../src/core/dt/reader.ts","../../../src/core/template/loaders/dt.ts","../../../src/core/template/loaders/index.ts","../../../src/core/template/utils.ts","../../../src/core/template/context.ts","../../../src/core/template/engine.ts"],"names":["path","err: any","relative","config: EtaConfig","compileBody","buffer: Array<AstObject>","leftTrim: string | false","rightTrim: string | false","escMap: { [key: string]: string }","defaultConfig: EtaConfig","trimLeftOfNextStr: string | false","m: RegExpExecArray | null","closeTag: RegExpExecArray | null","currentObj: AstObject | false","templateFn: TemplateFunction","cache: Record<string, T>","Eta","EtaCore","dirname","join","exports","readFile","randomBytes","readFileSync","loadJson5","loadYaml","loadCsv","processFile"],"mappings":";;;;;;;;;;;;;;;AAAA,IAAa,QAAA,GAAb,cAA8B,KAAA,CAAM;AAClC,EAAA,WAAA,CAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAA,CAAA;AACN,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;;;AAIhB,IAAa,aAAA,GAAb,cAAmC,QAAA,CAAS;AAC1C,EAAA,WAAA,CAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAA,CAAA;AACN,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;;;AAIhB,IAAa,eAAA,GAAb,cAAqC,QAAA,CAAS;AAC5C,EAAA,WAAA,CAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAA,CAAA;AACN,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;;;AAIhB,IAAa,sBAAA,GAAb,cAA4C,QAAA,CAAS;AACnD,EAAA,WAAA,CAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAA,CAAA;AACN,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;;;AAIhB,IAAa,sBAAA,GAAb,cAA4C,QAAA,CAAS;AACnD,EAAA,WAAA,CAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAA,CAAA;AACN,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;;;AAQhB,SAAgB,QAAA,CAAS,OAAA,EAAiB,G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M,OAAA,GAAU,MAAMN,UAAAA,CAAS,QAAA,EAAU,OAAO,CAAA;AAGhD,EAAA,IAAI,CAAC,UAAA,CAAW,QAAQ,CAAA,EAAG;AAEvB,IAAA,OAAO;AAAA,MACH,GAAA,EAAK,OAAA;AAAA,MACL,UAAA,EAAY;AAAA,KAChB;AAAA,EAEJ;AAGA,EAAA,MAAM,KAAA,GAAQ,YAAY,GAAA,EAAI;AAE9B,EAAA,MAAM,OAAA,GAAU,MAAM,YAAA,CAAa,QAAA,EAAU,OAAO,CAAA;AACpD,EAAA,MAAM,GAAA,GAAM,MAAM,cAAA,CAAe,OAAA,EAAS,OAAO,CAAA;AAEjD,EAAA,MAAM,UAAA,GAAa,WAAA,CAAY,GAAA,EAAI,GAAI,KAAA;AAEvC,EAAA,QAAA,CAAS,KAAK,iBAAA,EAAmB;AAAA,IAC7B,QAAA;AAAA,IACA;AAAA,GACH,CAAA;AAED,EAAA,OAAO;AAAA,IACH,GAAA;AAAA,IACA,UAAA,EAAY,IAAA;AAAA,IACZ;AAAA,GACJ;AAEJ;AASA,eAAsB,YAAA,CAClB,SAAA,EACA,OAAA,GAAyB,EAAC,EACF;AAExB,EAAA,MAAM,UAA2B,EAAC;AAElC,EAAA,KAAA,MAAW,YAAY,SAAA,EAAW;AAE9B,IAAA,MAAM,MAAA,GAAS,MAAM,WAAA,CAAY,QAAA,EAAU,OAAO,CAAA;AAClD,IAAA,OAAA,CAAQ,KAAK,MAAM,CAAA;AAAA,EAEvB;AAEA,EAAA,OAAO,OAAA;AAEX","file":"chunk-3UDETNWW.js","sourcesContent":["export class EtaError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"Eta Error\";\n }\n}\n\nexport class EtaParseError extends EtaError {\n constructor(message: string) {\n super(message);\n this.name = \"EtaParser Error\";\n }\n}\n\nexport class EtaRuntimeError extends EtaError {\n constructor(message: string) {\n super(message);\n this.name = \"EtaRuntime Error\";\n }\n}\n\nexport class EtaFileResolutionError extends EtaError {\n constructor(message: string) {\n super(message);\n this.name = \"EtaFileResolution Error\";\n }\n}\n\nexport class EtaNameResolutionError extends EtaError {\n constructor(message: string) {\n super(message);\n this.name = \"EtaNameResolution Error\";\n }\n}\n\n/**\n * Throws an EtaError with a nicely formatted error and message showing where in the template the error occurred.\n */\n\nexport function ParseErr(message: string, str: string, indx: number): never {\n const whitespace = str.slice(0, indx).split(/\\n/);\n\n const lineNo = whitespace.length;\n const colNo = whitespace[lineNo - 1].length + 1;\n message +=\n \" at line \" +\n lineNo +\n \" col \" +\n colNo +\n \":\\n\\n\" +\n \" \" +\n str.split(/\\n/)[lineNo - 1] +\n \"\\n\" +\n \" \" +\n Array(colNo).join(\" \") +\n \"^\";\n throw new EtaParseError(message);\n}\n\nexport function RuntimeErr(\n originalError: Error,\n str: string,\n lineNo: number,\n path: string,\n): never {\n // code gratefully taken from https://github.com/mde/ejs and adapted\n\n const lines = str.split(\"\\n\");\n const start = Math.max(lineNo - 3, 0);\n const end = Math.min(lines.length, lineNo + 3);\n const filename = path;\n // Error context\n const context = lines\n .slice(start, end)\n .map((line, i) => {\n const curr = i + start + 1;\n return (curr === lineNo ? \" >> \" : \" \") + curr + \"| \" + line;\n })\n .join(\"\\n\");\n\n const header = filename\n ? filename + \":\" + lineNo + \"\\n\"\n : \"line \" + lineNo + \"\\n\";\n\n const err = new EtaRuntimeError(\n header + context + \"\\n\\n\" + originalError.message,\n );\n\n err.name = originalError.name; // the original name (e.g. ReferenceError) may be useful\n err.cause = originalError;\n\n throw err;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport type { Options } from \"./config.ts\";\nimport { EtaFileResolutionError } from \"./err.ts\";\nimport type { Eta as EtaCore } from \"./internal.ts\";\n\nexport function readFile(this: EtaCore, path: string): string {\n let res = \"\";\n\n try {\n res = fs.readFileSync(path, \"utf8\");\n // biome-ignore lint/suspicious/noExplicitAny: it's an error\n } catch (err: any) {\n if (err?.code === \"ENOENT\") {\n throw new EtaFileResolutionError(`Could not find template: ${path}`);\n } else {\n throw err;\n }\n }\n\n return res;\n}\n\nexport function resolvePath(\n this: EtaCore,\n templatePath: string,\n options?: Partial<Options>,\n): string {\n let resolvedFilePath = \"\";\n\n const views = this.config.views;\n\n if (!views) {\n throw new EtaFileResolutionError(\"Views directory is not defined\");\n }\n\n const baseFilePath = options?.filepath;\n const defaultExtension =\n this.config.defaultExtension === undefined\n ? \".eta\"\n : this.config.defaultExtension;\n\n // how we index cached template paths\n const cacheIndex = JSON.stringify({\n filename: baseFilePath, // filename of the template which called includeFile()\n path: templatePath,\n views: this.config.views,\n });\n\n templatePath += path.extname(templatePath) ? \"\" : defaultExtension;\n\n // if the file was included from another template\n if (baseFilePath) {\n // check the cache\n\n if (this.config.cacheFilepaths && this.filepathCache[cacheIndex]) {\n return this.filepathCache[cacheIndex];\n }\n\n const absolutePathTest = absolutePathRegExp.exec(templatePath);\n\n if (absolutePathTest?.length) {\n const formattedPath = templatePath.replace(/^\\/*|^\\\\*/, \"\");\n resolvedFilePath = path.join(views, formattedPath);\n } else {\n resolvedFilePath = path.join(path.dirname(baseFilePath), templatePath);\n }\n } else {\n resolvedFilePath = path.join(views, templatePath);\n }\n\n if (dirIsChild(views, resolvedFilePath)) {\n // add resolved path to the cache\n if (baseFilePath && this.config.cacheFilepaths) {\n this.filepathCache[cacheIndex] = resolvedFilePath;\n }\n\n return resolvedFilePath;\n } else {\n throw new EtaFileResolutionError(\n `Template '${templatePath}' is not in the views directory`,\n );\n }\n}\n\nfunction dirIsChild(parent: string, dir: string) {\n const relative = path.relative(parent, dir);\n return relative && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n\nconst absolutePathRegExp = /^\\\\|^\\//;\n","import type { EtaConfig, Options } from \"./config.ts\";\nimport { EtaParseError } from \"./err.ts\";\nimport type { Eta } from \"./internal.ts\";\n\nexport type TemplateFunction = (\n this: Eta,\n data?: object,\n options?: Partial<Options>,\n) => string;\n/* END TYPES */\n\n/* istanbul ignore next */\nconst AsyncFunction = (async () => {}).constructor;\n\n/**\n * Takes a template string and returns a template function that can be called with (data, config)\n *\n * @param str - The template string\n * @param config - A custom configuration object (optional)\n */\n\nexport function compile(\n this: Eta,\n str: string,\n options?: Partial<Options>,\n): TemplateFunction {\n const config: EtaConfig = this.config;\n\n /* ASYNC HANDLING */\n // code gratefully taken from https://github.com/mde/ejs and adapted\n const ctor = options?.async\n ? (AsyncFunction as FunctionConstructor)\n : Function;\n /* END ASYNC HANDLING */\n\n try {\n return new ctor(\n config.varName,\n \"options\",\n this.compileToString.call(this, str, options),\n ) as TemplateFunction; // eslint-disable-line no-new-func\n } catch (e) {\n if (e instanceof SyntaxError) {\n throw new EtaParseError(\n \"Bad template syntax\\n\\n\" +\n e.message +\n \"\\n\" +\n Array(e.message.length + 1).join(\"=\") +\n \"\\n\" +\n this.compileToString.call(this, str, options) +\n \"\\n\", // This will put an extra newline before the callstack for extra readability\n );\n } else {\n throw e;\n }\n }\n}\n","import type { Options } from \"./config.ts\";\nimport type { Eta } from \"./internal.ts\";\nimport type { AstObject } from \"./parse.ts\";\n\n/**\n * Compiles a template string to a function string. Most often users just use `compile()`, which calls `compileToString` and creates a new function using the result\n */\n\nexport function compileToString(\n this: Eta,\n str: string,\n options?: Partial<Options>,\n): string {\n const config = this.config;\n const isAsync = options?.async;\n\n const compileBody = this.compileBody;\n\n const buffer: Array<AstObject> = this.parse.call(this, str);\n\n // note: when the include function passes through options, the only parameter that matters is the filepath parameter\n let res = `${config.functionHeader}\nlet include = (__eta_t, __eta_d) => this.render(__eta_t, {...${config.varName}, ...(__eta_d ?? {})}, options);\nlet includeAsync = (__eta_t, __eta_d) => this.renderAsync(__eta_t, {...${config.varName}, ...(__eta_d ?? {})}, options);\n\nlet __eta = {res: \"\", e: this.config.escapeFunction, f: this.config.filterFunction${\n config.debug\n ? ', line: 1, templateStr: \"' +\n str.replace(/\\\\|\"/g, \"\\\\$&\").replace(/\\r\\n|\\n|\\r/g, \"\\\\n\") +\n '\"'\n : \"\"\n }};\n\nfunction layout(path, data) {\n __eta.layout = path;\n __eta.layoutData = data;\n}${config.debug ? \"try {\" : \"\"}${\n config.useWith ? \"with(\" + config.varName + \"||{}){\" : \"\"\n }\n\nfunction ${config.outputFunctionName}(s){__eta.res+=s;}\n\n${compileBody.call(this, buffer)}\nif (__eta.layout) {\n __eta.res = ${\n isAsync ? \"await includeAsync\" : \"include\"\n } (__eta.layout, {...${\n config.varName\n }, body: __eta.res, ...__eta.layoutData});\n}\n${config.useWith ? \"}\" : \"\"}${\n config.debug\n ? \"} catch (e) { this.RuntimeErr(e, __eta.templateStr, __eta.line, options.filepath) }\"\n : \"\"\n}\nreturn __eta.res;\n`;\n\n if (config.plugins) {\n for (let i = 0; i < config.plugins.length; i++) {\n const plugin = config.plugins[i];\n if (plugin.processFnString) {\n res = plugin.processFnString(res, config);\n }\n }\n }\n\n return res;\n}\n\n/**\n * Loops through the AST generated by `parse` and transform each item into JS calls\n *\n * **Example**\n *\n * ```js\n * let templateAST = ['Hi ', { val: 'it.name', t: 'i' }]\n * compileBody.call(Eta, templateAST)\n * // => \"__eta.res+='Hi '\\n__eta.res+=__eta.e(it.name)\\n\"\n * ```\n */\n\nexport function compileBody(this: Eta, buff: Array<AstObject>): string {\n const config = this.config;\n\n let i = 0;\n const buffLength = buff.length;\n let returnStr = \"\";\n\n for (i; i < buffLength; i++) {\n const currentBlock = buff[i];\n if (typeof currentBlock === \"string\") {\n const str = currentBlock;\n\n // we know string exists\n returnStr += \"__eta.res+='\" + str + \"';\\n\";\n } else {\n const type = currentBlock.t; // \"r\", \"e\", or \"i\"\n let content = currentBlock.val || \"\";\n\n if (config.debug) returnStr += \"__eta.line=\" + currentBlock.lineNo + \"\\n\";\n\n if (type === \"r\") {\n // raw\n\n if (config.autoFilter) {\n content = \"__eta.f(\" + content + \")\";\n }\n\n returnStr += \"__eta.res+=\" + content + \";\\n\";\n } else if (type === \"i\") {\n // interpolate\n\n if (config.autoFilter) {\n content = \"__eta.f(\" + content + \")\";\n }\n\n if (config.autoEscape) {\n content = \"__eta.e(\" + content + \")\";\n }\n\n returnStr += \"__eta.res+=\" + content + \";\\n\";\n } else if (type === \"e\") {\n // execute\n returnStr += content + \"\\n\";\n }\n }\n }\n\n return returnStr;\n}\n","import type { EtaConfig } from \"./config.ts\";\n\n/**\n * Takes a string within a template and trims it, based on the preceding tag's whitespace control and `config.autoTrim`\n */\n\nexport function trimWS(\n str: string,\n config: EtaConfig,\n wsLeft: string | false,\n wsRight?: string | false,\n): string {\n let leftTrim: string | false;\n let rightTrim: string | false;\n\n if (Array.isArray(config.autoTrim)) {\n // Slightly confusing,\n // but _}} will trim the left side of the following string\n leftTrim = config.autoTrim[1];\n rightTrim = config.autoTrim[0];\n } else {\n leftTrim = rightTrim = config.autoTrim;\n }\n\n if (wsLeft || wsLeft === false) {\n leftTrim = wsLeft;\n }\n\n if (wsRight || wsRight === false) {\n rightTrim = wsRight;\n }\n\n if (!rightTrim && !leftTrim) {\n return str;\n }\n\n if (leftTrim === \"slurp\" && rightTrim === \"slurp\") {\n return str.trim();\n }\n\n if (leftTrim === \"_\" || leftTrim === \"slurp\") {\n // full slurp\n str = str.trimStart();\n } else if (leftTrim === \"-\" || leftTrim === \"nl\") {\n // nl trim\n str = str.replace(/^(?:\\r\\n|\\n|\\r)/, \"\");\n }\n\n if (rightTrim === \"_\" || rightTrim === \"slurp\") {\n // full slurp\n str = str.trimEnd();\n } else if (rightTrim === \"-\" || rightTrim === \"nl\") {\n // nl trim\n str = str.replace(/(?:\\r\\n|\\n|\\r)$/, \"\");\n }\n\n return str;\n}\n\n/**\n * A map of special HTML characters to their XML-escaped equivalents\n */\n\nconst escMap: { [key: string]: string } = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nfunction replaceChar(s: string): string {\n return escMap[s];\n}\n\n/**\n * XML-escapes an input value after converting it to a string\n *\n * @param str - Input value (usually a string)\n * @returns XML-escaped string\n */\n\nexport function XMLEscape(str: unknown): string {\n // To deal with XSS. Based on Escape implementations of Mustache.JS and Marko, then customized.\n const newStr = String(str);\n if (/[&<>\"']/.test(newStr)) {\n return newStr.replace(/[&<>\"']/g, replaceChar);\n } else {\n return newStr;\n }\n}\n","import type { AstObject } from \"./parse.ts\";\nimport { XMLEscape } from \"./utils.ts\";\n\ntype trimConfig = \"nl\" | \"slurp\" | false;\n\nexport interface Options {\n /** Compile to async function */\n async?: boolean;\n\n /** Absolute path to template file */\n filepath?: string;\n}\n\nexport interface EtaConfig {\n /** Whether or not to automatically XML-escape interpolations. Default true */\n autoEscape: boolean;\n\n /** Apply a filter function defined on the class to every interpolation or raw interpolation */\n autoFilter: boolean;\n\n /** Configure automatic whitespace trimming. Default `[false, 'nl']` */\n autoTrim: trimConfig | [trimConfig, trimConfig];\n\n /** Whether or not to cache templates if `name` or `filename` is passed */\n cache: boolean;\n\n /** Holds cache of resolved filepaths. Set to `false` to disable. */\n cacheFilepaths: boolean;\n\n /** Whether to pretty-format error messages (introduces runtime penalties) */\n debug: boolean;\n\n /** Function to XML-sanitize interpolations */\n escapeFunction: (str: unknown) => string;\n\n /** Function applied to all interpolations when autoFilter is true */\n filterFunction: (val: unknown) => string;\n\n /** Name of the function that can be used in template code to output text to the result (like EJS's `outputFunctionName`). */\n outputFunctionName: string;\n\n /** Raw JS code inserted in the template function. Useful for declaring global variables for user templates */\n functionHeader: string;\n\n /** Parsing options */\n parse: {\n /** Which prefix to use for evaluation. Default `\"\"`, does not support `\"-\"` or `\"_\"` */\n exec: string;\n\n /** Which prefix to use for interpolation. Default `\"=\"`, does not support `\"-\"` or `\"_\"` */\n interpolate: string;\n\n /** Which prefix to use for raw interpolation. Default `\"~\"`, does not support `\"-\"` or `\"_\"` */\n raw: string;\n };\n\n /** Array of plugins */\n plugins: Array<{\n processFnString?: (fnString: string, env?: EtaConfig) => string;\n processAST?: (ast: AstObject[], env?: EtaConfig) => AstObject[];\n processTemplate?: (fnString: string, env?: EtaConfig) => string;\n }>;\n\n /** Remove empty lines and whitespace between lines */\n rmWhitespace: boolean;\n\n /** Delimiters: by default `['<%', '%>']` */\n tags: [string, string];\n\n /** Make data available on the global object instead of varName */\n useWith: boolean;\n\n /** Name of the data object. Default `it` */\n varName: string;\n\n /** Directory that contains templates */\n views?: string;\n\n /** Control template file extension defaults. Default `.eta` */\n defaultExtension?: string;\n}\n\n/* END TYPES */\n\n/** Eta's base (global) configuration */\nconst defaultConfig: EtaConfig = {\n autoEscape: true,\n autoFilter: false,\n autoTrim: [false, \"nl\"],\n cache: false,\n cacheFilepaths: true,\n debug: false,\n escapeFunction: XMLEscape,\n // default filter function (not used unless enables) just stringifies the input\n filterFunction: (val) => String(val),\n outputFunctionName: \"output\",\n functionHeader: \"\",\n parse: {\n exec: \"\",\n interpolate: \"=\",\n raw: \"~\",\n },\n plugins: [],\n rmWhitespace: false,\n tags: [\"<%\", \"%>\"],\n useWith: false,\n varName: \"it\",\n defaultExtension: \".eta\",\n};\n\nexport { defaultConfig };\n","import { ParseErr } from \"./err.ts\";\nimport type { Eta } from \"./internal.ts\";\nimport { trimWS } from \"./utils.ts\";\n\nexport type TagType = \"r\" | \"e\" | \"i\" | \"\";\n\nexport interface TemplateObject {\n t: TagType;\n val: string;\n lineNo?: number;\n}\n\nexport type AstObject = string | TemplateObject;\n\n/* END TYPES */\n\nconst templateLitReg =\n /`(?:\\\\[\\s\\S]|\\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\\${)[^\\\\`])*`/g;\n\nconst singleQuoteReg = /'(?:\\\\[\\s\\w\"'\\\\`]|[^\\n\\r'\\\\])*?'/g;\n\nconst doubleQuoteReg = /\"(?:\\\\[\\s\\w\"'\\\\`]|[^\\n\\r\"\\\\])*?\"/g;\n\n/** Escape special regular expression characters inside a string */\n\nfunction escapeRegExp(string: string) {\n // From MDN\n return string.replace(/[.*+\\-?^${}()|[\\]\\\\]/g, \"\\\\$&\"); // $& means the whole matched string\n}\n\nfunction getLineNo(str: string, index: number) {\n return str.slice(0, index).split(\"\\n\").length;\n}\n\nexport function parse(this: Eta, str: string): Array<AstObject> {\n const config = this.config;\n\n let buffer: Array<AstObject> = [];\n let trimLeftOfNextStr: string | false = false;\n let lastIndex = 0;\n const parseOptions = config.parse;\n\n if (config.plugins) {\n for (let i = 0; i < config.plugins.length; i++) {\n const plugin = config.plugins[i];\n if (plugin.processTemplate) {\n str = plugin.processTemplate(str, config);\n }\n }\n }\n\n /* Adding for EJS compatibility */\n if (config.rmWhitespace) {\n // Code taken directly from EJS\n // Have to use two separate replaces here as `^` and `$` operators don't\n // work well with `\\r` and empty lines don't work well with the `m` flag.\n // Essentially, this replaces the whitespace at the beginning and end of\n // each line and removes multiple newlines.\n str = str.replace(/[\\r\\n]+/g, \"\\n\").replace(/^\\s+|\\s+$/gm, \"\");\n }\n /* End rmWhitespace option */\n\n templateLitReg.lastIndex = 0;\n singleQuoteReg.lastIndex = 0;\n doubleQuoteReg.lastIndex = 0;\n\n function pushString(strng: string, shouldTrimRightOfString?: string | false) {\n if (strng) {\n // if string is truthy it must be of type 'string'\n\n strng = trimWS(\n strng,\n config,\n trimLeftOfNextStr, // this will only be false on the first str, the next ones will be null or undefined\n shouldTrimRightOfString,\n );\n\n if (strng) {\n // replace \\ with \\\\, ' with \\'\n // we're going to convert all CRLF to LF so it doesn't take more than one replace\n\n strng = strng.replace(/\\\\|'/g, \"\\\\$&\").replace(/\\r\\n|\\n|\\r/g, \"\\\\n\");\n\n buffer.push(strng);\n }\n }\n }\n\n const prefixes = [\n parseOptions.exec,\n parseOptions.interpolate,\n parseOptions.raw,\n ].reduce((accumulator, prefix) => {\n if (accumulator && prefix) {\n return accumulator + \"|\" + escapeRegExp(prefix);\n } else if (prefix) {\n // accumulator is falsy\n return escapeRegExp(prefix);\n } else {\n // prefix and accumulator are both falsy\n return accumulator;\n }\n }, \"\");\n\n const parseOpenReg = new RegExp(\n escapeRegExp(config.tags[0]) + \"(-|_)?\\\\s*(\" + prefixes + \")?\\\\s*\",\n \"g\",\n );\n\n const parseCloseReg = new RegExp(\n \"'|\\\"|`|\\\\/\\\\*|(\\\\s*(-|_)?\" + escapeRegExp(config.tags[1]) + \")\",\n \"g\",\n );\n\n let m: RegExpExecArray | null;\n\n // biome-ignore lint/suspicious/noAssignInExpressions: this is performant\n while ((m = parseOpenReg.exec(str))) {\n const precedingString = str.slice(lastIndex, m.index);\n\n lastIndex = m[0].length + m.index;\n\n const wsLeft = m[1];\n const prefix = m[2] || \"\"; // by default either ~, =, or empty\n\n pushString(precedingString, wsLeft);\n\n parseCloseReg.lastIndex = lastIndex;\n let closeTag: RegExpExecArray | null;\n let currentObj: AstObject | false = false;\n\n // biome-ignore lint/suspicious/noAssignInExpressions: this is performant\n while ((closeTag = parseCloseReg.exec(str))) {\n if (closeTag[1]) {\n const content = str.slice(lastIndex, closeTag.index);\n\n parseOpenReg.lastIndex = lastIndex = parseCloseReg.lastIndex;\n\n trimLeftOfNextStr = closeTag[2];\n\n const currentType: TagType =\n prefix === parseOptions.exec\n ? \"e\"\n : prefix === parseOptions.raw\n ? \"r\"\n : prefix === parseOptions.interpolate\n ? \"i\"\n : \"\";\n\n currentObj = { t: currentType, val: content };\n break;\n } else {\n const char = closeTag[0];\n if (char === \"/*\") {\n const commentCloseInd = str.indexOf(\"*/\", parseCloseReg.lastIndex);\n\n if (commentCloseInd === -1) {\n ParseErr(\"unclosed comment\", str, closeTag.index);\n }\n parseCloseReg.lastIndex = commentCloseInd;\n } else if (char === \"'\") {\n singleQuoteReg.lastIndex = closeTag.index;\n\n const singleQuoteMatch = singleQuoteReg.exec(str);\n if (singleQuoteMatch) {\n parseCloseReg.lastIndex = singleQuoteReg.lastIndex;\n } else {\n ParseErr(\"unclosed string\", str, closeTag.index);\n }\n } else if (char === '\"') {\n doubleQuoteReg.lastIndex = closeTag.index;\n const doubleQuoteMatch = doubleQuoteReg.exec(str);\n\n if (doubleQuoteMatch) {\n parseCloseReg.lastIndex = doubleQuoteReg.lastIndex;\n } else {\n ParseErr(\"unclosed string\", str, closeTag.index);\n }\n } else if (char === \"`\") {\n templateLitReg.lastIndex = closeTag.index;\n const templateLitMatch = templateLitReg.exec(str);\n if (templateLitMatch) {\n parseCloseReg.lastIndex = templateLitReg.lastIndex;\n } else {\n ParseErr(\"unclosed string\", str, closeTag.index);\n }\n }\n }\n }\n if (currentObj) {\n if (config.debug) {\n currentObj.lineNo = getLineNo(str, m.index);\n }\n buffer.push(currentObj);\n } else {\n ParseErr(\"unclosed tag\", str, m.index);\n }\n }\n\n pushString(str.slice(lastIndex, str.length), false);\n\n if (config.plugins) {\n for (let i = 0; i < config.plugins.length; i++) {\n const plugin = config.plugins[i];\n if (plugin.processAST) {\n buffer = plugin.processAST(buffer, config);\n }\n }\n }\n\n return buffer;\n}\n","import type { TemplateFunction } from \"./compile.ts\";\n\n/* TYPES */\nimport type { Options } from \"./config.ts\";\nimport { EtaNameResolutionError } from \"./err.ts\";\nimport type { Eta } from \"./internal.ts\";\n\n/* END TYPES */\n\nfunction handleCache(\n this: Eta,\n template: string,\n options: Partial<Options>,\n): TemplateFunction {\n const templateStore = options?.async\n ? this.templatesAsync\n : this.templatesSync;\n\n if (this.resolvePath && this.readFile && !template.startsWith(\"@\")) {\n const templatePath = options.filepath as string;\n\n const cachedTemplate = templateStore.get(templatePath);\n\n if (this.config.cache && cachedTemplate) {\n return cachedTemplate;\n } else {\n const templateString = this.readFile(templatePath);\n\n const templateFn = this.compile(templateString, options);\n\n if (this.config.cache) templateStore.define(templatePath, templateFn);\n\n return templateFn;\n }\n } else {\n const cachedTemplate = templateStore.get(template);\n\n if (cachedTemplate) {\n return cachedTemplate;\n } else {\n throw new EtaNameResolutionError(`Failed to get template '${template}'`);\n }\n }\n}\n\nexport function render<T extends object>(\n this: Eta,\n template: string | TemplateFunction, // template name or template function\n data: T,\n meta?: { filepath: string },\n): string {\n let templateFn: TemplateFunction;\n const options = { ...meta, async: false };\n\n if (typeof template === \"string\") {\n if (this.resolvePath && this.readFile && !template.startsWith(\"@\")) {\n options.filepath = this.resolvePath(template, options);\n }\n\n templateFn = handleCache.call(this, template, options);\n } else {\n templateFn = template;\n }\n\n const res = templateFn.call(this, data, options);\n\n return res;\n}\n\nexport function renderAsync<T extends object>(\n this: Eta,\n template: string | TemplateFunction, // template name or template function\n data: T,\n meta?: { filepath: string },\n): Promise<string> {\n let templateFn: TemplateFunction;\n const options = { ...meta, async: true };\n\n if (typeof template === \"string\") {\n if (this.resolvePath && this.readFile && !template.startsWith(\"@\")) {\n options.filepath = this.resolvePath(template, options);\n }\n\n templateFn = handleCache.call(this, template, options);\n } else {\n templateFn = template;\n }\n\n const res = templateFn.call(this, data, options);\n\n // Return a promise\n return Promise.resolve(res);\n}\n\nexport function renderString<T extends object>(\n this: Eta,\n template: string,\n data: T,\n): string {\n const templateFn = this.compile(template, { async: false });\n\n return render.call(this, templateFn, data);\n}\n\nexport function renderStringAsync<T extends object>(\n this: Eta,\n template: string,\n data: T,\n): Promise<string> {\n const templateFn = this.compile(template, { async: true });\n\n return renderAsync.call(this, templateFn, data);\n}\n","/**\n * Handles storage and accessing of values\n *\n * In this case, we use it to store compiled template functions\n * Indexed by their `name` or `filename`\n */\n\nexport class Cacher<T> {\n constructor(private cache: Record<string, T>) {}\n define(key: string, val: T): void {\n this.cache[key] = val;\n }\n get(key: string): T {\n return this.cache[key];\n }\n remove(key: string): void {\n delete this.cache[key];\n }\n reset(): void {\n this.cache = {};\n }\n load(cacheObj: Record<string, T>): void {\n this.cache = { ...this.cache, ...cacheObj };\n }\n}\n","import type { TemplateFunction } from \"./compile.ts\";\nimport { compile } from \"./compile.ts\";\nimport { compileBody, compileToString } from \"./compile-string.ts\";\nimport type { EtaConfig, Options } from \"./config.ts\";\nimport { defaultConfig } from \"./config.ts\";\nimport { EtaError, RuntimeErr } from \"./err.ts\";\nimport { parse } from \"./parse.ts\";\nimport {\n render,\n renderAsync,\n renderString,\n renderStringAsync,\n} from \"./render.ts\";\nimport { Cacher } from \"./storage.ts\";\n\nexport class Eta {\n constructor(customConfig?: Partial<EtaConfig>) {\n if (customConfig) {\n this.config = { ...defaultConfig, ...customConfig };\n } else {\n this.config = { ...defaultConfig };\n }\n }\n\n config: EtaConfig;\n\n RuntimeErr = RuntimeErr;\n\n compile = compile;\n compileToString = compileToString;\n compileBody = compileBody;\n parse = parse;\n render = render;\n renderAsync = renderAsync;\n renderString = renderString;\n renderStringAsync = renderStringAsync;\n\n filepathCache: Record<string, string> = {};\n templatesSync: Cacher<TemplateFunction> = new Cacher<TemplateFunction>({});\n templatesAsync: Cacher<TemplateFunction> = new Cacher<TemplateFunction>({});\n\n // resolvePath takes a relative path from the \"views\" directory\n resolvePath:\n | null\n | ((this: Eta, template: string, options?: Partial<Options>) => string) =\n null;\n readFile: null | ((this: Eta, path: string) => string) = null;\n\n // METHODS\n\n configure(customConfig: Partial<EtaConfig>) {\n this.config = { ...this.config, ...customConfig };\n }\n\n withConfig(customConfig: Partial<EtaConfig>): this & { config: EtaConfig } {\n return { ...this, config: { ...this.config, ...customConfig } };\n }\n\n loadTemplate(\n name: string,\n template: string | TemplateFunction, // template string or template function\n options?: { async: boolean },\n ): void {\n if (typeof template === \"string\") {\n const templates = options?.async\n ? this.templatesAsync\n : this.templatesSync;\n\n templates.define(name, this.compile(template, options));\n } else {\n let templates = this.templatesSync;\n\n if (template.constructor.name === \"AsyncFunction\" || options?.async) {\n templates = this.templatesAsync;\n }\n\n templates.define(name, template);\n }\n }\n}\n\n// for instance checking against thrown errors\nexport { EtaError };\n","import { readFile, resolvePath } from \"./file-handling.ts\";\nimport { Eta as EtaCore } from \"./internal.ts\";\n\nexport type { TemplateFunction } from \"./compile.ts\";\nexport type { EtaConfig, Options } from \"./config.ts\";\nexport {\n EtaError,\n EtaFileResolutionError,\n EtaNameResolutionError,\n EtaParseError,\n EtaRuntimeError,\n} from \"./err.ts\";\n\nexport class Eta extends EtaCore {\n readFile = readFile;\n\n resolvePath = resolvePath;\n}\n","/**\n * Template engine types.\n *\n * Defines the context object ($) available in templates, loader interfaces,\n * and configuration options for the template engine.\n */\n\n/**\n * Built-in helper functions available on the template context.\n */\nexport interface BuiltInHelpers {\n /**\n * Include another SQL file.\n * Path is resolved relative to the template's directory.\n *\n * @example\n * ```sql\n * {%~ await $.include('lib/uuid_function.sql') %}\n * ```\n */\n include: (path: string) => Promise<string>;\n\n /**\n * SQL-escape a string value.\n * Escapes single quotes by doubling them.\n *\n * @example\n * ```sql\n * WHERE name = '{%~ $.escape(userName) %}'\n * ```\n */\n escape: (value: string) => string;\n\n /**\n * SQL-escape and wrap in single quotes.\n *\n * @example\n * ```sql\n * INSERT INTO users (name) VALUES ({%~ $.quote(userName) %});\n * ```\n */\n quote: (value: string | number | boolean | null) => string;\n\n /**\n * JSON stringify a value.\n *\n * @example\n * ```sql\n * INSERT INTO config (data) VALUES ('{%~ $.json(configObject) %}');\n * ```\n */\n json: (value: unknown) => string;\n\n /**\n * Current ISO timestamp.\n *\n * @example\n * ```sql\n * INSERT INTO logs (created_at) VALUES ('{%~ $.now() %}');\n * ```\n */\n now: () => string;\n\n /**\n * Generate a UUID v4.\n *\n * @example\n * ```sql\n * INSERT INTO users (id) VALUES ('{%~ $.uuid() %}');\n * ```\n */\n uuid: () => string;\n}\n\n/**\n * Template context object ($) available in templates.\n *\n * Contains auto-loaded data, inherited helpers, secrets, and built-in functions.\n */\nexport interface TemplateContext extends BuiltInHelpers {\n /**\n * Active configuration object.\n * Only available if no `config.*` file exists in the template directory.\n */\n config?: Record<string, unknown>;\n\n /**\n * Decrypted secrets for the active config.\n */\n secrets: Record<string, string>;\n\n /**\n * Decrypted global secrets (shared across configs).\n */\n globalSecrets: Record<string, string>;\n\n /**\n * Environment variables.\n */\n env: Record<string, string | undefined>;\n\n /**\n * Auto-loaded data files and inherited helpers.\n * Keys are camelCased filenames (e.g., `$.users`, `$.seedData`).\n */\n [key: string]: unknown;\n}\n\n/**\n * Result from a data loader.\n */\nexport interface LoaderResult {\n /**\n * The parsed data.\n */\n data: unknown;\n\n /**\n * Original file path.\n */\n filepath: string;\n\n /**\n * File extension (e.g., '.json5', '.yml').\n */\n format: string;\n}\n\n/**\n * A data file loader function.\n */\nexport type Loader = (filepath: string) => Promise<unknown>;\n\n/**\n * Registry of loaders by file extension.\n */\nexport type LoaderRegistry = Record<string, Loader>;\n\n/**\n * Options for rendering a template.\n */\nexport interface RenderOptions {\n /**\n * Active configuration to include in context.\n */\n config?: Record<string, unknown>;\n\n /**\n * Secrets for the active config.\n */\n secrets?: Record<string, string>;\n\n /**\n * Global secrets shared across configs.\n */\n globalSecrets?: Record<string, string>;\n\n /**\n * Project root directory.\n * Used to determine where to stop walking up for helpers.\n * Defaults to process.cwd().\n */\n projectRoot?: string;\n}\n\n/**\n * Result of processing a SQL file.\n */\nexport interface ProcessResult {\n /**\n * The SQL content (rendered if template, raw if .sql).\n */\n sql: string;\n\n /**\n * Whether the file was a template.\n */\n isTemplate: boolean;\n\n /**\n * Render duration in milliseconds (only for templates).\n */\n durationMs?: number;\n}\n\n/**\n * Supported data file extensions.\n */\nexport const DATA_EXTENSIONS = [\n '.json',\n '.json5',\n '.yaml',\n '.yml',\n '.csv',\n '.js',\n '.mjs',\n '.ts',\n '.sql',\n] as const;\n\n/**\n * Template file extension.\n */\nexport const TEMPLATE_EXTENSION = '.tmpl';\n\n/**\n * Helper file name pattern.\n */\nexport const HELPER_FILENAME = '$helpers';\n\n/**\n * Supported helper file extensions.\n */\nexport const HELPER_EXTENSIONS = ['.ts', '.js', '.mjs'] as const;\n","/**\n * JavaScript/TypeScript module loader.\n *\n * Loads .js, .mjs, and .ts files via dynamic import.\n * Returns module.default if available, otherwise the entire module.\n *\n * In compiled Bun binaries, bare specifier resolution fails because\n * the binary's resolver uses its virtual $bunfs. We use Bun.build()\n * to bundle the file with all dependencies resolved, then import\n * the bundled output.\n *\n * @example\n * ```typescript\n * const data = await loadJs('/path/to/helpers.ts')\n * ```\n */\nimport { dirname, join } from 'node:path';\nimport { unlinkSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport { randomBytes } from 'node:crypto';\n\nconst IS_COMPILED = import.meta.url.includes('$bunfs');\n\n/**\n * Load a JavaScript or TypeScript module.\n *\n * Uses dynamic import to load the module. If the module has a default\n * export, returns that. Otherwise returns the entire module object.\n *\n * @param filepath - Absolute path to the JS/TS file\n * @returns The module's default export or the entire module\n * @throws If file cannot be imported\n */\nexport async function loadJs(filepath: string): Promise<unknown> {\n\n const mod = IS_COMPILED\n ? await loadWithBunBuild(filepath)\n : await loadWithImport(filepath);\n\n // Return default export if available, otherwise the whole module\n return mod['default'] !== undefined ? mod['default'] : mod;\n\n}\n\n/**\n * Load a module using Bun.build() for compiled binary context.\n *\n * Bun.build() resolves all bare specifiers and bundles them into\n * a single self-contained file, bypassing the $bunfs resolver.\n */\nasync function loadWithBunBuild(filepath: string): Promise<Record<string, unknown>> {\n\n const fileDir = dirname(filepath);\n const tmpFile = join(fileDir, `.noorm-helper-${randomBytes(8).toString('hex')}.js`);\n\n const result = await Bun.build({\n entrypoints: [filepath],\n outdir: fileDir,\n naming: tmpFile.split('/').pop()!,\n target: 'bun',\n format: 'esm',\n });\n\n if (!result.success) {\n\n const messages = result.logs.map(l => l.message).join('; ');\n throw new Error(`Failed to bundle ${filepath}: ${messages}`);\n\n }\n\n const mod = await import(pathToFileURL(tmpFile).href);\n\n unlinkSync(tmpFile);\n\n return mod as Record<string, unknown>;\n\n}\n\n/**\n * Load a module via dynamic import().\n *\n * Used in dev mode (node/bun from dist/) where import() resolves\n * bare specifiers correctly from the file's location.\n */\nasync function loadWithImport(filepath: string): Promise<Record<string, unknown>> {\n\n const url = pathToFileURL(filepath).href;\n\n // Cache-busting query param to avoid stale imports\n const urlWithCacheBust = `${url}?t=${Date.now()}`;\n\n return await import(urlWithCacheBust) as Record<string, unknown>;\n\n}\n","/**\n * Helper file tree walker.\n *\n * Walks up the directory tree from a template's location to the project root,\n * collecting and merging $helpers.ts files. Child helpers override parent helpers.\n *\n * @example\n * ```typescript\n * import { loadHelpers } from './helpers'\n *\n * // Given structure:\n * // sql/\n * // ├── $helpers.ts ← loaded first (base)\n * // └── users/\n * // ├── $helpers.ts ← loaded second (overrides)\n * // └── 001_create.sql.tmpl\n *\n * const helpers = await loadHelpers('/project/sql/users', '/project')\n * // helpers contains merged exports from both files\n * ```\n */\nimport path from 'node:path';\nimport { stat } from 'node:fs/promises';\n\nimport { attempt } from '@logosdx/utils';\n\nimport { observer } from '../observer.js';\nimport { HELPER_FILENAME, HELPER_EXTENSIONS } from './types.js';\nimport { loadJs } from './loaders/js.js';\n\n/**\n * Find all helper files from a directory up to the project root.\n *\n * Returns paths in order from root to leaf (so child can override parent).\n *\n * @param fromDir - Starting directory (template's directory)\n * @param projectRoot - Project root directory (stop walking here)\n * @returns Array of helper file paths, ordered root to leaf\n */\nexport async function findHelperFiles(fromDir: string, projectRoot: string): Promise<string[]> {\n\n const helperPaths: string[] = [];\n let currentDir = path.resolve(fromDir);\n const root = path.resolve(projectRoot);\n\n // Walk up until we reach or pass the project root\n while (currentDir.startsWith(root)) {\n\n const helperPath = await findHelperInDir(currentDir);\n\n if (helperPath) {\n\n // Prepend so we get root-to-leaf order\n helperPaths.unshift(helperPath);\n\n }\n\n // Move up one directory\n const parentDir = path.dirname(currentDir);\n\n // Stop if we've reached the root or can't go higher\n if (parentDir === currentDir) {\n\n break;\n\n }\n\n currentDir = parentDir;\n\n }\n\n return helperPaths;\n\n}\n\n/**\n * Find a helper file in a directory.\n *\n * Checks for $helpers.ts, $helpers.js, $helpers.mjs in order.\n *\n * @param dir - Directory to search\n * @returns Path to helper file if found, null otherwise\n */\nasync function findHelperInDir(dir: string): Promise<string | null> {\n\n for (const ext of HELPER_EXTENSIONS) {\n\n const filepath = path.join(dir, `${HELPER_FILENAME}${ext}`);\n const [stats] = await attempt(() => stat(filepath));\n\n if (stats?.isFile()) {\n\n return filepath;\n\n }\n\n }\n\n return null;\n\n}\n\n/**\n * Load and merge helper files from a directory tree.\n *\n * Walks up from the template directory to the project root, loading each\n * $helpers.ts file found. Later helpers (closer to template) override\n * earlier helpers (closer to root).\n *\n * @param fromDir - Template's directory\n * @param projectRoot - Project root directory\n * @returns Merged helper exports\n *\n * @example\n * ```typescript\n * const helpers = await loadHelpers('/project/sql/users', '/project')\n * // helpers.padId() from sql/users/$helpers.ts\n * // helpers.formatDate() from sql/$helpers.ts\n * ```\n */\n/**\n * Error encountered while loading a $helpers file.\n */\nexport interface HelperLoadError {\n filepath: string;\n error: Error;\n}\n\n/**\n * Result from loading helpers, including any load errors.\n */\nexport interface LoadHelpersResult {\n helpers: Record<string, unknown>;\n errors: HelperLoadError[];\n}\n\nexport async function loadHelpers(\n fromDir: string,\n projectRoot: string,\n): Promise<LoadHelpersResult> {\n\n const helperPaths = await findHelperFiles(fromDir, projectRoot);\n const merged: Record<string, unknown> = {};\n const errors: HelperLoadError[] = [];\n\n for (const filepath of helperPaths) {\n\n const [mod, err] = await attempt(() => loadJs(filepath));\n\n if (err) {\n\n errors.push({ filepath, error: err });\n\n observer.emit('error', {\n source: 'template',\n error: err,\n context: { filepath, operation: 'load-helpers' },\n });\n continue;\n\n }\n\n // Merge exports (later files override earlier)\n if (mod && typeof mod === 'object') {\n\n const exports = mod as Record<string, unknown>;\n const exportCount = Object.keys(exports).length;\n\n Object.assign(merged, exports);\n\n observer.emit('template:helpers', {\n filepath,\n count: exportCount,\n });\n\n }\n\n }\n\n return { helpers: merged, errors };\n\n}\n","/**\n * SQL file loader.\n *\n * Loads .sql files as raw text strings.\n * Used for including SQL fragments in templates.\n *\n * @example\n * ```typescript\n * const sql = await loadSql('/path/to/fragment.sql')\n * ```\n */\nimport { readFile } from 'node:fs/promises';\n\n/**\n * Load a SQL file as text.\n *\n * @param filepath - Absolute path to the SQL file\n * @returns The SQL file content as a string\n * @throws If file cannot be read\n */\nexport async function loadSql(filepath: string): Promise<string> {\n\n return readFile(filepath, 'utf-8');\n\n}\n","/**\n * Constants for the .dt format.\n *\n * Defines thresholds for smart compression decisions and type classification sets.\n */\nimport type { EncodedType, SimpleType } from './types.js';\n\n/**\n * Current .dt format version.\n */\nexport const FORMAT_VERSION = 1;\n\n/**\n * Minimum byte size before considering gzip compression.\n *\n * Values smaller than this threshold remain uncompressed for readability.\n * 128 bytes is the sweet spot: below this, gzip overhead exceeds savings.\n */\nexport const GZIP_THRESHOLD = 128;\n\n/**\n * Maximum gzip-to-raw ratio to accept compression.\n *\n * Gzip must save at least 15% (ratio < 0.85) to be worth the overhead.\n * Incompressible data (random bytes, already-compressed content) stays raw.\n */\nexport const GZIP_RATIO_THRESHOLD = 0.85;\n\n/**\n * Simple types stored as native JSON values.\n *\n * Uses boolean hash for O(1) lookups.\n */\nexport const SIMPLE_TYPES: { [key in SimpleType]: true } = {\n string: true,\n int: true,\n bigint: true,\n float: true,\n decimal: true,\n bool: true,\n timestamp: true,\n date: true,\n uuid: true,\n};\n\n/**\n * Encoded types that use `[value, encoding]` tuples.\n *\n * Uses boolean hash for O(1) lookups.\n */\nexport const ENCODED_TYPES: { [key in EncodedType]: true } = {\n json: true,\n binary: true,\n vector: true,\n array: true,\n text: true,\n custom: true,\n};\n\n/**\n * Valid .dt file extensions.\n */\nexport const DT_EXTENSIONS = {\n /** Raw .dt file (uncompressed JSON5 lines). */\n RAW: '.dt',\n /** Gzip-compressed .dt file. */\n COMPRESSED: '.dtz',\n /** Gzip-compressed and AES-256-GCM encrypted .dt file. */\n ENCRYPTED: '.dtzx',\n} as const;\n\n/**\n * Supported database dialects for .dt operations.\n */\nexport const DT_SUPPORTED_DIALECTS = ['postgres', 'mysql', 'mssql'] as const;\n","/**\n * Passphrase-based encryption for .dtzx files.\n *\n * Self-contained AES-256-GCM encryption using PBKDF2 key derivation.\n * Independent of the identity system — uses a user-provided passphrase.\n *\n * @example\n * ```typescript\n * import { encryptWithPassphrase, decryptWithPassphrase } from './crypto.js';\n *\n * const payload = encryptWithPassphrase(data, 'my-secret');\n * const decrypted = decryptWithPassphrase(payload, 'my-secret');\n * ```\n */\nimport {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n pbkdf2Sync,\n} from 'node:crypto';\n\nimport type { DtEncryptedPayload } from './types.js';\n\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_LENGTH = 16;\nconst SALT_LENGTH = 32;\nconst AUTH_TAG_LENGTH = 16;\nconst KEY_LENGTH = 32;\nconst PBKDF2_ITERATIONS = 100_000;\nconst PBKDF2_DIGEST = 'sha256';\n\n/**\n * Encrypt data with a passphrase using AES-256-GCM.\n *\n * Derives a key from the passphrase using PBKDF2 with a random salt.\n * Each call generates a new salt and IV for unique ciphertexts.\n *\n * @param data - Data to encrypt\n * @param passphrase - User-provided encryption passphrase\n * @returns Encrypted payload with salt, IV, authTag, and ciphertext\n *\n * @example\n * ```typescript\n * const compressed = gzipSync(fileContent);\n * const payload = encryptWithPassphrase(compressed, 'my-passphrase');\n * ```\n */\nexport function encryptWithPassphrase(data: Buffer, passphrase: string): DtEncryptedPayload {\n\n const salt = randomBytes(SALT_LENGTH);\n const iv = randomBytes(IV_LENGTH);\n\n const key = pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);\n\n const cipher = createCipheriv(ALGORITHM, key, iv, {\n authTagLength: AUTH_TAG_LENGTH,\n });\n\n const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);\n const authTag = cipher.getAuthTag();\n\n return {\n salt: salt.toString('base64'),\n iv: iv.toString('base64'),\n authTag: authTag.toString('base64'),\n ciphertext: ciphertext.toString('base64'),\n };\n\n}\n\n/**\n * Decrypt a payload using a passphrase.\n *\n * Derives the same key using PBKDF2 with the stored salt,\n * then decrypts and verifies with AES-256-GCM.\n *\n * @param payload - Encrypted payload from encryptWithPassphrase\n * @param passphrase - Same passphrase used for encryption\n * @returns Decrypted data buffer\n * @throws If passphrase is wrong or data is tampered\n *\n * @example\n * ```typescript\n * const decrypted = decryptWithPassphrase(payload, 'my-passphrase');\n * const content = gunzipSync(decrypted);\n * ```\n */\nexport function decryptWithPassphrase(payload: DtEncryptedPayload, passphrase: string): Buffer {\n\n const salt = Buffer.from(payload.salt, 'base64');\n const iv = Buffer.from(payload.iv, 'base64');\n const authTag = Buffer.from(payload.authTag, 'base64');\n const ciphertext = Buffer.from(payload.ciphertext, 'base64');\n\n const key = pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);\n\n const decipher = createDecipheriv(ALGORITHM, key, iv, {\n authTagLength: AUTH_TAG_LENGTH,\n });\n\n decipher.setAuthTag(authTag);\n\n const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);\n\n return decrypted;\n\n}\n","/**\n * Streaming .dt file reader.\n *\n * Reads .dt files with extension-based input handling:\n * - `.dt`: raw text readline\n * - `.dtz`: gunzip then readline\n * - `.dtzx`: decrypt then gunzip then readline\n *\n * @example\n * ```typescript\n * import { DtReader } from './reader.js';\n *\n * const reader = new DtReader({ filepath: './data/users.dtz' });\n * await reader.open();\n *\n * const schema = reader.schema;\n *\n * for await (const values of reader.rows()) {\n * // values is DtValue[]\n * }\n *\n * reader.close();\n * ```\n */\nimport { createReadStream, readFileSync } from 'node:fs';\nimport { createGunzip } from 'node:zlib';\nimport { gunzipSync } from 'node:zlib';\nimport { createInterface } from 'node:readline';\nimport { PassThrough } from 'node:stream';\nimport path from 'node:path';\nimport JSON5 from 'json5';\n\nimport type { Readable } from 'node:stream';\nimport type { DtSchema, DtValue, DtReaderOptions } from './types.js';\nimport { DT_EXTENSIONS } from './constants.js';\nimport { decryptWithPassphrase } from './crypto.js';\n\n/**\n * Streaming .dt file reader.\n *\n * Handles raw, compressed, and encrypted input based on file extension.\n * Provides schema access and async iteration over rows.\n */\nexport class DtReader {\n\n #filepath: string;\n #passphrase?: string;\n #extension: string;\n #schema: DtSchema | null = null;\n #lineReader: AsyncGenerator<DtValue[], void, undefined> | null = null;\n #inputStream: Readable | null = null;\n\n /**\n * Create a new DtReader.\n *\n * @param options - File path and optional passphrase for .dtzx\n */\n constructor(options: DtReaderOptions) {\n\n this.#filepath = options.filepath;\n this.#passphrase = options.passphrase;\n this.#extension = path.extname(options.filepath).toLowerCase();\n\n }\n\n /** The parsed schema from line 1. Available after open(). */\n get schema(): DtSchema | null {\n\n return this.#schema;\n\n }\n\n /**\n * Open the file and parse the schema header.\n *\n * Must be called before iterating rows.\n */\n async open(): Promise<void> {\n\n const readable = this.#createReadableStream();\n this.#inputStream = readable;\n\n // Read first line as schema\n const rl = createInterface({ input: readable, crlfDelay: Infinity });\n const lines = rl[Symbol.asyncIterator]();\n const firstLine = await lines.next();\n\n if (firstLine.done || !firstLine.value) {\n\n throw new Error('Empty .dt file — no schema line');\n\n }\n\n this.#schema = JSON5.parse(firstLine.value) as DtSchema;\n\n // Validate version\n if (this.#schema.v !== 1) {\n\n throw new Error(`Unsupported .dt format version: ${this.#schema.v}`);\n\n }\n\n // Store iterator for rows\n this.#lineReader = this.#createRowIterator(lines);\n\n }\n\n /**\n * Async generator yielding parsed row value arrays.\n *\n * Each yield is a `DtValue[]` in column order matching the schema.\n *\n * @example\n * ```typescript\n * for await (const values of reader.rows()) {\n * console.log(values); // [1, \"alice@example.com\", true, \"2024-01-15T10:30:00Z\"]\n * }\n * ```\n */\n async *rows(): AsyncGenerator<DtValue[], void, undefined> {\n\n if (!this.#lineReader) {\n\n throw new Error('Reader not opened — call open() first');\n\n }\n\n yield* this.#lineReader;\n\n }\n\n /**\n * Close the reader and release resources.\n */\n close(): void {\n\n if (this.#inputStream) {\n\n this.#inputStream.destroy();\n this.#inputStream = null;\n\n }\n\n }\n\n /**\n * Create the readable stream based on file extension.\n */\n #createReadableStream(): Readable {\n\n if (this.#extension === DT_EXTENSIONS.ENCRYPTED) {\n\n // .dtzx: read all, decrypt, gunzip, create readable from buffer\n if (!this.#passphrase) {\n\n throw new Error('Passphrase required for .dtzx files');\n\n }\n\n const encrypted = readFileSync(this.#filepath, 'utf8');\n const payload = JSON.parse(encrypted);\n const compressed = decryptWithPassphrase(payload, this.#passphrase);\n const raw = gunzipSync(compressed);\n\n const stream = new PassThrough();\n stream.end(raw);\n\n return stream;\n\n }\n\n if (this.#extension === DT_EXTENSIONS.COMPRESSED) {\n\n // .dtz: pipe through gunzip\n const fileStream = createReadStream(this.#filepath);\n const gunzip = createGunzip();\n\n fileStream.pipe(gunzip);\n\n return gunzip;\n\n }\n\n // .dt: raw file stream\n return createReadStream(this.#filepath, { encoding: 'utf8' });\n\n }\n\n /**\n * Create async generator from remaining readline lines.\n */\n async *#createRowIterator(\n lines: AsyncIterableIterator<string>,\n ): AsyncGenerator<DtValue[], void, undefined> {\n\n for await (const line of { [Symbol.asyncIterator]: () => lines }) {\n\n const trimmed = line.trim();\n\n if (trimmed.length === 0) continue;\n\n yield JSON5.parse(trimmed) as DtValue[];\n\n }\n\n }\n\n}\n","/**\n * .dt file loader for template seed data.\n *\n * Loads .dt and .dtz files as arrays of row objects.\n * Does NOT support .dtzx — no way to provide a decryption\n * key in the template context.\n *\n * @example\n * ```typescript\n * import { loadDt } from './dt.js';\n *\n * const rows = await loadDt('/path/to/seed.dt');\n * // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]\n * ```\n */\nimport { DtReader } from '../../dt/reader.js';\n\n/**\n * Load a .dt or .dtz file as an array of row objects.\n *\n * Reads the schema to get column names, then maps each row's\n * positional values to named fields.\n *\n * @param filepath - Path to .dt or .dtz file\n * @returns Array of row objects with column names as keys\n * @throws If the file cannot be read or parsed\n *\n * @example\n * ```typescript\n * // Given a .dt file with columns [id, name, active]:\n * const data = await loadDt('./seeds/users.dt');\n * // [{ id: 1, name: 'Alice', active: true }, ...]\n * ```\n */\nexport async function loadDt(filepath: string): Promise<Record<string, unknown>[]> {\n\n const reader = new DtReader({ filepath });\n\n await reader.open();\n\n const schema = reader.schema;\n\n if (!schema) {\n\n throw new Error(`Failed to read .dt schema from: ${filepath}`);\n\n }\n\n const columnNames = schema.columns.map((c) => c.name);\n const rows: Record<string, unknown>[] = [];\n\n for await (const values of reader.rows()) {\n\n const row: Record<string, unknown> = {};\n\n for (let i = 0; i < columnNames.length; i++) {\n\n row[columnNames[i]!] = values[i] ?? null;\n\n }\n\n rows.push(row);\n\n }\n\n reader.close();\n\n return rows;\n\n}\n","/**\n * Loader registry for data files.\n *\n * Maps file extensions to their respective loader functions.\n * Provides a unified interface for loading any supported data format.\n *\n * Loaders with external dependencies (json5, yaml, csv-parse) are\n * lazy-loaded on first use to avoid pulling heavy parsers into the\n * bundle when they aren't needed.\n *\n * @example\n * ```typescript\n * import { loadDataFile, getLoader, hasLoader } from './loaders'\n *\n * if (hasLoader('.json5')) {\n * const data = await loadDataFile('/path/to/config.json5')\n * }\n * ```\n */\nimport path from 'node:path';\n\nimport type { Loader, LoaderRegistry } from '../types.js';\nimport { loadJs } from './js.js';\nimport { loadSql } from './sql.js';\nimport { loadDt } from './dt.js';\n\n// ─────────────────────────────────────────────────────────────\n// Lazy Loaders\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Lazy wrapper for JSON5 loader.\n *\n * Defers `import('json5')` until a .json or .json5 file is loaded.\n */\nasync function lazyLoadJson5(filepath: string): Promise<unknown> {\n\n const { loadJson5 } = await import('./json5.js');\n\n return loadJson5(filepath);\n\n}\n\n/**\n * Lazy wrapper for YAML loader.\n *\n * Defers `import('yaml')` until a .yaml or .yml file is loaded.\n */\nasync function lazyLoadYaml(filepath: string): Promise<unknown> {\n\n const { loadYaml } = await import('./yaml.js');\n\n return loadYaml(filepath);\n\n}\n\n/**\n * Lazy wrapper for CSV loader.\n *\n * Defers `import('csv-parse/sync')` until a .csv file is loaded.\n */\nasync function lazyLoadCsv(filepath: string): Promise<unknown> {\n\n const { loadCsv } = await import('./csv.js');\n\n return loadCsv(filepath);\n\n}\n\n// ─────────────────────────────────────────────────────────────\n// Registry\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Registry of loaders by file extension.\n *\n * json5, yaml, and csv loaders are lazy — their parser libraries\n * are only imported when a file of that type is first loaded.\n */\nconst loaders: LoaderRegistry = {\n '.json': lazyLoadJson5,\n '.json5': lazyLoadJson5,\n '.yaml': lazyLoadYaml,\n '.yml': lazyLoadYaml,\n '.csv': lazyLoadCsv,\n '.js': loadJs,\n '.mjs': loadJs,\n '.ts': loadJs,\n '.sql': loadSql,\n '.dt': loadDt,\n '.dtz': loadDt,\n // NO .dtzx — can't provide passphrase in template context\n};\n\n/**\n * Check if a loader exists for the given extension.\n *\n * @param ext - File extension (e.g., '.json5')\n * @returns True if a loader is registered for this extension\n */\nexport function hasLoader(ext: string): boolean {\n\n return ext in loaders;\n\n}\n\n/**\n * Get the loader function for a file extension.\n *\n * @param ext - File extension (e.g., '.json5')\n * @returns The loader function, or undefined if not found\n */\nexport function getLoader(ext: string): Loader | undefined {\n\n return loaders[ext];\n\n}\n\n/**\n * Load a data file using the appropriate loader.\n *\n * Determines the loader from the file extension and loads the file.\n *\n * @param filepath - Absolute path to the data file\n * @returns The loaded and parsed data\n * @throws If no loader exists for the file extension\n * @throws If the file cannot be loaded or parsed\n *\n * @example\n * ```typescript\n * const users = await loadDataFile('/path/to/users.json5')\n * const config = await loadDataFile('/path/to/config.yml')\n * ```\n */\nexport async function loadDataFile(filepath: string): Promise<unknown> {\n\n const ext = path.extname(filepath).toLowerCase();\n const loader = getLoader(ext);\n\n if (!loader) {\n\n throw new Error(`No loader registered for extension: ${ext}`);\n\n }\n\n return loader(filepath);\n\n}\n\n/**\n * Get all supported data file extensions.\n *\n * @returns Array of supported extensions (e.g., ['.json', '.json5', '.yml', ...])\n */\nexport function getSupportedExtensions(): string[] {\n\n return Object.keys(loaders);\n\n}\n\n// Re-export individual loaders for direct use\nexport { loadJson5 } from './json5.js';\nexport { loadYaml } from './yaml.js';\nexport { loadCsv } from './csv.js';\nexport { loadJs } from './js.js';\nexport { loadSql } from './sql.js';\nexport { loadDt } from './dt.js';\n","/**\n * String transformation utilities using Voca.\n *\n * Provides consistent string transformations for converting filenames\n * to context property names.\n *\n * @example\n * ```typescript\n * import { toContextKey } from './utils'\n *\n * toContextKey('my-config.json5') // → 'myConfig'\n * toContextKey('seed_data.yml') // → 'seedData'\n * toContextKey('API_KEYS.json') // → 'apiKeys'\n * ```\n */\nimport path from 'node:path';\n\n/**\n * Convert a string to camelCase.\n *\n * Splits on hyphens, underscores, and case boundaries,\n * then joins with first word lowercased and rest capitalized.\n *\n * @param str - Input string in any casing\n * @returns camelCase string\n */\nfunction camelCase(str: string): string {\n\n const words = str\n .replace(/([a-z])([A-Z])/g, '$1 $2')\n .split(/[-_\\s]+/)\n .filter(Boolean);\n\n if (words.length === 0) return '';\n\n return words\n .map((w, i) => i === 0\n ? w.toLowerCase()\n : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())\n .join('');\n\n}\n\n/**\n * Convert a filename to a camelCase context key.\n *\n * Strips the file extension and converts the base name to camelCase.\n * Handles kebab-case, snake_case, and SCREAMING_CASE.\n *\n * @param filename - The filename to convert (e.g., 'my-config.json5')\n * @returns The camelCase key (e.g., 'myConfig')\n *\n * @example\n * ```typescript\n * toContextKey('my-config.json5') // → 'myConfig'\n * toContextKey('seed_data.yml') // → 'seedData'\n * toContextKey('API_KEYS.json') // → 'apiKeys'\n * toContextKey('users.csv') // → 'users'\n * ```\n */\nexport function toContextKey(filename: string): string {\n\n // Get basename without extension\n const ext = path.extname(filename);\n const base = path.basename(filename, ext);\n\n // Convert to camelCase\n return camelCase(base);\n\n}\n\n/**\n * SQL-escape a string value.\n *\n * Escapes single quotes by doubling them, which is the standard\n * SQL escape sequence for string literals.\n *\n * @param value - The string to escape\n * @returns The escaped string (without surrounding quotes)\n *\n * @example\n * ```typescript\n * sqlEscape(\"O'Brien\") // → \"O''Brien\"\n * sqlEscape(\"normal\") // → \"normal\"\n * ```\n */\nexport function sqlEscape(value: string): string {\n\n return value.replace(/'/g, \"''\");\n\n}\n\n/**\n * SQL-escape and wrap in single quotes.\n *\n * Handles null values and various types appropriately.\n *\n * @param value - The value to quote\n * @returns The quoted SQL literal\n *\n * @example\n * ```typescript\n * sqlQuote(\"O'Brien\") // → \"'O''Brien'\"\n * sqlQuote(42) // → \"'42'\"\n * sqlQuote(null) // → \"NULL\"\n * sqlQuote(true) // → \"'true'\"\n * ```\n */\nexport function sqlQuote(value: string | number | boolean | null): string {\n\n if (value === null) {\n\n return 'NULL';\n\n }\n\n return `'${sqlEscape(String(value))}'`;\n\n}\n\n/**\n * Generate a UUID v4.\n *\n * Uses crypto.randomUUID() for secure random generation.\n *\n * @returns A UUID v4 string\n *\n * @example\n * ```typescript\n * generateUuid() // → \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\nexport function generateUuid(): string {\n\n return crypto.randomUUID();\n\n}\n\n/**\n * Get current ISO timestamp.\n *\n * @returns ISO 8601 timestamp string\n *\n * @example\n * ```typescript\n * isoNow() // → \"2024-01-15T10:30:00.000Z\"\n * ```\n */\nexport function isoNow(): string {\n\n return new Date().toISOString();\n\n}\n","/**\n * Template context builder.\n *\n * Builds the $ context object available in templates by:\n * 1. Loading inherited helpers from $helpers.ts files\n * 2. Auto-loading data files from the template's directory\n * 3. Adding config, secrets, env, and built-in helpers\n *\n * @example\n * ```typescript\n * import { buildContext } from './context'\n *\n * const ctx = await buildContext('/project/sql/users/001_create.sql.tmpl', {\n * projectRoot: '/project',\n * config: activeConfig,\n * secrets: { API_KEY: '...' },\n * })\n *\n * // ctx now has: $.padId, $.users, $.config, $.secrets, $.quote, etc.\n * ```\n */\nimport path from 'node:path';\nimport { readdir } from 'node:fs/promises';\n\nimport { attempt } from '@logosdx/utils';\n\nimport { observer } from '../observer.js';\nimport type { TemplateContext, RenderOptions } from './types.js';\nimport { HELPER_FILENAME } from './types.js';\nimport { loadHelpers } from './helpers.js';\nimport { loadDataFile, hasLoader } from './loaders/index.js';\nimport { toContextKey, sqlEscape, sqlQuote, generateUuid, isoNow } from './utils.js';\n\n/**\n * Build the template context ($) for a template file.\n *\n * @param templatePath - Absolute path to the template file\n * @param options - Render options (config, secrets, projectRoot)\n * @returns The complete template context\n */\nexport async function buildContext(\n templatePath: string,\n options: RenderOptions = {},\n): Promise<TemplateContext> {\n\n const templateDir = path.dirname(templatePath);\n const projectRoot = options.projectRoot ?? process.cwd();\n\n // 1. Load inherited helpers\n const { helpers } = await loadHelpers(templateDir, projectRoot);\n\n // 2. Auto-load data files from template directory\n const dataFiles = await loadDataFilesInDir(templateDir);\n\n // 3. Check if data files include a config file\n const hasLocalConfig = 'config' in dataFiles;\n\n // 4. Build context with all components\n const ctx: TemplateContext = {\n // Inherited helpers (can be overridden by data files with same name)\n ...helpers,\n\n // Auto-loaded data files\n ...dataFiles,\n\n // Config (only if no local config.* file)\n ...(hasLocalConfig ? {} : { config: options.config }),\n\n // Secrets\n secrets: options.secrets ?? {},\n globalSecrets: options.globalSecrets ?? {},\n\n // Environment\n env: process.env as Record<string, string | undefined>,\n\n // Built-in helpers\n include: createIncludeHelper(templateDir, projectRoot, options),\n escape: sqlEscape,\n quote: sqlQuote,\n json: (value: unknown) => JSON.stringify(value),\n now: isoNow,\n uuid: generateUuid,\n };\n\n return ctx;\n\n}\n\n/**\n * Load all data files in a directory.\n *\n * Scans the directory for supported data file extensions and loads each one.\n * File names are converted to camelCase context keys.\n *\n * @param dir - Directory to scan\n * @returns Object with camelCased keys and loaded data\n */\nasync function loadDataFilesInDir(dir: string): Promise<Record<string, unknown>> {\n\n const data: Record<string, unknown> = {};\n\n const [entries, readErr] = await attempt(() => readdir(dir, { withFileTypes: true }));\n\n if (readErr || !entries) {\n\n observer.emit('error', {\n source: 'template',\n error: readErr ?? new Error('Failed to read directory'),\n context: { dir, operation: 'scan-data-files' },\n });\n\n return data;\n\n }\n\n for (const entry of entries) {\n\n // Skip directories\n if (!entry.isFile()) {\n\n continue;\n\n }\n\n // Skip dotfiles (includes helper files and temp files)\n if (entry.name.startsWith('.') || entry.name.startsWith(HELPER_FILENAME)) {\n\n continue;\n\n }\n\n // Skip template files\n if (entry.name.endsWith('.tmpl')) {\n\n continue;\n\n }\n\n const ext = path.extname(entry.name).toLowerCase();\n\n // Skip unsupported extensions\n if (!hasLoader(ext)) {\n\n continue;\n\n }\n\n // Skip .sql files in data loading (they're for include())\n if (ext === '.sql') {\n\n continue;\n\n }\n\n const filepath = path.join(dir, entry.name);\n const key = toContextKey(entry.name);\n\n const [loaded, loadErr] = await attempt(() => loadDataFile(filepath));\n\n if (loadErr) {\n\n observer.emit('error', {\n source: 'template',\n error: loadErr,\n context: { filepath, operation: 'load-data-file' },\n });\n continue;\n\n }\n\n data[key] = loaded;\n\n observer.emit('template:load', {\n filepath,\n format: ext,\n });\n\n }\n\n return data;\n\n}\n\n/**\n * Create the include() helper function.\n *\n * The include helper resolves paths relative to the template's directory\n * and cannot escape the project root. If the included file is a template\n * (.sql.tmpl), it will be rendered recursively with the same options.\n *\n * @param templateDir - Template's directory\n * @param projectRoot - Project root (cannot escape)\n * @param options - Render options for nested templates\n * @returns The include helper function\n */\nfunction createIncludeHelper(\n templateDir: string,\n projectRoot: string,\n options: RenderOptions,\n): (includePath: string) => Promise<string> {\n\n return async (includePath: string): Promise<string> => {\n\n // Resolve path relative to template directory\n const resolved = path.resolve(templateDir, includePath);\n\n // Security: ensure we don't escape project root\n if (!resolved.startsWith(projectRoot)) {\n\n throw new Error(`Include path escapes project root: ${includePath}`);\n\n }\n\n // If it's a template, render it recursively\n if (resolved.endsWith('.tmpl')) {\n\n // Dynamic import to avoid circular dependency\n const { processFile } = await import('./engine.js');\n const result = await processFile(resolved, options);\n\n return result.sql;\n\n }\n\n // Load raw file\n const [content, err] = await attempt(() => loadDataFile(resolved));\n\n if (err) {\n\n throw new Error(`Failed to include '${includePath}': ${err.message}`);\n\n }\n\n if (typeof content === 'string') {\n\n return content;\n\n }\n\n // Non-string content (shouldn't happen for .sql files)\n return JSON.stringify(content);\n\n };\n\n}\n","/**\n * Template engine using Eta.\n *\n * Wraps Eta with noorm's custom syntax and integrates with the context builder\n * for auto-loading data files and inherited helpers.\n *\n * @example\n * ```typescript\n * import { processFile, renderTemplate } from './engine'\n *\n * // Process any SQL file (template or raw)\n * const result = await processFile('/path/to/file.sql.tmpl', {\n * config: activeConfig,\n * secrets: { API_KEY: '...' },\n * })\n *\n * // Or render a template string directly\n * const sql = await renderTemplate(\n * '{% for (const r of $.roles) { %}...',\n * context,\n * )\n * ```\n */\nimport { readFile } from 'node:fs/promises';\n\nimport { Eta } from 'eta';\n\nimport { observer } from '../observer.js';\nimport type { TemplateContext, RenderOptions, ProcessResult } from './types.js';\nimport { TEMPLATE_EXTENSION } from './types.js';\nimport { buildContext } from './context.js';\n\n/**\n * Strips entire `-- {% ... %}` directive lines from templates.\n *\n * The `-- {% %}` convention keeps .sql.tmpl files valid SQL (directives\n * look like comments to SQL parsers). Before Eta processes the template,\n * this regex strips the `-- ` prefix, trailing whitespace, and the line's\n * newline from directive-only lines so they produce no output.\n *\n * Only matches lines where `-- {% ... %}` is the ONLY content (plus whitespace).\n * Regular SQL comments and inline tags are not affected.\n *\n * ` -- {% for (const x of $.items) { %}\\n` → `{% for (const x of $.items) { %}`\n * `SELECT 1; -- comment` → unchanged (no `{%`)\n * `-- {% if (x) { %} SELECT 1` → unchanged (content after tag)\n */\nconst DIRECTIVE_LINE_RE = /^[ \\t]*-- (\\{%.*?%\\})[ \\t]*$(?:\\r?\\n)?/gm;\n\n/**\n * Eta instance configured with noorm's custom syntax.\n *\n * Custom delimiters:\n * - `{% %}` for JavaScript code (instead of `<% %>`)\n * - `{%~ %}` for raw output (instead of `<%~ %>`)\n * - `$` as the context variable (instead of `it`)\n *\n * autoTrim is disabled. Instead, the `-- {% %}` directive-line convention\n * is handled by DIRECTIVE_LINE_RE which strips entire directive lines\n * (including their newline) before Eta parses. This avoids Eta's autoTrim\n * gotchas where leftTrim eats content newlines after interpolation tags\n * (e.g. `{%= item %}\\nAS` becoming `itemAS`).\n */\nconst eta = new Eta({\n // Custom tags for code blocks\n tags: ['{%', '%}'],\n\n // Variable name for context ($ instead of it)\n varName: '$',\n\n // Don't auto-escape (SQL doesn't need HTML escaping)\n autoEscape: false,\n\n // Disabled — directive-line stripping handles whitespace instead\n autoTrim: [false, false],\n\n // Allow async functions in templates\n useWith: false,\n\n // Don't cache templates (we handle caching at a higher level)\n cache: false,\n});\n\n/**\n * Check if a file path is a template.\n *\n * @param filepath - File path to check\n * @returns True if the file has the .tmpl extension\n */\nexport function isTemplate(filepath: string): boolean {\n\n return filepath.endsWith(TEMPLATE_EXTENSION);\n\n}\n\n/**\n * Render a template string with the given context.\n *\n * @param template - Template string with Eta syntax\n * @param context - The $ context object\n * @returns Rendered SQL string\n *\n * @example\n * ```typescript\n * const sql = await renderTemplate(\n * '{% for (const role of $.roles) { %}INSERT INTO roles (name) VALUES ({%~ $.quote(role) %});\\n{% } %}',\n * { roles: ['admin', 'user'], quote: sqlQuote }\n * )\n * ```\n */\nexport async function renderTemplate(template: string, context: TemplateContext): Promise<string> {\n\n // Strip entire -- {% %} directive lines so they produce no output.\n // The -- prefix keeps .tmpl files valid SQL; the regex removes the\n // prefix, trailing whitespace, and the line's newline.\n const prepared = template.replace(DIRECTIVE_LINE_RE, '$1');\n\n const result = await eta.renderStringAsync(prepared, context);\n\n // Strip leading/trailing blank lines — directive lines at template\n // boundaries and file-trailing newlines can leave empty lines\n return result.replace(/^\\n+|\\n+$/g, '');\n\n}\n\n/**\n * Process a SQL file.\n *\n * If the file is a template (.sql.tmpl), renders it with the context.\n * If it's a raw SQL file (.sql), returns the content as-is.\n *\n * @param filepath - Absolute path to the SQL file\n * @param options - Render options (config, secrets, projectRoot)\n * @returns Process result with SQL content and metadata\n *\n * @example\n * ```typescript\n * const result = await processFile('/project/sql/users/001_create.sql.tmpl', {\n * projectRoot: '/project',\n * config: { name: 'dev', connection: { ... } },\n * secrets: { API_KEY: 'secret123' },\n * })\n *\n * console.log(result.sql) // Rendered SQL\n * console.log(result.isTemplate) // true\n * console.log(result.durationMs) // 12\n * ```\n */\nexport async function processFile(\n filepath: string,\n options: RenderOptions = {},\n): Promise<ProcessResult> {\n\n // Read file content\n const content = await readFile(filepath, 'utf-8');\n\n // If not a template, return raw content\n if (!isTemplate(filepath)) {\n\n return {\n sql: content,\n isTemplate: false,\n };\n\n }\n\n // It's a template - build context and render\n const start = performance.now();\n\n const context = await buildContext(filepath, options);\n const sql = await renderTemplate(content, context);\n\n const durationMs = performance.now() - start;\n\n observer.emit('template:render', {\n filepath,\n durationMs,\n });\n\n return {\n sql,\n isTemplate: true,\n durationMs,\n };\n\n}\n\n/**\n * Process multiple SQL files.\n *\n * @param filepaths - Array of file paths to process\n * @param options - Render options\n * @returns Array of process results\n */\nexport async function processFiles(\n filepaths: string[],\n options: RenderOptions = {},\n): Promise<ProcessResult[]> {\n\n const results: ProcessResult[] = [];\n\n for (const filepath of filepaths) {\n\n const result = await processFile(filepath, options);\n results.push(result);\n\n }\n\n return results;\n\n}\n\n// Export the Eta instance for advanced usage\nexport { eta };\n"]}
@@ -0,0 +1,42 @@
1
+ import { createRequire } from 'module';
2
+
3
+ const require$1 = createRequire(import.meta.url);
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __require = /* @__PURE__ */ ((x) => typeof require$1 !== "undefined" ? require$1 : typeof Proxy !== "undefined" ? new Proxy(x, {
11
+ get: (a, b) => (typeof require$1 !== "undefined" ? require$1 : a)[b]
12
+ }) : x)(function(x) {
13
+ if (typeof require$1 !== "undefined") return require$1.apply(this, arguments);
14
+ throw Error('Dynamic require of "' + x + '" is not supported');
15
+ });
16
+ var __commonJS = (cb, mod) => function __require2() {
17
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, { get: all[name], enumerable: true });
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
+ // If the importer is in node compatibility mode or this is not an ESM
33
+ // file that has been converted to a CommonJS file using a Babel-
34
+ // compatible transform (i.e. "__esModule" has not been set), then set
35
+ // "default" to the CommonJS "module.exports" for node compatibility.
36
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37
+ mod
38
+ ));
39
+
40
+ export { __commonJS, __export, __require, __toESM };
41
+ //# sourceMappingURL=chunk-D2XW2UOP.js.map
42
+ //# sourceMappingURL=chunk-D2XW2UOP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-D2XW2UOP.js"}