@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,943 @@
1
+ import { createRequire } from 'module';
2
+ import { observer, attempt } from './chunk-UDUDHOIB.js';
3
+ import { dist_default } from './chunk-TBRUDUBQ.js';
4
+ import { readFile as readFile$1, readdir, stat } from 'fs/promises';
5
+ import * as fs from 'fs';
6
+ import { readFileSync, createReadStream, unlinkSync } from 'fs';
7
+ import * as path from 'path';
8
+ import path__default, { dirname, join } from 'path';
9
+ import { pathToFileURL } from 'url';
10
+ import { randomBytes, pbkdf2Sync, createCipheriv, createDecipheriv } from 'crypto';
11
+ import { gunzipSync, createGunzip } from 'zlib';
12
+ import { createInterface } from 'readline';
13
+ import { PassThrough } from 'stream';
14
+
15
+ createRequire(import.meta.url);
16
+ var EtaError = class extends Error {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = "Eta Error";
20
+ }
21
+ };
22
+ var EtaParseError = class extends EtaError {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "EtaParser Error";
26
+ }
27
+ };
28
+ var EtaRuntimeError = class extends EtaError {
29
+ constructor(message) {
30
+ super(message);
31
+ this.name = "EtaRuntime Error";
32
+ }
33
+ };
34
+ var EtaFileResolutionError = class extends EtaError {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "EtaFileResolution Error";
38
+ }
39
+ };
40
+ var EtaNameResolutionError = class extends EtaError {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = "EtaNameResolution Error";
44
+ }
45
+ };
46
+ function ParseErr(message, str, indx) {
47
+ const whitespace = str.slice(0, indx).split(/\n/);
48
+ const lineNo = whitespace.length;
49
+ const colNo = whitespace[lineNo - 1].length + 1;
50
+ message += " at line " + lineNo + " col " + colNo + ":\n\n " + str.split(/\n/)[lineNo - 1] + "\n " + Array(colNo).join(" ") + "^";
51
+ throw new EtaParseError(message);
52
+ }
53
+ function RuntimeErr(originalError, str, lineNo, path$1) {
54
+ const lines = str.split("\n");
55
+ const start = Math.max(lineNo - 3, 0);
56
+ const end = Math.min(lines.length, lineNo + 3);
57
+ const filename = path$1;
58
+ const context = lines.slice(start, end).map((line, i) => {
59
+ const curr = i + start + 1;
60
+ return (curr === lineNo ? " >> " : " ") + curr + "| " + line;
61
+ }).join("\n");
62
+ const err = new EtaRuntimeError((filename ? filename + ":" + lineNo + "\n" : "line " + lineNo + "\n") + context + "\n\n" + originalError.message);
63
+ err.name = originalError.name;
64
+ err.cause = originalError;
65
+ throw err;
66
+ }
67
+ function readFile(path$1) {
68
+ let res = "";
69
+ try {
70
+ res = fs.readFileSync(path$1, "utf8");
71
+ } catch (err) {
72
+ if (err?.code === "ENOENT") throw new EtaFileResolutionError(`Could not find template: ${path$1}`);
73
+ else throw err;
74
+ }
75
+ return res;
76
+ }
77
+ function resolvePath(templatePath, options) {
78
+ let resolvedFilePath = "";
79
+ const views = this.config.views;
80
+ if (!views) throw new EtaFileResolutionError("Views directory is not defined");
81
+ const baseFilePath = options?.filepath;
82
+ const defaultExtension = this.config.defaultExtension === void 0 ? ".eta" : this.config.defaultExtension;
83
+ const cacheIndex = JSON.stringify({
84
+ filename: baseFilePath,
85
+ path: templatePath,
86
+ views: this.config.views
87
+ });
88
+ templatePath += path.extname(templatePath) ? "" : defaultExtension;
89
+ if (baseFilePath) {
90
+ if (this.config.cacheFilepaths && this.filepathCache[cacheIndex]) return this.filepathCache[cacheIndex];
91
+ if (absolutePathRegExp.exec(templatePath)?.length) {
92
+ const formattedPath = templatePath.replace(/^\/*|^\\*/, "");
93
+ resolvedFilePath = path.join(views, formattedPath);
94
+ } else resolvedFilePath = path.join(path.dirname(baseFilePath), templatePath);
95
+ } else resolvedFilePath = path.join(views, templatePath);
96
+ if (dirIsChild(views, resolvedFilePath)) {
97
+ if (baseFilePath && this.config.cacheFilepaths) this.filepathCache[cacheIndex] = resolvedFilePath;
98
+ return resolvedFilePath;
99
+ } else throw new EtaFileResolutionError(`Template '${templatePath}' is not in the views directory`);
100
+ }
101
+ function dirIsChild(parent, dir) {
102
+ const relative2 = path.relative(parent, dir);
103
+ return relative2 && !relative2.startsWith("..") && !path.isAbsolute(relative2);
104
+ }
105
+ var absolutePathRegExp = /^\\|^\//;
106
+ var AsyncFunction = (async () => {
107
+ }).constructor;
108
+ function compile(str, options) {
109
+ const config = this.config;
110
+ const ctor = options?.async ? AsyncFunction : Function;
111
+ try {
112
+ return new ctor(config.varName, "options", this.compileToString.call(this, str, options));
113
+ } catch (e) {
114
+ if (e instanceof SyntaxError) throw new EtaParseError("Bad template syntax\n\n" + e.message + "\n" + Array(e.message.length + 1).join("=") + "\n" + this.compileToString.call(this, str, options) + "\n");
115
+ else throw e;
116
+ }
117
+ }
118
+ function compileToString(str, options) {
119
+ const config = this.config;
120
+ const isAsync = options?.async;
121
+ const compileBody$1 = this.compileBody;
122
+ const buffer = this.parse.call(this, str);
123
+ let res = `${config.functionHeader}
124
+ let include = (__eta_t, __eta_d) => this.render(__eta_t, {...${config.varName}, ...(__eta_d ?? {})}, options);
125
+ let includeAsync = (__eta_t, __eta_d) => this.renderAsync(__eta_t, {...${config.varName}, ...(__eta_d ?? {})}, options);
126
+
127
+ let __eta = {res: "", e: this.config.escapeFunction, f: this.config.filterFunction${config.debug ? ', line: 1, templateStr: "' + str.replace(/\\|"/g, "\\$&").replace(/\r\n|\n|\r/g, "\\n") + '"' : ""}};
128
+
129
+ function layout(path, data) {
130
+ __eta.layout = path;
131
+ __eta.layoutData = data;
132
+ }${config.debug ? "try {" : ""}${config.useWith ? "with(" + config.varName + "||{}){" : ""}
133
+
134
+ function ${config.outputFunctionName}(s){__eta.res+=s;}
135
+
136
+ ${compileBody$1.call(this, buffer)}
137
+ if (__eta.layout) {
138
+ __eta.res = ${isAsync ? "await includeAsync" : "include"} (__eta.layout, {...${config.varName}, body: __eta.res, ...__eta.layoutData});
139
+ }
140
+ ${config.useWith ? "}" : ""}${config.debug ? "} catch (e) { this.RuntimeErr(e, __eta.templateStr, __eta.line, options.filepath) }" : ""}
141
+ return __eta.res;
142
+ `;
143
+ if (config.plugins) for (let i = 0; i < config.plugins.length; i++) {
144
+ const plugin = config.plugins[i];
145
+ if (plugin.processFnString) res = plugin.processFnString(res, config);
146
+ }
147
+ return res;
148
+ }
149
+ function compileBody(buff) {
150
+ const config = this.config;
151
+ let i = 0;
152
+ const buffLength = buff.length;
153
+ let returnStr = "";
154
+ for (; i < buffLength; i++) {
155
+ const currentBlock = buff[i];
156
+ if (typeof currentBlock === "string") returnStr += "__eta.res+='" + currentBlock + "';\n";
157
+ else {
158
+ const type = currentBlock.t;
159
+ let content = currentBlock.val || "";
160
+ if (config.debug) returnStr += "__eta.line=" + currentBlock.lineNo + "\n";
161
+ if (type === "r") {
162
+ if (config.autoFilter) content = "__eta.f(" + content + ")";
163
+ returnStr += "__eta.res+=" + content + ";\n";
164
+ } else if (type === "i") {
165
+ if (config.autoFilter) content = "__eta.f(" + content + ")";
166
+ if (config.autoEscape) content = "__eta.e(" + content + ")";
167
+ returnStr += "__eta.res+=" + content + ";\n";
168
+ } else if (type === "e") returnStr += content + "\n";
169
+ }
170
+ }
171
+ return returnStr;
172
+ }
173
+ function trimWS(str, config, wsLeft, wsRight) {
174
+ let leftTrim;
175
+ let rightTrim;
176
+ if (Array.isArray(config.autoTrim)) {
177
+ leftTrim = config.autoTrim[1];
178
+ rightTrim = config.autoTrim[0];
179
+ } else leftTrim = rightTrim = config.autoTrim;
180
+ if (wsLeft || wsLeft === false) leftTrim = wsLeft;
181
+ if (wsRight || wsRight === false) rightTrim = wsRight;
182
+ if (!rightTrim && !leftTrim) return str;
183
+ if (leftTrim === "slurp" && rightTrim === "slurp") return str.trim();
184
+ if (leftTrim === "_" || leftTrim === "slurp") str = str.trimStart();
185
+ else if (leftTrim === "-" || leftTrim === "nl") str = str.replace(/^(?:\r\n|\n|\r)/, "");
186
+ if (rightTrim === "_" || rightTrim === "slurp") str = str.trimEnd();
187
+ else if (rightTrim === "-" || rightTrim === "nl") str = str.replace(/(?:\r\n|\n|\r)$/, "");
188
+ return str;
189
+ }
190
+ var escMap = {
191
+ "&": "&amp;",
192
+ "<": "&lt;",
193
+ ">": "&gt;",
194
+ '"': "&quot;",
195
+ "'": "&#39;"
196
+ };
197
+ function replaceChar(s) {
198
+ return escMap[s];
199
+ }
200
+ function XMLEscape(str) {
201
+ const newStr = String(str);
202
+ if (/[&<>"']/.test(newStr)) return newStr.replace(/[&<>"']/g, replaceChar);
203
+ else return newStr;
204
+ }
205
+ var defaultConfig = {
206
+ autoEscape: true,
207
+ autoFilter: false,
208
+ autoTrim: [false, "nl"],
209
+ cache: false,
210
+ cacheFilepaths: true,
211
+ debug: false,
212
+ escapeFunction: XMLEscape,
213
+ filterFunction: (val) => String(val),
214
+ outputFunctionName: "output",
215
+ functionHeader: "",
216
+ parse: {
217
+ exec: "",
218
+ interpolate: "=",
219
+ raw: "~"
220
+ },
221
+ plugins: [],
222
+ rmWhitespace: false,
223
+ tags: ["<%", "%>"],
224
+ useWith: false,
225
+ varName: "it",
226
+ defaultExtension: ".eta"
227
+ };
228
+ var templateLitReg = /`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g;
229
+ var singleQuoteReg = /'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g;
230
+ var doubleQuoteReg = /"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;
231
+ function escapeRegExp(string) {
232
+ return string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
233
+ }
234
+ function getLineNo(str, index) {
235
+ return str.slice(0, index).split("\n").length;
236
+ }
237
+ function parse(str) {
238
+ const config = this.config;
239
+ let buffer = [];
240
+ let trimLeftOfNextStr = false;
241
+ let lastIndex = 0;
242
+ const parseOptions = config.parse;
243
+ if (config.plugins) for (let i = 0; i < config.plugins.length; i++) {
244
+ const plugin = config.plugins[i];
245
+ if (plugin.processTemplate) str = plugin.processTemplate(str, config);
246
+ }
247
+ if (config.rmWhitespace) str = str.replace(/[\r\n]+/g, "\n").replace(/^\s+|\s+$/gm, "");
248
+ templateLitReg.lastIndex = 0;
249
+ singleQuoteReg.lastIndex = 0;
250
+ doubleQuoteReg.lastIndex = 0;
251
+ function pushString(strng, shouldTrimRightOfString) {
252
+ if (strng) {
253
+ strng = trimWS(strng, config, trimLeftOfNextStr, shouldTrimRightOfString);
254
+ if (strng) {
255
+ strng = strng.replace(/\\|'/g, "\\$&").replace(/\r\n|\n|\r/g, "\\n");
256
+ buffer.push(strng);
257
+ }
258
+ }
259
+ }
260
+ const prefixes = [
261
+ parseOptions.exec,
262
+ parseOptions.interpolate,
263
+ parseOptions.raw
264
+ ].reduce((accumulator, prefix) => {
265
+ if (accumulator && prefix) return accumulator + "|" + escapeRegExp(prefix);
266
+ else if (prefix) return escapeRegExp(prefix);
267
+ else return accumulator;
268
+ }, "");
269
+ const parseOpenReg = new RegExp(escapeRegExp(config.tags[0]) + "(-|_)?\\s*(" + prefixes + ")?\\s*", "g");
270
+ const parseCloseReg = new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?" + escapeRegExp(config.tags[1]) + ")", "g");
271
+ let m;
272
+ while (m = parseOpenReg.exec(str)) {
273
+ const precedingString = str.slice(lastIndex, m.index);
274
+ lastIndex = m[0].length + m.index;
275
+ const wsLeft = m[1];
276
+ const prefix = m[2] || "";
277
+ pushString(precedingString, wsLeft);
278
+ parseCloseReg.lastIndex = lastIndex;
279
+ let closeTag;
280
+ let currentObj = false;
281
+ while (closeTag = parseCloseReg.exec(str)) if (closeTag[1]) {
282
+ const content = str.slice(lastIndex, closeTag.index);
283
+ parseOpenReg.lastIndex = lastIndex = parseCloseReg.lastIndex;
284
+ trimLeftOfNextStr = closeTag[2];
285
+ currentObj = {
286
+ t: prefix === parseOptions.exec ? "e" : prefix === parseOptions.raw ? "r" : prefix === parseOptions.interpolate ? "i" : "",
287
+ val: content
288
+ };
289
+ break;
290
+ } else {
291
+ const char = closeTag[0];
292
+ if (char === "/*") {
293
+ const commentCloseInd = str.indexOf("*/", parseCloseReg.lastIndex);
294
+ if (commentCloseInd === -1) ParseErr("unclosed comment", str, closeTag.index);
295
+ parseCloseReg.lastIndex = commentCloseInd;
296
+ } else if (char === "'") {
297
+ singleQuoteReg.lastIndex = closeTag.index;
298
+ if (singleQuoteReg.exec(str)) parseCloseReg.lastIndex = singleQuoteReg.lastIndex;
299
+ else ParseErr("unclosed string", str, closeTag.index);
300
+ } else if (char === '"') {
301
+ doubleQuoteReg.lastIndex = closeTag.index;
302
+ if (doubleQuoteReg.exec(str)) parseCloseReg.lastIndex = doubleQuoteReg.lastIndex;
303
+ else ParseErr("unclosed string", str, closeTag.index);
304
+ } else if (char === "`") {
305
+ templateLitReg.lastIndex = closeTag.index;
306
+ if (templateLitReg.exec(str)) parseCloseReg.lastIndex = templateLitReg.lastIndex;
307
+ else ParseErr("unclosed string", str, closeTag.index);
308
+ }
309
+ }
310
+ if (currentObj) {
311
+ if (config.debug) currentObj.lineNo = getLineNo(str, m.index);
312
+ buffer.push(currentObj);
313
+ } else ParseErr("unclosed tag", str, m.index);
314
+ }
315
+ pushString(str.slice(lastIndex, str.length), false);
316
+ if (config.plugins) for (let i = 0; i < config.plugins.length; i++) {
317
+ const plugin = config.plugins[i];
318
+ if (plugin.processAST) buffer = plugin.processAST(buffer, config);
319
+ }
320
+ return buffer;
321
+ }
322
+ function handleCache(template, options) {
323
+ const templateStore = options?.async ? this.templatesAsync : this.templatesSync;
324
+ if (this.resolvePath && this.readFile && !template.startsWith("@")) {
325
+ const templatePath = options.filepath;
326
+ const cachedTemplate = templateStore.get(templatePath);
327
+ if (this.config.cache && cachedTemplate) return cachedTemplate;
328
+ else {
329
+ const templateString = this.readFile(templatePath);
330
+ const templateFn = this.compile(templateString, options);
331
+ if (this.config.cache) templateStore.define(templatePath, templateFn);
332
+ return templateFn;
333
+ }
334
+ } else {
335
+ const cachedTemplate = templateStore.get(template);
336
+ if (cachedTemplate) return cachedTemplate;
337
+ else throw new EtaNameResolutionError(`Failed to get template '${template}'`);
338
+ }
339
+ }
340
+ function render(template, data, meta) {
341
+ let templateFn;
342
+ const options = {
343
+ ...meta,
344
+ async: false
345
+ };
346
+ if (typeof template === "string") {
347
+ if (this.resolvePath && this.readFile && !template.startsWith("@")) options.filepath = this.resolvePath(template, options);
348
+ templateFn = handleCache.call(this, template, options);
349
+ } else templateFn = template;
350
+ return templateFn.call(this, data, options);
351
+ }
352
+ function renderAsync(template, data, meta) {
353
+ let templateFn;
354
+ const options = {
355
+ ...meta,
356
+ async: true
357
+ };
358
+ if (typeof template === "string") {
359
+ if (this.resolvePath && this.readFile && !template.startsWith("@")) options.filepath = this.resolvePath(template, options);
360
+ templateFn = handleCache.call(this, template, options);
361
+ } else templateFn = template;
362
+ const res = templateFn.call(this, data, options);
363
+ return Promise.resolve(res);
364
+ }
365
+ function renderString(template, data) {
366
+ const templateFn = this.compile(template, { async: false });
367
+ return render.call(this, templateFn, data);
368
+ }
369
+ function renderStringAsync(template, data) {
370
+ const templateFn = this.compile(template, { async: true });
371
+ return renderAsync.call(this, templateFn, data);
372
+ }
373
+ var Cacher = class {
374
+ constructor(cache) {
375
+ this.cache = cache;
376
+ }
377
+ define(key, val) {
378
+ this.cache[key] = val;
379
+ }
380
+ get(key) {
381
+ return this.cache[key];
382
+ }
383
+ remove(key) {
384
+ delete this.cache[key];
385
+ }
386
+ reset() {
387
+ this.cache = {};
388
+ }
389
+ load(cacheObj) {
390
+ this.cache = {
391
+ ...this.cache,
392
+ ...cacheObj
393
+ };
394
+ }
395
+ };
396
+ var Eta$1 = class {
397
+ constructor(customConfig) {
398
+ if (customConfig) this.config = {
399
+ ...defaultConfig,
400
+ ...customConfig
401
+ };
402
+ else this.config = { ...defaultConfig };
403
+ }
404
+ config;
405
+ RuntimeErr = RuntimeErr;
406
+ compile = compile;
407
+ compileToString = compileToString;
408
+ compileBody = compileBody;
409
+ parse = parse;
410
+ render = render;
411
+ renderAsync = renderAsync;
412
+ renderString = renderString;
413
+ renderStringAsync = renderStringAsync;
414
+ filepathCache = {};
415
+ templatesSync = new Cacher({});
416
+ templatesAsync = new Cacher({});
417
+ resolvePath = null;
418
+ readFile = null;
419
+ configure(customConfig) {
420
+ this.config = {
421
+ ...this.config,
422
+ ...customConfig
423
+ };
424
+ }
425
+ withConfig(customConfig) {
426
+ return {
427
+ ...this,
428
+ config: {
429
+ ...this.config,
430
+ ...customConfig
431
+ }
432
+ };
433
+ }
434
+ loadTemplate(name, template, options) {
435
+ if (typeof template === "string") (options?.async ? this.templatesAsync : this.templatesSync).define(name, this.compile(template, options));
436
+ else {
437
+ let templates = this.templatesSync;
438
+ if (template.constructor.name === "AsyncFunction" || options?.async) templates = this.templatesAsync;
439
+ templates.define(name, template);
440
+ }
441
+ }
442
+ };
443
+ var Eta = class extends Eta$1 {
444
+ readFile = readFile;
445
+ resolvePath = resolvePath;
446
+ };
447
+
448
+ // src/core/template/types.ts
449
+ var TEMPLATE_EXTENSION = ".tmpl";
450
+ var HELPER_FILENAME = "$helpers";
451
+ var HELPER_EXTENSIONS = [".ts", ".js", ".mjs"];
452
+ var IS_COMPILED = import.meta.url.includes("$bunfs");
453
+ async function loadJs(filepath) {
454
+ const mod = IS_COMPILED ? await loadWithBunBuild(filepath) : await loadWithImport(filepath);
455
+ return mod["default"] !== void 0 ? mod["default"] : mod;
456
+ }
457
+ async function loadWithBunBuild(filepath) {
458
+ const fileDir = dirname(filepath);
459
+ const tmpFile = join(fileDir, `.noorm-helper-${randomBytes(8).toString("hex")}.js`);
460
+ const result = await Bun.build({
461
+ entrypoints: [filepath],
462
+ outdir: fileDir,
463
+ naming: tmpFile.split("/").pop(),
464
+ target: "bun",
465
+ format: "esm"
466
+ });
467
+ if (!result.success) {
468
+ const messages = result.logs.map((l) => l.message).join("; ");
469
+ throw new Error(`Failed to bundle ${filepath}: ${messages}`);
470
+ }
471
+ const mod = await import(pathToFileURL(tmpFile).href);
472
+ unlinkSync(tmpFile);
473
+ return mod;
474
+ }
475
+ async function loadWithImport(filepath) {
476
+ const url = pathToFileURL(filepath).href;
477
+ const urlWithCacheBust = `${url}?t=${Date.now()}`;
478
+ return await import(urlWithCacheBust);
479
+ }
480
+
481
+ // src/core/template/helpers.ts
482
+ async function findHelperFiles(fromDir, projectRoot) {
483
+ const helperPaths = [];
484
+ let currentDir = path__default.resolve(fromDir);
485
+ const root = path__default.resolve(projectRoot);
486
+ while (currentDir.startsWith(root)) {
487
+ const helperPath = await findHelperInDir(currentDir);
488
+ if (helperPath) {
489
+ helperPaths.unshift(helperPath);
490
+ }
491
+ const parentDir = path__default.dirname(currentDir);
492
+ if (parentDir === currentDir) {
493
+ break;
494
+ }
495
+ currentDir = parentDir;
496
+ }
497
+ return helperPaths;
498
+ }
499
+ async function findHelperInDir(dir) {
500
+ for (const ext of HELPER_EXTENSIONS) {
501
+ const filepath = path__default.join(dir, `${HELPER_FILENAME}${ext}`);
502
+ const [stats] = await attempt(() => stat(filepath));
503
+ if (stats?.isFile()) {
504
+ return filepath;
505
+ }
506
+ }
507
+ return null;
508
+ }
509
+ async function loadHelpers(fromDir, projectRoot) {
510
+ const helperPaths = await findHelperFiles(fromDir, projectRoot);
511
+ const merged = {};
512
+ const errors = [];
513
+ for (const filepath of helperPaths) {
514
+ const [mod, err] = await attempt(() => loadJs(filepath));
515
+ if (err) {
516
+ errors.push({ filepath, error: err });
517
+ observer.emit("error", {
518
+ source: "template",
519
+ error: err,
520
+ context: { filepath, operation: "load-helpers" }
521
+ });
522
+ continue;
523
+ }
524
+ if (mod && typeof mod === "object") {
525
+ const exports$1 = mod;
526
+ const exportCount = Object.keys(exports$1).length;
527
+ Object.assign(merged, exports$1);
528
+ observer.emit("template:helpers", {
529
+ filepath,
530
+ count: exportCount
531
+ });
532
+ }
533
+ }
534
+ return { helpers: merged, errors };
535
+ }
536
+ async function loadSql(filepath) {
537
+ return readFile$1(filepath, "utf-8");
538
+ }
539
+
540
+ // src/core/dt/constants.ts
541
+ var FORMAT_VERSION = 1;
542
+ var ENCODED_TYPES = {
543
+ json: true,
544
+ binary: true,
545
+ vector: true,
546
+ array: true,
547
+ text: true,
548
+ custom: true
549
+ };
550
+ var DT_EXTENSIONS = {
551
+ /** Raw .dt file (uncompressed JSON5 lines). */
552
+ RAW: ".dt",
553
+ /** Gzip-compressed .dt file. */
554
+ COMPRESSED: ".dtz",
555
+ /** Gzip-compressed and AES-256-GCM encrypted .dt file. */
556
+ ENCRYPTED: ".dtzx"
557
+ };
558
+ var ALGORITHM = "aes-256-gcm";
559
+ var IV_LENGTH = 16;
560
+ var SALT_LENGTH = 32;
561
+ var AUTH_TAG_LENGTH = 16;
562
+ var KEY_LENGTH = 32;
563
+ var PBKDF2_ITERATIONS = 1e5;
564
+ var PBKDF2_DIGEST = "sha256";
565
+ function encryptWithPassphrase(data, passphrase) {
566
+ const salt = randomBytes(SALT_LENGTH);
567
+ const iv = randomBytes(IV_LENGTH);
568
+ const key = pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);
569
+ const cipher = createCipheriv(ALGORITHM, key, iv, {
570
+ authTagLength: AUTH_TAG_LENGTH
571
+ });
572
+ const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
573
+ const authTag = cipher.getAuthTag();
574
+ return {
575
+ salt: salt.toString("base64"),
576
+ iv: iv.toString("base64"),
577
+ authTag: authTag.toString("base64"),
578
+ ciphertext: ciphertext.toString("base64")
579
+ };
580
+ }
581
+ function decryptWithPassphrase(payload, passphrase) {
582
+ const salt = Buffer.from(payload.salt, "base64");
583
+ const iv = Buffer.from(payload.iv, "base64");
584
+ const authTag = Buffer.from(payload.authTag, "base64");
585
+ const ciphertext = Buffer.from(payload.ciphertext, "base64");
586
+ const key = pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);
587
+ const decipher = createDecipheriv(ALGORITHM, key, iv, {
588
+ authTagLength: AUTH_TAG_LENGTH
589
+ });
590
+ decipher.setAuthTag(authTag);
591
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
592
+ return decrypted;
593
+ }
594
+
595
+ // src/core/dt/reader.ts
596
+ var DtReader = class {
597
+ #filepath;
598
+ #passphrase;
599
+ #extension;
600
+ #schema = null;
601
+ #lineReader = null;
602
+ #inputStream = null;
603
+ /**
604
+ * Create a new DtReader.
605
+ *
606
+ * @param options - File path and optional passphrase for .dtzx
607
+ */
608
+ constructor(options) {
609
+ this.#filepath = options.filepath;
610
+ this.#passphrase = options.passphrase;
611
+ this.#extension = path__default.extname(options.filepath).toLowerCase();
612
+ }
613
+ /** The parsed schema from line 1. Available after open(). */
614
+ get schema() {
615
+ return this.#schema;
616
+ }
617
+ /**
618
+ * Open the file and parse the schema header.
619
+ *
620
+ * Must be called before iterating rows.
621
+ */
622
+ async open() {
623
+ const readable = this.#createReadableStream();
624
+ this.#inputStream = readable;
625
+ const rl = createInterface({ input: readable, crlfDelay: Infinity });
626
+ const lines = rl[Symbol.asyncIterator]();
627
+ const firstLine = await lines.next();
628
+ if (firstLine.done || !firstLine.value) {
629
+ throw new Error("Empty .dt file \u2014 no schema line");
630
+ }
631
+ this.#schema = dist_default.parse(firstLine.value);
632
+ if (this.#schema.v !== 1) {
633
+ throw new Error(`Unsupported .dt format version: ${this.#schema.v}`);
634
+ }
635
+ this.#lineReader = this.#createRowIterator(lines);
636
+ }
637
+ /**
638
+ * Async generator yielding parsed row value arrays.
639
+ *
640
+ * Each yield is a `DtValue[]` in column order matching the schema.
641
+ *
642
+ * @example
643
+ * ```typescript
644
+ * for await (const values of reader.rows()) {
645
+ * console.log(values); // [1, "alice@example.com", true, "2024-01-15T10:30:00Z"]
646
+ * }
647
+ * ```
648
+ */
649
+ async *rows() {
650
+ if (!this.#lineReader) {
651
+ throw new Error("Reader not opened \u2014 call open() first");
652
+ }
653
+ yield* this.#lineReader;
654
+ }
655
+ /**
656
+ * Close the reader and release resources.
657
+ */
658
+ close() {
659
+ if (this.#inputStream) {
660
+ this.#inputStream.destroy();
661
+ this.#inputStream = null;
662
+ }
663
+ }
664
+ /**
665
+ * Create the readable stream based on file extension.
666
+ */
667
+ #createReadableStream() {
668
+ if (this.#extension === DT_EXTENSIONS.ENCRYPTED) {
669
+ if (!this.#passphrase) {
670
+ throw new Error("Passphrase required for .dtzx files");
671
+ }
672
+ const encrypted = readFileSync(this.#filepath, "utf8");
673
+ const payload = JSON.parse(encrypted);
674
+ const compressed = decryptWithPassphrase(payload, this.#passphrase);
675
+ const raw = gunzipSync(compressed);
676
+ const stream = new PassThrough();
677
+ stream.end(raw);
678
+ return stream;
679
+ }
680
+ if (this.#extension === DT_EXTENSIONS.COMPRESSED) {
681
+ const fileStream = createReadStream(this.#filepath);
682
+ const gunzip = createGunzip();
683
+ fileStream.pipe(gunzip);
684
+ return gunzip;
685
+ }
686
+ return createReadStream(this.#filepath, { encoding: "utf8" });
687
+ }
688
+ /**
689
+ * Create async generator from remaining readline lines.
690
+ */
691
+ async *#createRowIterator(lines) {
692
+ for await (const line of { [Symbol.asyncIterator]: () => lines }) {
693
+ const trimmed = line.trim();
694
+ if (trimmed.length === 0) continue;
695
+ yield dist_default.parse(trimmed);
696
+ }
697
+ }
698
+ };
699
+
700
+ // src/core/template/loaders/dt.ts
701
+ async function loadDt(filepath) {
702
+ const reader = new DtReader({ filepath });
703
+ await reader.open();
704
+ const schema = reader.schema;
705
+ if (!schema) {
706
+ throw new Error(`Failed to read .dt schema from: ${filepath}`);
707
+ }
708
+ const columnNames = schema.columns.map((c) => c.name);
709
+ const rows = [];
710
+ for await (const values of reader.rows()) {
711
+ const row = {};
712
+ for (let i = 0; i < columnNames.length; i++) {
713
+ row[columnNames[i]] = values[i] ?? null;
714
+ }
715
+ rows.push(row);
716
+ }
717
+ reader.close();
718
+ return rows;
719
+ }
720
+
721
+ // src/core/template/loaders/index.ts
722
+ async function lazyLoadJson5(filepath) {
723
+ const { loadJson5: loadJson52 } = await import('./json5-LNT3RGJ7.js');
724
+ return loadJson52(filepath);
725
+ }
726
+ async function lazyLoadYaml(filepath) {
727
+ const { loadYaml: loadYaml2 } = await import('./yaml-XI7RQ2D5.js');
728
+ return loadYaml2(filepath);
729
+ }
730
+ async function lazyLoadCsv(filepath) {
731
+ const { loadCsv: loadCsv2 } = await import('./csv-T5P3IN4K.js');
732
+ return loadCsv2(filepath);
733
+ }
734
+ var loaders = {
735
+ ".json": lazyLoadJson5,
736
+ ".json5": lazyLoadJson5,
737
+ ".yaml": lazyLoadYaml,
738
+ ".yml": lazyLoadYaml,
739
+ ".csv": lazyLoadCsv,
740
+ ".js": loadJs,
741
+ ".mjs": loadJs,
742
+ ".ts": loadJs,
743
+ ".sql": loadSql,
744
+ ".dt": loadDt,
745
+ ".dtz": loadDt
746
+ // NO .dtzx — can't provide passphrase in template context
747
+ };
748
+ function hasLoader(ext) {
749
+ return ext in loaders;
750
+ }
751
+ function getLoader(ext) {
752
+ return loaders[ext];
753
+ }
754
+ async function loadDataFile(filepath) {
755
+ const ext = path__default.extname(filepath).toLowerCase();
756
+ const loader = getLoader(ext);
757
+ if (!loader) {
758
+ throw new Error(`No loader registered for extension: ${ext}`);
759
+ }
760
+ return loader(filepath);
761
+ }
762
+ function camelCase(str) {
763
+ const words = str.replace(/([a-z])([A-Z])/g, "$1 $2").split(/[-_\s]+/).filter(Boolean);
764
+ if (words.length === 0) return "";
765
+ return words.map((w, i) => i === 0 ? w.toLowerCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join("");
766
+ }
767
+ function toContextKey(filename) {
768
+ const ext = path__default.extname(filename);
769
+ const base = path__default.basename(filename, ext);
770
+ return camelCase(base);
771
+ }
772
+ function sqlEscape(value) {
773
+ return value.replace(/'/g, "''");
774
+ }
775
+ function sqlQuote(value) {
776
+ if (value === null) {
777
+ return "NULL";
778
+ }
779
+ return `'${sqlEscape(String(value))}'`;
780
+ }
781
+ function generateUuid() {
782
+ return crypto.randomUUID();
783
+ }
784
+ function isoNow() {
785
+ return (/* @__PURE__ */ new Date()).toISOString();
786
+ }
787
+
788
+ // src/core/template/context.ts
789
+ async function buildContext(templatePath, options = {}) {
790
+ const templateDir = path__default.dirname(templatePath);
791
+ const projectRoot = options.projectRoot ?? process.cwd();
792
+ const { helpers } = await loadHelpers(templateDir, projectRoot);
793
+ const dataFiles = await loadDataFilesInDir(templateDir);
794
+ const hasLocalConfig = "config" in dataFiles;
795
+ const ctx = {
796
+ // Inherited helpers (can be overridden by data files with same name)
797
+ ...helpers,
798
+ // Auto-loaded data files
799
+ ...dataFiles,
800
+ // Config (only if no local config.* file)
801
+ ...hasLocalConfig ? {} : { config: options.config },
802
+ // Secrets
803
+ secrets: options.secrets ?? {},
804
+ globalSecrets: options.globalSecrets ?? {},
805
+ // Environment
806
+ env: process.env,
807
+ // Built-in helpers
808
+ include: createIncludeHelper(templateDir, projectRoot, options),
809
+ escape: sqlEscape,
810
+ quote: sqlQuote,
811
+ json: (value) => JSON.stringify(value),
812
+ now: isoNow,
813
+ uuid: generateUuid
814
+ };
815
+ return ctx;
816
+ }
817
+ async function loadDataFilesInDir(dir) {
818
+ const data = {};
819
+ const [entries, readErr] = await attempt(() => readdir(dir, { withFileTypes: true }));
820
+ if (readErr || !entries) {
821
+ observer.emit("error", {
822
+ source: "template",
823
+ error: readErr ?? new Error("Failed to read directory"),
824
+ context: { dir, operation: "scan-data-files" }
825
+ });
826
+ return data;
827
+ }
828
+ for (const entry of entries) {
829
+ if (!entry.isFile()) {
830
+ continue;
831
+ }
832
+ if (entry.name.startsWith(".") || entry.name.startsWith(HELPER_FILENAME)) {
833
+ continue;
834
+ }
835
+ if (entry.name.endsWith(".tmpl")) {
836
+ continue;
837
+ }
838
+ const ext = path__default.extname(entry.name).toLowerCase();
839
+ if (!hasLoader(ext)) {
840
+ continue;
841
+ }
842
+ if (ext === ".sql") {
843
+ continue;
844
+ }
845
+ const filepath = path__default.join(dir, entry.name);
846
+ const key = toContextKey(entry.name);
847
+ const [loaded, loadErr] = await attempt(() => loadDataFile(filepath));
848
+ if (loadErr) {
849
+ observer.emit("error", {
850
+ source: "template",
851
+ error: loadErr,
852
+ context: { filepath, operation: "load-data-file" }
853
+ });
854
+ continue;
855
+ }
856
+ data[key] = loaded;
857
+ observer.emit("template:load", {
858
+ filepath,
859
+ format: ext
860
+ });
861
+ }
862
+ return data;
863
+ }
864
+ function createIncludeHelper(templateDir, projectRoot, options) {
865
+ return async (includePath) => {
866
+ const resolved = path__default.resolve(templateDir, includePath);
867
+ if (!resolved.startsWith(projectRoot)) {
868
+ throw new Error(`Include path escapes project root: ${includePath}`);
869
+ }
870
+ if (resolved.endsWith(".tmpl")) {
871
+ const { processFile: processFile2 } = await import('./engine-27DNMF4T.js');
872
+ const result = await processFile2(resolved, options);
873
+ return result.sql;
874
+ }
875
+ const [content, err] = await attempt(() => loadDataFile(resolved));
876
+ if (err) {
877
+ throw new Error(`Failed to include '${includePath}': ${err.message}`);
878
+ }
879
+ if (typeof content === "string") {
880
+ return content;
881
+ }
882
+ return JSON.stringify(content);
883
+ };
884
+ }
885
+
886
+ // src/core/template/engine.ts
887
+ var DIRECTIVE_LINE_RE = /^[ \t]*-- (\{%.*?%\})[ \t]*$(?:\r?\n)?/gm;
888
+ var eta = new Eta({
889
+ // Custom tags for code blocks
890
+ tags: ["{%", "%}"],
891
+ // Variable name for context ($ instead of it)
892
+ varName: "$",
893
+ // Don't auto-escape (SQL doesn't need HTML escaping)
894
+ autoEscape: false,
895
+ // Disabled — directive-line stripping handles whitespace instead
896
+ autoTrim: [false, false],
897
+ // Allow async functions in templates
898
+ useWith: false,
899
+ // Don't cache templates (we handle caching at a higher level)
900
+ cache: false
901
+ });
902
+ function isTemplate(filepath) {
903
+ return filepath.endsWith(TEMPLATE_EXTENSION);
904
+ }
905
+ async function renderTemplate(template, context) {
906
+ const prepared = template.replace(DIRECTIVE_LINE_RE, "$1");
907
+ const result = await eta.renderStringAsync(prepared, context);
908
+ return result.replace(/^\n+|\n+$/g, "");
909
+ }
910
+ async function processFile(filepath, options = {}) {
911
+ const content = await readFile$1(filepath, "utf-8");
912
+ if (!isTemplate(filepath)) {
913
+ return {
914
+ sql: content,
915
+ isTemplate: false
916
+ };
917
+ }
918
+ const start = performance.now();
919
+ const context = await buildContext(filepath, options);
920
+ const sql = await renderTemplate(content, context);
921
+ const durationMs = performance.now() - start;
922
+ observer.emit("template:render", {
923
+ filepath,
924
+ durationMs
925
+ });
926
+ return {
927
+ sql,
928
+ isTemplate: true,
929
+ durationMs
930
+ };
931
+ }
932
+ async function processFiles(filepaths, options = {}) {
933
+ const results = [];
934
+ for (const filepath of filepaths) {
935
+ const result = await processFile(filepath, options);
936
+ results.push(result);
937
+ }
938
+ return results;
939
+ }
940
+
941
+ export { DT_EXTENSIONS, DtReader, ENCODED_TYPES, FORMAT_VERSION, encryptWithPassphrase, eta, isTemplate, processFile, processFiles, renderTemplate };
942
+ //# sourceMappingURL=chunk-3UDETNWW.js.map
943
+ //# sourceMappingURL=chunk-3UDETNWW.js.map