miki-template 2.0.0 → 2.0.1

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.
@@ -0,0 +1,214 @@
1
+ ## Integrations — miki-template
2
+
3
+ This document shows concise examples for integrating `miki-template` with popular Node.js and Bun web frameworks. Use the synchronous `render()` API for CPU-bound sync templates, and `asyncRender()` when using async helpers.
4
+
5
+ Notes
6
+ - For CommonJS: `const miki = require('miki-template');`
7
+ - For ESM / Bun: `import miki from 'miki-template';` or `import * as miki from 'miki-template';`
8
+ - When rendering files, pass `options.views` or set framework view roots so the engine can locate templates.
9
+
10
+ Setup (install)
11
+
12
+ ```bash
13
+ # npm
14
+ npm install miki-template
15
+
16
+ # bun
17
+ bun add miki-template
18
+ ```
19
+
20
+ Express (recommended: use `setupExpress`)
21
+
22
+ CommonJS
23
+
24
+ ```js
25
+ const express = require('express');
26
+ const miki = require('miki-template');
27
+
28
+ const app = express();
29
+
30
+ // One-line setup: wires engine, sets views, and patches res.render to support `view#partial`
31
+ miki.setupExpress(app, { extension: 'html', views: './views' });
32
+
33
+ app.get('/', (req, res) => {
34
+ res.render('index', { user: req.user });
35
+ });
36
+
37
+ app.get('/partial/:name', (req, res) => {
38
+ // Renders only the named partial inside the template
39
+ res.render(`index#${req.params.name}`, { user: req.user });
40
+ });
41
+
42
+ app.listen(3000);
43
+ ```
44
+
45
+ ESM / Bun (similar)
46
+
47
+ ```js
48
+ import express from 'express';
49
+ import miki from 'miki-template';
50
+
51
+ const app = express();
52
+ miki.setupExpress(app, { extension: 'html', views: './views' });
53
+ app.listen(3000);
54
+ ```
55
+
56
+ Koa
57
+
58
+ ```js
59
+ // CommonJS
60
+ const Koa = require('koa');
61
+ const path = require('path');
62
+ const miki = require('miki-template');
63
+
64
+ const app = new Koa();
65
+
66
+ // Simple render helper attached to context
67
+ app.context.render = async function (view, locals = {}) {
68
+ const html = await miki.asyncRender(view, locals, { views: path.resolve('./views') });
69
+ this.type = 'text/html';
70
+ this.body = html;
71
+ };
72
+
73
+ app.use(async (ctx) => {
74
+ await ctx.render('index', { user: ctx.state.user });
75
+ });
76
+
77
+ app.listen(3000);
78
+ ```
79
+
80
+ Fastify
81
+
82
+ ```js
83
+ const Fastify = require('fastify');
84
+ const path = require('path');
85
+ const miki = require('miki-template');
86
+
87
+ const app = Fastify();
88
+
89
+ app.get('/', async (request, reply) => {
90
+ const html = await miki.asyncRender('index', { user: request.user }, { views: path.resolve('./views') });
91
+ reply.type('text/html').send(html);
92
+ });
93
+
94
+ app.listen(3000);
95
+ ```
96
+
97
+ NestJS (Express under the hood)
98
+
99
+ ```ts
100
+ // In main.ts
101
+ import { NestFactory } from '@nestjs/core';
102
+ import { AppModule } from './app.module';
103
+ import * as miki from 'miki-template';
104
+
105
+ async function bootstrap() {
106
+ const app = await NestFactory.create(AppModule);
107
+ // Use the underlying Express instance
108
+ const expressApp = app.getHttpAdapter().getInstance();
109
+ miki.setupExpress(expressApp, { extension: 'html', views: './views' });
110
+ await app.listen(3000);
111
+ }
112
+ bootstrap();
113
+ ```
114
+
115
+ Ts.ED
116
+
117
+ ```ts
118
+ // In server bootstrap
119
+ import { ServerLoader } from '@tsed/di';
120
+ import * as miki from 'miki-template';
121
+
122
+ // Ts.ED also runs on Express/Koa — obtain the underlying app
123
+ // and call miki.setupExpress(...) when using the Express adapter.
124
+
125
+ // Example when using Express adapter:
126
+ // miki.setupExpress(server.rawApp, { extension: 'html', views: './views' });
127
+ ```
128
+
129
+ Elysia (Bun-friendly)
130
+
131
+ ```js
132
+ // ESM / Bun example
133
+ import { Elysia } from 'elysia';
134
+ import * as miki from 'miki-template';
135
+ import path from 'path';
136
+
137
+ const app = new Elysia();
138
+
139
+ app.get('/', async () => {
140
+ const html = await miki.asyncRender('index', { }, { views: path.resolve('./views') });
141
+ return new Response(html, { headers: { 'Content-Type': 'text/html' } });
142
+ });
143
+
144
+ app.listen(3000);
145
+ ```
146
+
147
+ Hono (Edge + Bun)
148
+
149
+ ```js
150
+ import { Hono } from 'hono';
151
+ import * as miki from 'miki-template';
152
+ import path from 'path';
153
+
154
+ const app = new Hono();
155
+
156
+ app.get('/', async (c) => {
157
+ const html = await miki.asyncRender('index', { }, { views: path.resolve('./views') });
158
+ return c.html(html);
159
+ });
160
+
161
+ app.listen({ port: 3000 });
162
+ ```
163
+
164
+ Nifra / other minimal frameworks
165
+
166
+ ```js
167
+ // Generic handler pattern — works in almost any framework
168
+ // (Nifra users can adapt the response API)
169
+ const miki = require('miki-template');
170
+ const path = require('path');
171
+
172
+ async function handler(req, res) {
173
+ const html = await miki.asyncRender('index', { }, { views: path.resolve('./views') });
174
+ res.setHeader('Content-Type', 'text/html');
175
+ res.end(html);
176
+ }
177
+ ```
178
+
179
+ Bun-specific notes
180
+ - Bun is ESM-first; import `miki-template` using `import miki from 'miki-template'`.
181
+ - Use `bun add miki-template` to install.
182
+ - When using Bun's native servers, call `miki.asyncRender(...)` and return/send the Response object accordingly.
183
+
184
+ Tips and best practices
185
+ - Prefer `miki.setupExpress()` for Express-based apps — it wires partial rendering and view expansion.
186
+ - For non-Express frameworks, call `miki.render()` (sync) or `miki.asyncRender()` (async) and set `options.views` to your views root (or pass absolute file paths resolved with your framework).
187
+ - To support Django-style app templates (e.g. `packages/*/templates/...`), call `miki.setAppTemplateDirNames(['templates','app_templates'])` early in your app startup if you use a custom folder name.
188
+
189
+ Engine usage & partial rendering
190
+
191
+ Use the engine APIs directly when you don't want framework-specific wiring or when you need fine-grained control over `views` roots.
192
+
193
+ ```js
194
+ const miki = require('miki-template');
195
+ const path = require('path');
196
+
197
+ // Sync render of a named partial inside a template file
198
+ const html = miki.render('home#card', { user: 'Alice', title: 'Card' }, { views: path.resolve('./views') });
199
+
200
+ // Async render when templates use async helpers
201
+ const htmlAsync = await miki.asyncRender('home#card', { user: 'Bob' }, { views: path.resolve('./views') });
202
+
203
+ // If your project arranges templates under custom folder names, configure
204
+ // what constitutes an "app template" directory before rendering:
205
+ miki.setAppTemplateDirNames(['templates', 'app_templates']);
206
+
207
+ // To locate a template file programmatically without rendering, use the
208
+ // exported finder helper:
209
+ const found = miki.findTemplateInViews('home', [path.resolve('./views')]);
210
+ if (found) console.log('Resolved to', found);
211
+ ```
212
+
213
+ Further reading
214
+ - See the main API docs for `setupExpress`, `render`, and `asyncRender` in `docs/api.md`.
@@ -0,0 +1,16 @@
1
+ import { Elysia } from 'elysia';
2
+ import path from 'path';
3
+ import miki from '../../src/esm.mjs';
4
+
5
+ const app = new Elysia();
6
+
7
+ app.get('/', async () => {
8
+ const html = await miki.asyncRender('home', {}, { views: path.resolve('./live-test/views') });
9
+ return new Response(html, { headers: { 'Content-Type': 'text/html' } });
10
+ });
11
+
12
+ export async function start(port = 3004) {
13
+ return app.listen({ port });
14
+ }
15
+
16
+ if (import.meta.url === `file://${process.argv[1]}`) start().then(() => console.log('Elysia example listening on 3004'));
@@ -0,0 +1,24 @@
1
+ const express = require('express');
2
+ const path = require('path');
3
+ const miki = require('../../');
4
+
5
+ const app = express();
6
+ miki.setupExpress(app, { extension: 'html', views: path.resolve(__dirname, '..', 'views') });
7
+
8
+ app.get('/', (req, res) => res.render('home', { user: 'ExpressUser', title: 'ExpressCard' }));
9
+ app.get('/partial', (req, res) => res.render('home#card', { user: 'ExpressUser', title: 'ExpressCard' }));
10
+
11
+ function start(port = 3000, host = '127.0.0.1') {
12
+ return new Promise((resolve, reject) => {
13
+ try {
14
+ const srv = app.listen(port, host, () => {
15
+ console.log('Express example listening on', port);
16
+ resolve(srv);
17
+ });
18
+ } catch (err) { reject(err); }
19
+ });
20
+ }
21
+
22
+ if (require.main === module) start().catch(err => { console.error(err); process.exit(1); });
23
+
24
+ module.exports = { app, start };
@@ -0,0 +1,20 @@
1
+ const Fastify = require('fastify');
2
+ const path = require('path');
3
+ const miki = require('../../');
4
+
5
+ const app = Fastify();
6
+
7
+ app.get('/', async (request, reply) => {
8
+ const html = await miki.asyncRender('home', { user: 'FastifyUser', title: 'FastifyCard' }, { views: path.resolve(__dirname, '..', 'views') });
9
+ reply.type('text/html').send(html);
10
+ });
11
+
12
+ function start(port = 3002, host = '127.0.0.1') {
13
+ return app.listen({ port, host });
14
+ }
15
+
16
+ if (require.main === module) {
17
+ start().then(() => console.log('Fastify example listening on 3002')).catch(err => { console.error('Fastify failed to start', err); process.exit(1); });
18
+ }
19
+
20
+ module.exports = { app, start };
@@ -0,0 +1,16 @@
1
+ import { Hono } from 'hono';
2
+ import miki from '../../src/esm.mjs';
3
+ import path from 'path';
4
+
5
+ const app = new Hono();
6
+
7
+ app.get('/', async (c) => {
8
+ const html = await miki.asyncRender('home', {}, { views: path.resolve('./live-test/views') });
9
+ return c.html(html);
10
+ });
11
+
12
+ export async function start(port = 3005) {
13
+ return app.listen({ port });
14
+ }
15
+
16
+ if (import.meta.url === `file://${process.argv[1]}`) start().then(() => console.log('Hono example listening on 3005'));
@@ -0,0 +1,30 @@
1
+ const Koa = require('koa');
2
+ const path = require('path');
3
+ const miki = require('../../');
4
+
5
+ const app = new Koa();
6
+
7
+ app.context.render = async function (view, locals = {}) {
8
+ const html = await miki.asyncRender(view, locals, { views: path.resolve(__dirname, '..', 'views') });
9
+ this.type = 'text/html';
10
+ this.body = html;
11
+ };
12
+
13
+ app.use(async (ctx) => {
14
+ await ctx.render('home', { user: 'KoaUser', title: 'KoaCard' });
15
+ });
16
+
17
+ function start(port = 3001, host = '127.0.0.1') {
18
+ return new Promise((resolve, reject) => {
19
+ try {
20
+ const srv = app.listen(port, host, () => {
21
+ console.log('Koa example listening on', port);
22
+ resolve(srv);
23
+ });
24
+ } catch (err) { reject(err); }
25
+ });
26
+ }
27
+
28
+ if (require.main === module) start().catch(err => { console.error(err); process.exit(1); });
29
+
30
+ module.exports = { app, start };
@@ -0,0 +1,25 @@
1
+ /*
2
+ Minimal NestJS integration example (TypeScript flavor shown).
3
+
4
+ This file is an illustrative snippet and is NOT executed by the
5
+ smoke-test (NestJS requires heavier deps). Use it as a guide.
6
+
7
+ // main.ts
8
+ import { NestFactory } from '@nestjs/core';
9
+ import { AppModule } from './app.module';
10
+ import * as miki from 'miki-template';
11
+
12
+ async function bootstrap() {
13
+ const app = await NestFactory.create(AppModule);
14
+ const expressApp = app.getHttpAdapter().getInstance();
15
+ // Wire miki into underlying Express instance
16
+ miki.setupExpress(expressApp, { extension: 'html', views: './views' });
17
+ await app.listen(3006);
18
+ }
19
+
20
+ bootstrap();
21
+
22
+ */
23
+
24
+ // Plain JS note: If you use Nest with JS, the same pattern applies:
25
+ // obtain the underlying Express instance and call miki.setupExpress(...)
@@ -0,0 +1,166 @@
1
+ const { spawn } = require('child_process');
2
+ const path = require('path');
3
+ const http = require('http');
4
+
5
+ async function start(scriptPath) {
6
+ // Skip optional ESM integrations when their deps are missing
7
+ const missing = {
8
+ 'elysia-example.js': 'elysia',
9
+ 'hono-example.js': 'hono'
10
+ };
11
+ const basename = path.basename(scriptPath);
12
+ if (missing[basename]) {
13
+ try { require.resolve(missing[basename]); }
14
+ catch {
15
+ console.warn(`Skipping ${basename}: ${missing[basename]} is not installed`);
16
+ return null;
17
+ }
18
+ }
19
+
20
+ // Require the example module and call its exported start() which
21
+ // returns a Promise or a server instance.
22
+ const mod = require(scriptPath);
23
+ if (mod && typeof mod.start === 'function') {
24
+ let res;
25
+ try {
26
+ res = mod.start();
27
+ } catch (err) {
28
+ console.warn(`Skipping ${basename}: start() failed: ${err.message}`);
29
+ return null;
30
+ }
31
+ // Fastify returns a Promise resolving to server address; Koa/Express
32
+ // return a server instance synchronously — normalize both.
33
+ if (res && typeof res.then === 'function') {
34
+ try {
35
+ await res;
36
+ return res;
37
+ } catch (err) {
38
+ console.warn(`Skipping ${basename}: start() promise rejected: ${err.message}`);
39
+ return null;
40
+ }
41
+ }
42
+ return res;
43
+ }
44
+ // Fallback: spawn as a child process
45
+ return new Promise((resolve, reject) => {
46
+ const child = spawn(process.execPath, [scriptPath], { stdio: 'inherit' });
47
+ child.on('error', reject);
48
+ setTimeout(() => resolve(child), 800);
49
+ });
50
+ }
51
+
52
+ async function fetch(url) {
53
+ return new Promise((resolve, reject) => {
54
+ http.get(url, res => {
55
+ let data = '';
56
+ res.on('data', c => data += c.toString());
57
+ res.on('end', () => resolve({ status: res.statusCode, body: data }));
58
+ }).on('error', reject);
59
+ });
60
+ }
61
+
62
+ async function main() {
63
+ const root = path.resolve(__dirname);
64
+ const servers = [
65
+ { file: path.join(root, 'express-example.js'), url: 'http://localhost:3000/' },
66
+ { file: path.join(root, 'koa-example.js'), url: 'http://localhost:3001/' },
67
+ { file: path.join(root, 'fastify-example.js'), url: 'http://localhost:3002/' }
68
+ ];
69
+ // Add ESM-based examples (elysia, hono). These will be spawned as
70
+ // child processes if they cannot be required as modules.
71
+ servers.push({ file: path.join(root, 'elysia-example.js'), url: 'http://localhost:3004/' });
72
+ servers.push({ file: path.join(root, 'hono-example.js'), url: 'http://localhost:3005/' });
73
+
74
+ const procs = [];
75
+ for (const s of servers) {
76
+ procs.push(await start(s.file));
77
+ }
78
+
79
+ // Test each server
80
+ for (let i = 0; i < servers.length; i++) {
81
+ const s = servers[i];
82
+ const p = procs[i];
83
+ if (!p) {
84
+ console.warn(`Skipping smoke-test for ${path.basename(s.file)} (not running)`);
85
+ continue;
86
+ }
87
+ try {
88
+ const res = await fetch(s.url);
89
+ console.log(`${s.url} -> ${res.status} length=${res.body.length}`);
90
+ } catch (e) {
91
+ console.error(`Failed to fetch ${s.url}:`, e.message || e);
92
+ }
93
+ }
94
+
95
+ // Test partial route on express
96
+ try {
97
+ const res = await fetch('http://localhost:3000/partial');
98
+ console.log(`/partial -> ${res.status} length=${res.body.length}`);
99
+ } catch (e) { console.error('Partial fetch failed', e.message || e); }
100
+
101
+ // Programmatic engine tests: render('home#card') via the engine APIs
102
+ try {
103
+ // Try requiring as if the package were installed; fallback to local
104
+ let miki;
105
+ try { miki = require('miki-template'); } catch (e) { miki = require('../..'); }
106
+
107
+ // For each framework, test programmatic partial rendering and finder behavior
108
+ const frameworks = ['express', 'koa', 'fastify', 'elysia', 'hono'];
109
+ for (const name of frameworks) {
110
+ const viewsDir = path.resolve(__dirname, '..', 'views');
111
+ try {
112
+ const asyncHtml = await miki.asyncRender('home#card', { user: name + 'Async', title: name + 'Card' }, { views: viewsDir });
113
+ console.log(`${name}: asyncRender(home#card) length=${asyncHtml.length}`);
114
+ } catch (e) { console.error(`${name}: asyncRender failed`, e && e.message ? e.message : e); }
115
+
116
+ try {
117
+ const syncHtml = miki.render('home#card', { user: name + 'Sync', title: name + 'Card' }, { views: viewsDir });
118
+ console.log(`${name}: render(home#card) length=${syncHtml.length}`);
119
+ } catch (e) { console.error(`${name}: render failed`, e && e.message ? e.message : e); }
120
+
121
+ // Finder tests: simulate multiple view roots including nested app-template dirs
122
+ try {
123
+ const found = miki.findTemplateInViews('home', [viewsDir, path.resolve(__dirname, '..')]);
124
+ console.log(`${name}: finder resolved -> ${found ? found : 'not found'}`);
125
+ } catch (e) { console.error(`${name}: finder error`, e && e.message ? e.message : e); }
126
+ }
127
+ } catch (e) {
128
+ console.error('Engine partial render failed:', e && e.stack ? e.stack : e);
129
+ }
130
+
131
+ // Cleanup: attempt graceful shutdown for each started server
132
+ for (let i = 0; i < procs.length; i++) {
133
+ const p = procs[i];
134
+ if (!p) continue;
135
+ try {
136
+ if (typeof p.kill === 'function') {
137
+ p.kill();
138
+ continue;
139
+ }
140
+ if (typeof p.close === 'function') {
141
+ p.close();
142
+ continue;
143
+ }
144
+ // Fastify may return an address string; try to require module and call exported stop/close
145
+ try {
146
+ const mod = require(servers[i].file);
147
+ if (mod) {
148
+ if (typeof mod.stop === 'function') await mod.stop();
149
+ else if (typeof mod.close === 'function') await mod.close();
150
+ else if (mod.app && typeof mod.app.close === 'function') mod.app.close();
151
+ }
152
+ } catch (e) {
153
+ // ignore
154
+ }
155
+ } catch (e) {
156
+ // ignore errors during cleanup
157
+ }
158
+ }
159
+ }
160
+
161
+ if (require.main === module) {
162
+ main().catch(err => {
163
+ console.error('smoke-test failed', err && err.stack ? err.stack : err);
164
+ process.exit(1);
165
+ });
166
+ }
@@ -0,0 +1,23 @@
1
+ /*
2
+ Ts.ED integration (Express adapter)
3
+
4
+ This is an example snippet for Ts.ED users. Ts.ED can run on Express
5
+ or Koa — when using the Express adapter, obtain the raw Express app
6
+ and call `miki.setupExpress()` as shown.
7
+
8
+ // server.ts (snippet)
9
+ import { ServerLoader } from '@tsed/di';
10
+ import * as miki from 'miki-template';
11
+
12
+ async function bootstrap() {
13
+ const server = await ServerLoader.bootstrap();
14
+ // server.rawApp is the underlying Express/Koa instance depending on adapter
15
+ miki.setupExpress(server.rawApp, { extension: 'html', views: './views' });
16
+ await server.listen();
17
+ }
18
+
19
+ bootstrap();
20
+
21
+ */
22
+
23
+ // Plain JS: same approach — call setupExpress on the underlying app.