ecto 4.8.3 → 4.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ecto.mjs ADDED
@@ -0,0 +1,863 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { Cacheable, CacheableMemory } from "cacheable";
4
+ import { Hookified } from "hookified";
5
+ import { Writr } from "writr";
6
+ import ejs from "ejs";
7
+ import { fumanchu } from "@jaredwray/fumanchu";
8
+ import { decode } from "ent";
9
+ import { Liquid as Liquid$1 } from "liquidjs";
10
+ import * as nunjucks from "nunjucks";
11
+ import * as pug from "pug";
12
+ //#region src/engine-map.ts
13
+ var EngineMap = class {
14
+ _mappings = /* @__PURE__ */ new Map();
15
+ set(name, extensions) {
16
+ const engineName = name.trim().toLowerCase();
17
+ const engineExtensions = [];
18
+ if (extensions.length > 0 && name !== "") {
19
+ for (let extension of extensions) {
20
+ extension = extension.trim().toLowerCase();
21
+ if (!engineExtensions.includes(extension)) engineExtensions.push(extension);
22
+ }
23
+ this._mappings.set(engineName, engineExtensions);
24
+ }
25
+ }
26
+ delete(name) {
27
+ this._mappings.delete(name.trim().toLowerCase());
28
+ }
29
+ deleteExtension(name, extension) {
30
+ const engineName = name.trim().toLowerCase();
31
+ const extensions = this._mappings.get(engineName);
32
+ if (extensions) {
33
+ const engineExtensions = [];
34
+ for (const extension_ of extensions) if (extension_ !== extension.trim().toLowerCase()) engineExtensions.push(extension_);
35
+ this._mappings.set(engineName, engineExtensions);
36
+ }
37
+ }
38
+ get(name) {
39
+ return this._mappings.get(name.trim().toLowerCase());
40
+ }
41
+ getName(extension) {
42
+ let engineName;
43
+ for (const [name, extensions] of this._mappings) if (extensions.includes(extension.trim().toLowerCase())) engineName = name;
44
+ return engineName;
45
+ }
46
+ };
47
+ //#endregion
48
+ //#region src/base-engine.ts
49
+ var BaseEngine = class {
50
+ names = [];
51
+ opts = void 0;
52
+ engine;
53
+ rootTemplatePath = void 0;
54
+ _extensions = [];
55
+ getExtensions() {
56
+ return this._extensions;
57
+ }
58
+ setExtensions(extensions) {
59
+ this._extensions = [];
60
+ for (const extension of extensions) {
61
+ const newExtension = extension.trim().toLowerCase();
62
+ if (!this._extensions.includes(newExtension)) this._extensions.push(newExtension);
63
+ }
64
+ }
65
+ deleteExtension(name) {
66
+ for (const [index, extension] of this._extensions.entries()) if (name.toLowerCase().trim() === extension) this._extensions.splice(index, 1);
67
+ }
68
+ };
69
+ //#endregion
70
+ //#region src/engines/ejs.ts
71
+ var EJS = class extends BaseEngine {
72
+ constructor(options) {
73
+ super();
74
+ this.names = ["ejs"];
75
+ if (options) this.opts = options;
76
+ this.setExtensions(["ejs"]);
77
+ }
78
+ async render(source, data) {
79
+ this.engine ??= ejs;
80
+ this.opts ??= {};
81
+ if (this.rootTemplatePath) this.opts.root = this.rootTemplatePath;
82
+ return ejs.render(source, data, this.opts);
83
+ }
84
+ renderSync(source, data) {
85
+ this.engine ??= ejs;
86
+ this.opts ??= {};
87
+ if (this.rootTemplatePath) this.opts.root = this.rootTemplatePath;
88
+ return ejs.render(source, data, this.opts);
89
+ }
90
+ };
91
+ //#endregion
92
+ //#region src/engines/handlebars.ts
93
+ var Handlebars = class extends BaseEngine {
94
+ partialsPath = [
95
+ "partials",
96
+ "includes",
97
+ "templates"
98
+ ];
99
+ constructor(options) {
100
+ super();
101
+ this.names = ["handlebars", "mustache"];
102
+ this.opts = options;
103
+ this.engine = fumanchu();
104
+ this.setExtensions([
105
+ "hbs",
106
+ "hjs",
107
+ "handlebars",
108
+ "mustache"
109
+ ]);
110
+ }
111
+ async render(source, data) {
112
+ if (this.rootTemplatePath) this.initPartials();
113
+ let result = this.engine.compile(source, this.opts)(data, this.opts);
114
+ result = decode(result);
115
+ return result;
116
+ }
117
+ renderSync(source, data) {
118
+ if (this.rootTemplatePath) this.initPartials();
119
+ let result = this.engine.compile(source, this.opts)(data, this.opts);
120
+ result = decode(result);
121
+ return result;
122
+ }
123
+ initPartials() {
124
+ for (const path of this.partialsPath) {
125
+ const fullPath = `${this.rootTemplatePath}/${path}`;
126
+ this.registerPartials(fullPath);
127
+ }
128
+ }
129
+ registerPartials(partialsPath) {
130
+ let result = false;
131
+ if (fs.existsSync(partialsPath)) {
132
+ const partials = fs.readdirSync(partialsPath, {
133
+ recursive: true,
134
+ encoding: "utf8"
135
+ });
136
+ for (const p of partials) if (fs.statSync(`${partialsPath}/${p}`).isDirectory()) {
137
+ const directoryPartials = fs.readdirSync(`${partialsPath}/${p}`, {
138
+ recursive: true,
139
+ encoding: "utf8"
140
+ });
141
+ for (const dp of directoryPartials) {
142
+ const source = fs.readFileSync(`${partialsPath}/${p}/${dp}`).toString();
143
+ const name = `${p}/${dp.split(".")[0]}`;
144
+ this.engine.registerPartial(name, this.engine.compile(source));
145
+ }
146
+ } else {
147
+ const source = fs.readFileSync(`${partialsPath}/${p}`, "utf8");
148
+ const name = p.split(".")[0];
149
+ this.engine.registerPartial(name, this.engine.compile(source));
150
+ }
151
+ result = true;
152
+ }
153
+ return result;
154
+ }
155
+ };
156
+ //#endregion
157
+ //#region src/engines/liquid.ts
158
+ var Liquid = class extends BaseEngine {
159
+ constructor(options) {
160
+ super();
161
+ this.names = ["liquid"];
162
+ if (options) this.opts = options;
163
+ this.setExtensions(["liquid"]);
164
+ }
165
+ async render(source, data) {
166
+ if (this.rootTemplatePath) {
167
+ this.opts ??= {};
168
+ this.opts.root = this.rootTemplatePath;
169
+ }
170
+ if (!this.engine) this.engine = new Liquid$1(this.opts);
171
+ return this.engine.parseAndRender(source, data);
172
+ }
173
+ renderSync(source, data) {
174
+ if (this.rootTemplatePath) {
175
+ this.opts ??= {};
176
+ this.opts.root = this.rootTemplatePath;
177
+ }
178
+ if (!this.engine) this.engine = new Liquid$1(this.opts);
179
+ return this.engine.parseAndRenderSync(source, data);
180
+ }
181
+ };
182
+ //#endregion
183
+ //#region src/engines/markdown.ts
184
+ var Markdown = class extends BaseEngine {
185
+ constructor(options) {
186
+ super();
187
+ this.names = ["markdown"];
188
+ if (options) this.opts = options;
189
+ this.engine = new Writr(options);
190
+ this.setExtensions(["md", "markdown"]);
191
+ }
192
+ async render(source, data) {
193
+ this.engine.content = source;
194
+ return this.engine.render(data);
195
+ }
196
+ renderSync(source, data) {
197
+ this.engine.content = source;
198
+ return this.engine.renderSync(data);
199
+ }
200
+ };
201
+ //#endregion
202
+ //#region src/engines/nunjucks.ts
203
+ var Nunjucks = class extends BaseEngine {
204
+ constructor(options) {
205
+ super();
206
+ this.names = ["nunjucks"];
207
+ this.engine = nunjucks;
208
+ this.opts = { autoescape: true };
209
+ if (options) this.opts = options;
210
+ this.setExtensions(["njk"]);
211
+ }
212
+ async render(source, data) {
213
+ if (this.rootTemplatePath) nunjucks.configure(this.rootTemplatePath, this.opts);
214
+ else nunjucks.configure(this.opts);
215
+ data ??= {};
216
+ return nunjucks.renderString(source, data);
217
+ }
218
+ renderSync(source, data) {
219
+ if (this.rootTemplatePath) nunjucks.configure(this.rootTemplatePath, this.opts);
220
+ else nunjucks.configure(this.opts);
221
+ data ??= {};
222
+ return nunjucks.renderString(source, data);
223
+ }
224
+ };
225
+ //#endregion
226
+ //#region src/engines/pug.ts
227
+ var Pug = class extends BaseEngine {
228
+ constructor(options) {
229
+ super();
230
+ this.names = ["pug"];
231
+ this.engine = pug;
232
+ if (options) this.opts = options;
233
+ this.setExtensions(["pug", "jade"]);
234
+ }
235
+ async render(source, data) {
236
+ if (this.rootTemplatePath) {
237
+ this.opts ??= {};
238
+ this.opts.basedir = this.rootTemplatePath;
239
+ }
240
+ return pug.compile(source, this.opts)(data);
241
+ }
242
+ renderSync(source, data) {
243
+ if (this.rootTemplatePath) {
244
+ this.opts ??= {};
245
+ this.opts.basedir = this.rootTemplatePath;
246
+ }
247
+ return pug.compile(source, this.opts)(data);
248
+ }
249
+ };
250
+ //#endregion
251
+ //#region src/ecto.ts
252
+ let EctoEvents = /* @__PURE__ */ function(EctoEvents) {
253
+ EctoEvents["cacheHit"] = "cacheHit";
254
+ EctoEvents["cacheMiss"] = "cacheMiss";
255
+ EctoEvents["warn"] = "warn";
256
+ EctoEvents["error"] = "error";
257
+ EctoEvents["beforeRender"] = "beforeRender";
258
+ EctoEvents["afterRender"] = "afterRender";
259
+ EctoEvents["beforeRenderSync"] = "beforeRenderSync";
260
+ EctoEvents["afterRenderSync"] = "afterRenderSync";
261
+ return EctoEvents;
262
+ }({});
263
+ var Ecto = class extends Hookified {
264
+ _mapping = new EngineMap();
265
+ _engines = [];
266
+ _cache;
267
+ _cacheSync;
268
+ _defaultEngine = "ejs";
269
+ _ejs;
270
+ _markdown;
271
+ _pug;
272
+ _nunjucks;
273
+ _handlebars;
274
+ _liquid;
275
+ /**
276
+ * Ecto constructor
277
+ * @param {EctoOptions} [options] - The options for the ecto engine
278
+ */
279
+ constructor(options) {
280
+ super();
281
+ this._ejs = new EJS(options?.engineOptions?.ejs);
282
+ this._markdown = new Markdown(options?.engineOptions?.markdown);
283
+ this._pug = new Pug(options?.engineOptions?.pug);
284
+ this._nunjucks = new Nunjucks(options?.engineOptions?.nunjucks);
285
+ this._handlebars = new Handlebars(options?.engineOptions?.handlebars);
286
+ this._liquid = new Liquid(options?.engineOptions?.liquid);
287
+ this._engines.push(this._ejs, this._markdown, this._pug, this._nunjucks, this._handlebars, this._liquid);
288
+ this.registerEngineMappings();
289
+ if (options?.cache === true) this._cache = new Cacheable();
290
+ else if (options?.cache instanceof Cacheable) this._cache = options.cache;
291
+ if (options?.cacheSync === true) this._cacheSync = new CacheableMemory();
292
+ else if (options?.cacheSync instanceof CacheableMemory) this._cacheSync = options.cacheSync;
293
+ if (options?.defaultEngine && this.isValidEngine(options.defaultEngine)) this._defaultEngine = options.defaultEngine;
294
+ }
295
+ /**
296
+ * Get the default engine
297
+ * @returns {string} - the engine name such as 'ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid'
298
+ */
299
+ get defaultEngine() {
300
+ return this._defaultEngine;
301
+ }
302
+ /**
303
+ * Set the default engine
304
+ * @param {string} value the engine name such as 'ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid'
305
+ */
306
+ set defaultEngine(value) {
307
+ value = value.toLowerCase().trim();
308
+ if (this.isValidEngine(value)) this._defaultEngine = value;
309
+ else this.emit(EctoEvents.warn, `Invalid engine name: ${value}. Defaulting to ${this._defaultEngine}.`);
310
+ }
311
+ /**
312
+ * Get the cacheable instance
313
+ * @returns {Cacheable | undefined} - The cacheable instance or undefined if caching is disabled
314
+ */
315
+ get cache() {
316
+ return this._cache;
317
+ }
318
+ /**
319
+ * Set the cacheable instance
320
+ * @param {Cacheable | undefined} value - The cacheable instance to set. If set to undefined, caching will be disabled.
321
+ */
322
+ set cache(value) {
323
+ this._cache = value;
324
+ }
325
+ /**
326
+ * Get the cacheable memory instance
327
+ * @returns {CacheableMemory | undefined} - The cacheable memory instance or undefined if caching is disabled
328
+ */
329
+ get cacheSync() {
330
+ return this._cacheSync;
331
+ }
332
+ /**
333
+ * Set the cacheable memory instance
334
+ * @param {CacheableMemory | undefined} value - The cacheable memory instance to set. If set to undefined, caching will be disabled.
335
+ */
336
+ set cacheSync(value) {
337
+ this._cacheSync = value;
338
+ }
339
+ /**
340
+ * Get the Engine Mappings. This is used to map file extensions to engines
341
+ * @returns {EngineMap}
342
+ */
343
+ get mappings() {
344
+ return this._mapping;
345
+ }
346
+ /**
347
+ * Get the EJS Engine
348
+ * @returns {EJS}
349
+ */
350
+ get ejs() {
351
+ return this._ejs;
352
+ }
353
+ /**
354
+ * Get the Markdown Engine
355
+ * @returns {Markdown}
356
+ */
357
+ get markdown() {
358
+ return this._markdown;
359
+ }
360
+ /**
361
+ * Get the Pug Engine
362
+ * @returns {Pug}
363
+ */
364
+ get pug() {
365
+ return this._pug;
366
+ }
367
+ /**
368
+ * Get the Nunjucks Engine
369
+ * @returns {Nunjucks}
370
+ */
371
+ get nunjucks() {
372
+ return this._nunjucks;
373
+ }
374
+ /**
375
+ * Get the Handlebars Engine
376
+ * @returns {Handlebars}
377
+ */
378
+ get handlebars() {
379
+ return this._handlebars;
380
+ }
381
+ /**
382
+ * Get the Liquid Engine
383
+ * @returns {Liquid}
384
+ */
385
+ get liquid() {
386
+ return this._liquid;
387
+ }
388
+ /**
389
+ * Asynchronously render a template source with data using the specified engine
390
+ * @param {string} source - The template source string to render
391
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
392
+ * @param {string} [engineName] - Name of the engine to use (e.g., 'ejs', 'pug'). Defaults to defaultEngine
393
+ * @param {string} [rootTemplatePath] - Root directory path for template includes/partials resolution
394
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
395
+ * @returns {Promise<string>} The rendered template output as a string
396
+ * @example
397
+ * const result = await ecto.render('<%= name %>', { name: 'World' }, 'ejs');
398
+ */
399
+ async render(source, data, engineName, rootTemplatePath, filePathOutput) {
400
+ try {
401
+ let renderEngineName = this._defaultEngine;
402
+ if (this.isValidEngine(engineName) && engineName !== void 0) renderEngineName = engineName;
403
+ const cacheKey = `${renderEngineName}-${source}-${JSON.stringify(data)}`;
404
+ if (this._cache) {
405
+ const cachedResult = await this._cache.get(cacheKey);
406
+ if (cachedResult) {
407
+ this.emit(EctoEvents.cacheHit, `Cache hit for key: ${cacheKey}`);
408
+ const context = {
409
+ source,
410
+ data,
411
+ engineName: renderEngineName,
412
+ rootTemplatePath,
413
+ filePathOutput,
414
+ cached: true
415
+ };
416
+ await this.hook(EctoEvents.beforeRender, context);
417
+ const renderResult = {
418
+ result: cachedResult,
419
+ context
420
+ };
421
+ await this.hook(EctoEvents.afterRender, renderResult);
422
+ await this.writeFile(filePathOutput, renderResult.result);
423
+ return renderResult.result;
424
+ }
425
+ this.emit(EctoEvents.cacheMiss, `Cache miss for key: ${cacheKey}`);
426
+ }
427
+ const context = {
428
+ source,
429
+ data,
430
+ engineName: renderEngineName,
431
+ rootTemplatePath,
432
+ filePathOutput,
433
+ cached: false
434
+ };
435
+ await this.hook(EctoEvents.beforeRender, context);
436
+ const renderEngine = this.getRenderEngine(renderEngineName);
437
+ renderEngine.rootTemplatePath = context.rootTemplatePath;
438
+ let result = await renderEngine.render(context.source, context.data);
439
+ const renderResult = {
440
+ result,
441
+ context
442
+ };
443
+ await this.hook(EctoEvents.afterRender, renderResult);
444
+ result = renderResult.result;
445
+ if (this._cache) await this._cache.set(cacheKey, result);
446
+ await this.writeFile(filePathOutput, result);
447
+ return result;
448
+ } catch (error) {
449
+ /* v8 ignore next -- @preserve */
450
+ this.emit(EctoEvents.error, error);
451
+ /* v8 ignore next -- @preserve */
452
+ return "";
453
+ }
454
+ }
455
+ /**
456
+ * Synchronously render a template source with data using the specified engine
457
+ * @param {string} source - The template source string to render
458
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
459
+ * @param {string} [engineName] - Name of the engine to use (e.g., 'ejs', 'pug'). Defaults to defaultEngine
460
+ * @param {string} [rootTemplatePath] - Root directory path for template includes/partials resolution
461
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
462
+ * @returns {string} The rendered template output as a string
463
+ * @example
464
+ * const result = ecto.renderSync('<%= name %>', { name: 'World' }, 'ejs');
465
+ */
466
+ renderSync(source, data, engineName, rootTemplatePath, filePathOutput) {
467
+ try {
468
+ let renderEngineName = this._defaultEngine;
469
+ if (this.isValidEngine(engineName) && engineName !== void 0) renderEngineName = engineName;
470
+ const cacheKey = `${renderEngineName}-${source}-${JSON.stringify(data)}`;
471
+ if (this._cacheSync) {
472
+ const cachedResult = this._cacheSync.get(cacheKey);
473
+ if (cachedResult) {
474
+ this.emit(EctoEvents.cacheHit, `Cache hit for key: ${cacheKey}`);
475
+ const context = {
476
+ source,
477
+ data,
478
+ engineName: renderEngineName,
479
+ rootTemplatePath,
480
+ filePathOutput,
481
+ cached: true
482
+ };
483
+ this.hookSync(EctoEvents.beforeRenderSync, context);
484
+ const renderResult = {
485
+ result: cachedResult,
486
+ context
487
+ };
488
+ this.hookSync(EctoEvents.afterRenderSync, renderResult);
489
+ this.writeFileSync(filePathOutput, renderResult.result);
490
+ return renderResult.result;
491
+ }
492
+ this.emit(EctoEvents.cacheMiss, `Cache miss for key: ${cacheKey}`);
493
+ }
494
+ const context = {
495
+ source,
496
+ data,
497
+ engineName: renderEngineName,
498
+ rootTemplatePath,
499
+ filePathOutput,
500
+ cached: false
501
+ };
502
+ this.hookSync(EctoEvents.beforeRenderSync, context);
503
+ const renderEngine = this.getRenderEngine(renderEngineName);
504
+ renderEngine.rootTemplatePath = context.rootTemplatePath;
505
+ let result = renderEngine.renderSync(context.source, context.data);
506
+ const renderResult = {
507
+ result,
508
+ context
509
+ };
510
+ this.hookSync(EctoEvents.afterRenderSync, renderResult);
511
+ result = renderResult.result;
512
+ if (this._cacheSync) this._cacheSync.set(cacheKey, result);
513
+ this.writeFileSync(filePathOutput, result);
514
+ return result;
515
+ } catch (error) {
516
+ this.emit(EctoEvents.error, error);
517
+ return "";
518
+ }
519
+ }
520
+ /**
521
+ * Asynchronously render a template from a file path
522
+ * @param {string} filePath - Path to the template file to render
523
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
524
+ * @param {string} [rootTemplatePath] - Root directory for template includes. Defaults to file's directory
525
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
526
+ * @param {string} [engineName] - Engine to use. If not specified, determined from file extension
527
+ * @returns {Promise<string>} The rendered template output as a string
528
+ * @example
529
+ * const result = await ecto.renderFromFile('./templates/index.ejs', { title: 'Home' });
530
+ */
531
+ async renderFromFile(filePath, data, rootTemplatePath, filePathOutput, engineName) {
532
+ let result = "";
533
+ engineName ??= this.getEngineByFilePath(filePath);
534
+ const templateRootPath = rootTemplatePath ?? path.dirname(filePath);
535
+ const source = await fs.promises.readFile(filePath, "utf8");
536
+ result = await this.render(source, data, engineName, templateRootPath, filePathOutput);
537
+ return result;
538
+ }
539
+ /**
540
+ * Synchronously render a template from a file path
541
+ * @param {string} filePath - Path to the template file to render
542
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
543
+ * @param {string} [rootTemplatePath] - Root directory for template includes. Defaults to file's directory
544
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
545
+ * @param {string} [engineName] - Engine to use. If not specified, determined from file extension
546
+ * @returns {string} The rendered template output as a string
547
+ * @example
548
+ * const result = ecto.renderFromFileSync('./templates/index.ejs', { title: 'Home' });
549
+ */
550
+ renderFromFileSync(filePath, data, rootTemplatePath, filePathOutput, engineName) {
551
+ let result = "";
552
+ engineName ??= this.getEngineByFilePath(filePath);
553
+ const templateRootPath = rootTemplatePath ?? path.dirname(filePath);
554
+ const source = fs.readFileSync(filePath, "utf8");
555
+ result = this.renderSync(source, data, engineName, templateRootPath, filePathOutput);
556
+ return result;
557
+ }
558
+ /**
559
+ * Asynchronously ensure that the directory path for a file exists, creating it if necessary
560
+ * @param {string} path - The full file path (directories will be extracted from this)
561
+ * @returns {Promise<void>}
562
+ * @example
563
+ * await ecto.ensureFilePath('/path/to/file.txt');
564
+ */
565
+ async ensureFilePath(path) {
566
+ const pathList = path.split("/");
567
+ pathList.pop();
568
+ const directory = pathList.join("/");
569
+ if (!fs.existsSync(directory)) fs.mkdirSync(directory, { recursive: true });
570
+ }
571
+ /**
572
+ * Synchronously ensure that the directory path for a file exists, creating it if necessary
573
+ * @param {string} path - The full file path (directories will be extracted from this)
574
+ * @returns {void}
575
+ * @example
576
+ * ecto.ensureFilePathSync('/path/to/file.txt');
577
+ */
578
+ ensureFilePathSync(path) {
579
+ const pathList = path.split("/");
580
+ pathList.pop();
581
+ const directory = pathList.join("/");
582
+ if (!fs.existsSync(directory)) fs.mkdirSync(directory, { recursive: true });
583
+ }
584
+ /**
585
+ * Determine the appropriate template engine based on a file's extension
586
+ * @param {string} filePath - The file path to analyze
587
+ * @returns {string} The engine name (e.g., 'ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid')
588
+ * @example
589
+ * const engine = ecto.getEngineByFilePath('template.ejs'); // Returns 'ejs'
590
+ */
591
+ getEngineByFilePath(filePath) {
592
+ let result = this._defaultEngine;
593
+ if (filePath !== void 0) {
594
+ const extension = filePath.includes(".") ? filePath.slice(filePath.lastIndexOf(".") + 1) : "";
595
+ const engExtension = this._mapping.getName(extension);
596
+ if (engExtension !== void 0) result = engExtension;
597
+ }
598
+ return result;
599
+ }
600
+ /**
601
+ * Asynchronously find a template file in a directory by name, regardless of extension
602
+ * @param {string} path - Directory path to search in
603
+ * @param {string} templateName - Template name without extension
604
+ * @returns {Promise<string>} Full path to the found template file, or empty string if not found
605
+ * @example
606
+ * const templatePath = await ecto.findTemplateWithoutExtension('./templates', 'index');
607
+ */
608
+ async findTemplateWithoutExtension(path, templateName) {
609
+ let result = "";
610
+ const files = await fs.promises.readdir(path);
611
+ for (const file of files) if (file.startsWith(`${templateName}.`)) {
612
+ result = `${path}/${file}`;
613
+ break;
614
+ }
615
+ return result;
616
+ }
617
+ /**
618
+ * Synchronously find a template file in a directory by name, regardless of extension
619
+ * @param {string} path - Directory path to search in
620
+ * @param {string} templateName - Template name without extension
621
+ * @returns {string} Full path to the found template file, or empty string if not found
622
+ * @example
623
+ * const templatePath = ecto.findTemplateWithoutExtensionSync('./templates', 'index');
624
+ */
625
+ findTemplateWithoutExtensionSync(path, templateName) {
626
+ let result = "";
627
+ const files = fs.readdirSync(path);
628
+ for (const file of files) if (file.startsWith(`${templateName}.`)) {
629
+ result = `${path}/${file}`;
630
+ break;
631
+ }
632
+ return result;
633
+ }
634
+ /**
635
+ * Check if the given engine name is valid and registered in Ecto
636
+ * @param {string} [engineName] - The engine name to validate
637
+ * @returns {boolean} True if the engine is valid and registered, false otherwise
638
+ * @example
639
+ * const isValid = ecto.isValidEngine('ejs'); // Returns true
640
+ */
641
+ isValidEngine(engineName) {
642
+ let result = false;
643
+ if (engineName !== void 0 && this._mapping.get(engineName) !== void 0) result = true;
644
+ return result;
645
+ }
646
+ /**
647
+ * Detect the template engine from a template string by analyzing its syntax
648
+ * @param {string} source - The template source string to analyze
649
+ * @returns {string} The detected engine name ('ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid') or the default engine
650
+ * @example
651
+ * const engine = ecto.detectEngine('<%= name %>'); // Returns 'ejs'
652
+ * const engine2 = ecto.detectEngine('{{name}}'); // Returns 'handlebars' or 'liquid'
653
+ * const engine3 = ecto.detectEngine('# Heading'); // Returns 'markdown'
654
+ * const engine4 = ecto.detectEngine('plain text'); // Returns defaultEngine (e.g., 'ejs')
655
+ */
656
+ detectEngine(source) {
657
+ if (!source || typeof source !== "string") return this._defaultEngine;
658
+ if (source.includes("<%")) {
659
+ if (source.includes("<%=") || source.includes("<%-") || source.includes("%>")) return "ejs";
660
+ }
661
+ if (source.includes("{%")) {
662
+ for (const keyword of [
663
+ "liquid",
664
+ "assign",
665
+ "capture",
666
+ "endcapture",
667
+ "case",
668
+ "when",
669
+ "unless",
670
+ "endunless",
671
+ "tablerow",
672
+ "endtablerow",
673
+ "increment",
674
+ "decrement"
675
+ ]) if (source.includes(`{% ${keyword}`) || source.includes(`{%${keyword}`)) return "liquid";
676
+ if (source.includes("{{") && source.includes("|") && source.includes("}}")) {
677
+ const nunjucksSpecific = [
678
+ "block",
679
+ "extends",
680
+ "macro",
681
+ "import",
682
+ "call"
683
+ ];
684
+ let hasNunjucksKeyword = false;
685
+ for (const keyword of nunjucksSpecific) if (source.includes(`{% ${keyword}`) || source.includes(`{%${keyword}`)) {
686
+ hasNunjucksKeyword = true;
687
+ break;
688
+ }
689
+ if (!hasNunjucksKeyword) return "liquid";
690
+ }
691
+ }
692
+ if (source.includes("{%")) {
693
+ for (const keyword of [
694
+ "block",
695
+ "extends",
696
+ "include",
697
+ "import",
698
+ "for",
699
+ "if",
700
+ "elif",
701
+ "else",
702
+ "endif",
703
+ "endfor",
704
+ "set",
705
+ "macro",
706
+ "endmacro",
707
+ "call"
708
+ ]) if (source.includes(`{% ${keyword}`) || source.includes(`{%${keyword}`)) return "nunjucks";
709
+ }
710
+ if (source.includes("{{")) {
711
+ if (source.includes(" | ") && source.includes("}}")) {
712
+ if (source.includes("{% assign ") || source.includes("{% capture ") || source.includes("{% unless ") || source.includes("{% increment ") || source.includes("{% decrement ") || source.includes("{% tablerow ") || source.includes("{% case ") || source.includes("{% when ") || source.includes(" | upcase") || source.includes(" | downcase") || source.includes(" | capitalize") || source.includes(" | minus:") || source.includes(" | plus:") || source.includes(" | money") || source.includes(" | date:")) return "liquid";
713
+ }
714
+ if (source.includes("{{#") || source.includes("{{/") || source.includes("{{>") || source.includes("{{!--")) return "handlebars";
715
+ /* v8 ignore next -- @preserve */
716
+ if (source.includes("}}") && !source.includes("{%")) return "handlebars";
717
+ }
718
+ const lines = source.split("\n");
719
+ let markdownIndicators = 0;
720
+ let pugIndicators = 0;
721
+ for (const line of lines) {
722
+ const trimmed = line.trim();
723
+ if (trimmed.startsWith("# ") || trimmed.startsWith("## ") || trimmed.startsWith("### ") || trimmed.startsWith("#### ") || trimmed.startsWith("##### ") || trimmed.startsWith("###### ")) markdownIndicators++;
724
+ if (trimmed.startsWith("- ") || trimmed.startsWith("* ") || trimmed.startsWith("+ ")) markdownIndicators++;
725
+ const firstChar = trimmed.charAt(0);
726
+ if (firstChar >= "0" && firstChar <= "9") {
727
+ const dotIndex = trimmed.indexOf(".");
728
+ if (dotIndex > 0 && dotIndex < 4 && trimmed.charAt(dotIndex + 1) === " ") markdownIndicators++;
729
+ }
730
+ if (trimmed.startsWith("> ")) markdownIndicators++;
731
+ if (trimmed.startsWith("```")) markdownIndicators++;
732
+ if (!trimmed.startsWith("# ") && !trimmed.startsWith("- ") && !trimmed.startsWith("* ") && !trimmed.startsWith("+ ") && !trimmed.startsWith("> ")) {
733
+ if (trimmed.startsWith("doctype") || trimmed.startsWith("html") || trimmed.startsWith("head") || trimmed.startsWith("body") || trimmed.startsWith("div") || trimmed.startsWith("p") || trimmed.startsWith("h") && trimmed.length > 1 && trimmed.charAt(1) >= "1" && trimmed.charAt(1) <= "6") pugIndicators++;
734
+ if (trimmed.includes("(") && trimmed.includes(")") || trimmed.indexOf(".") === 0 || trimmed.indexOf("#") === 0 && !trimmed.includes(" ")) pugIndicators++;
735
+ }
736
+ }
737
+ /* v8 ignore next -- @preserve */
738
+ if (source.includes("](") && (source.includes("[") || source.includes("!["))) markdownIndicators++;
739
+ if (source.includes("|") && source.includes("---")) markdownIndicators++;
740
+ if (markdownIndicators > 0) {
741
+ /* v8 ignore next -- @preserve */
742
+ if (!source.includes("<%") && !source.includes("{{") && !source.includes("{%")) return "markdown";
743
+ }
744
+ const hasHtmlOpenTag = source.includes("<") && source.includes(">");
745
+ const hasHtmlCloseTag = source.includes("</");
746
+ if (pugIndicators > 0 && !hasHtmlOpenTag && !hasHtmlCloseTag && !source.includes("<%") && !source.includes("{{") && !source.includes("{%")) return "pug";
747
+ return this._defaultEngine;
748
+ }
749
+ /**
750
+ * Register all engine mappings between engine names and file extensions
751
+ * @returns {void}
752
+ * @private
753
+ */
754
+ registerEngineMappings() {
755
+ for (const eng of this._engines) for (const name of eng.names) this._mapping.set(name, eng.getExtensions());
756
+ }
757
+ /**
758
+ * Get the render engine instance by name
759
+ * @param {string} engineName - The name of the engine to retrieve
760
+ * @returns {EngineInterface} The engine instance (defaults to EJS if not found)
761
+ * @example
762
+ * const engine = ecto.getRenderEngine('pug');
763
+ */
764
+ getRenderEngine(engineName) {
765
+ let result = this._ejs;
766
+ switch (engineName.trim().toLowerCase()) {
767
+ case "markdown":
768
+ result = this._markdown;
769
+ break;
770
+ case "pug":
771
+ result = this._pug;
772
+ break;
773
+ case "nunjucks":
774
+ result = this._nunjucks;
775
+ break;
776
+ case "mustache":
777
+ result = this._handlebars;
778
+ break;
779
+ case "handlebars":
780
+ result = this._handlebars;
781
+ break;
782
+ case "liquid":
783
+ result = this._liquid;
784
+ break;
785
+ default:
786
+ result = this._ejs;
787
+ break;
788
+ }
789
+ return result;
790
+ }
791
+ /**
792
+ * Check if the source content contains front matter (YAML metadata)
793
+ * @param {string} source - The source content to check
794
+ * @returns {boolean} True if front matter is present, false otherwise
795
+ * @example
796
+ * const hasFM = ecto.hasFrontMatter('---\ntitle: Test\n---\nContent');
797
+ */
798
+ hasFrontMatter(source) {
799
+ if (new Writr(source).frontMatterRaw !== "") return true;
800
+ return false;
801
+ }
802
+ /**
803
+ * Extract front matter data from the source content
804
+ * @param {string} source - The source content containing front matter
805
+ * @returns {Record<string, unknown>} Parsed front matter as an object
806
+ * @example
807
+ * const data = ecto.getFrontMatter('---\ntitle: Test\n---\nContent');
808
+ */
809
+ getFrontMatter(source) {
810
+ return new Writr(source).frontMatter;
811
+ }
812
+ /**
813
+ * Set or replace front matter in the source content
814
+ * @param {string} source - The source content
815
+ * @param {Record<string, unknown>} data - The front matter data to set
816
+ * @returns {string} The source content with updated front matter
817
+ * @example
818
+ * const updated = ecto.setFrontMatter('Content', { title: 'New Title' });
819
+ */
820
+ setFrontMatter(source, data) {
821
+ const writr = new Writr(source);
822
+ writr.frontMatter = data;
823
+ return writr.content;
824
+ }
825
+ /**
826
+ * Remove front matter from the source content, returning only the body
827
+ * @param {string} source - The source content with front matter
828
+ * @returns {string} The source content without front matter
829
+ * @example
830
+ * const body = ecto.removeFrontMatter('---\ntitle: Test\n---\nContent');
831
+ */
832
+ removeFrontMatter(source) {
833
+ return new Writr(source).body;
834
+ }
835
+ /**
836
+ * Write content to a file asynchronously, creating directories if needed
837
+ * @private
838
+ * @param {string} [filePath] - The path to write the file to
839
+ * @param {string} [source] - The content to write to the file
840
+ * @returns {Promise<void>}
841
+ */
842
+ async writeFile(filePath, source) {
843
+ if (filePath && source) {
844
+ await this.ensureFilePath(filePath);
845
+ await fs.promises.writeFile(filePath, source);
846
+ }
847
+ }
848
+ /**
849
+ * Write content to a file synchronously, creating directories if needed
850
+ * @private
851
+ * @param {string} [filePath] - The path to write the file to
852
+ * @param {string} [source] - The content to write to the file
853
+ * @returns {void}
854
+ */
855
+ writeFileSync(filePath, source) {
856
+ if (filePath && source) {
857
+ this.ensureFilePathSync(filePath);
858
+ fs.writeFileSync(filePath, source);
859
+ }
860
+ }
861
+ };
862
+ //#endregion
863
+ export { EJS, Ecto, EctoEvents, Handlebars, Liquid, Markdown, Nunjucks, Pug };