@celljs/mvc 4.0.0 → 4.2.0

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 (44) hide show
  1. package/README.md +13 -1
  2. package/esm/node/module.d.ts +1 -1
  3. package/esm/node/view/file-view.js +5 -3
  4. package/esm/node/view/file-view.js.map +1 -1
  5. package/esm/node/view/html-view.d.ts +8 -1
  6. package/esm/node/view/html-view.js +13 -7
  7. package/esm/node/view/html-view.js.map +1 -1
  8. package/esm/node/view/index.d.ts +1 -0
  9. package/esm/node/view/index.js +1 -0
  10. package/esm/node/view/index.js.map +1 -1
  11. package/esm/node/view/template.d.ts +33 -0
  12. package/esm/node/view/template.js +161 -0
  13. package/esm/node/view/template.js.map +1 -0
  14. package/lib/node/module.d.ts +1 -1
  15. package/lib/node/mvc-http.spec.d.ts +2 -0
  16. package/lib/node/mvc-http.spec.d.ts.map +1 -0
  17. package/lib/node/mvc-http.spec.js +532 -0
  18. package/lib/node/mvc-http.spec.js.map +1 -0
  19. package/lib/node/view/file-view.d.ts.map +1 -1
  20. package/lib/node/view/file-view.js +6 -3
  21. package/lib/node/view/file-view.js.map +1 -1
  22. package/lib/node/view/html-view.d.ts +8 -1
  23. package/lib/node/view/html-view.d.ts.map +1 -1
  24. package/lib/node/view/html-view.js +13 -9
  25. package/lib/node/view/html-view.js.map +1 -1
  26. package/lib/node/view/index.d.ts +1 -0
  27. package/lib/node/view/index.d.ts.map +1 -1
  28. package/lib/node/view/index.js +1 -0
  29. package/lib/node/view/index.js.map +1 -1
  30. package/lib/node/view/template.d.ts +34 -0
  31. package/lib/node/view/template.d.ts.map +1 -0
  32. package/lib/node/view/template.js +165 -0
  33. package/lib/node/view/template.js.map +1 -0
  34. package/lib/node/view/template.spec.d.ts +2 -0
  35. package/lib/node/view/template.spec.d.ts.map +1 -0
  36. package/lib/node/view/template.spec.js +35 -0
  37. package/lib/node/view/template.spec.js.map +1 -0
  38. package/package.json +7 -11
  39. package/src/node/mvc-http.spec.ts +352 -0
  40. package/src/node/view/file-view.ts +5 -2
  41. package/src/node/view/html-view.ts +15 -7
  42. package/src/node/view/index.ts +2 -1
  43. package/src/node/view/template.spec.ts +34 -0
  44. package/src/node/view/template.ts +170 -0
@@ -0,0 +1,352 @@
1
+ import { describe, it, afterEach } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { Server } from 'node:http';
4
+ import { AddressInfo } from 'node:net';
5
+ // 按 CLI 生成的后端入口加载顺序导入:core 的 static module → web 的 module → mvc 的 module(见 @celljs/vite 的
6
+ // ContainerGenerator 与各包 package.json 的 cell 字段)。不要导入 application-factory:它会顺带登记 CommonApplication,
7
+ // 和 node 的 BackendApplication 冲突。
8
+ import coreCommonStatic from '@celljs/core/lib/common/static-module';
9
+ import coreNodeStatic from '@celljs/core/lib/node/static-module';
10
+ import webCommonModule from '@celljs/web/lib/common/module';
11
+ import webNodeModule from '@celljs/web/lib/node/module';
12
+ import mvcNodeModule from './module';
13
+ import { Container } from '@celljs/core/lib/common/container/container';
14
+ import { ContainerProvider } from '@celljs/core/lib/common/container/container-provider';
15
+ import { autoBind } from '@celljs/core/lib/common/container/auto-bind';
16
+ import { currentThis } from '@celljs/core/lib/common/utils';
17
+ import { Application } from '@celljs/core/lib/common/application/application-protocol';
18
+ import { NotFoundError, HttpError, HttpServerUtil } from '@celljs/web/lib/node';
19
+ import {
20
+ Controller, Get, Post, Put, Delete, Patch, All, Param, Query, Body, Header, Cookie, Session, Req, Res, Text, Json, Catch
21
+ } from './annotation';
22
+
23
+ /**
24
+ * mvc 的 HTTP 行为约定(阶段 1.E 行为测试):经真实 HTTP 请求断言路由、参数解析、响应与异常。
25
+ *
26
+ * 请求路径与 express-adapter 的 http-application-entry 相同:HttpServerUtil.createHttpServer 收到请求 →
27
+ * new Context(req, res) → Context.run → Dispatcher.dispatch。
28
+ * 配置是 core / web / mvc / http 的 cell.yml 合并后的默认值(CLI 会做这一步;这里照抄,保持与 cell.yml 一致)。
29
+ * 阶段 2 换 HTTP 管线时,只需要替换 serve(),用例本身不用改。
30
+ */
31
+
32
+ const DEFAULT_CONFIG = {
33
+ cell: {
34
+ // core/cell.yml
35
+ name: 'Cell Framework', annotation: { Component: { proxy: false } }, aop: { enabled: true }, logger: { level: 'error' }, tenant: { enabled: false },
36
+ // web/cell.yml(含 backend 段)
37
+ session: { autoCommit: true, maxAge: 86400000, sessionIdKey: 'cell:sessionId', sessionKey: 'cell:session' },
38
+ server: { path: '/', port: 3000, host: '127.0.0.1', endpoint: 'http://localhost:${cell.server.port}' },
39
+ trace: { requestField: 'X-Cell-Trace-ID', responseField: 'X-Cell-Trace-ID' },
40
+ health: { url: '/health', method: 'GET' },
41
+ web: { route: { cacheSize: 500 }, validationPipeOptions: { detailedOutputDisabled: false, transformEnabled: true } },
42
+ cookies: { keys: ['abcdef'] },
43
+ // mvc/cell.yml
44
+ mvc: { path: '/*', defaultViewName: 'json', baseFileDir: 'assets' },
45
+ mustache: { cache: false, baseViewDir: 'assets/views' },
46
+ // http/cell.yml
47
+ client: { config: { withCredentials: true, headers: { 'X-Requested-With': 'XMLHttpRequest' } } },
48
+ },
49
+ };
50
+
51
+ let server: Server | undefined;
52
+ afterEach(async () => {
53
+ await new Promise<void>(r => (server ? server.close(() => r()) : r()));
54
+ server = undefined;
55
+ });
56
+
57
+ /** 启动应用(在调用之前定义好的控制器都会被装配),返回指向它的 fetch。 */
58
+ async function serve(): Promise<(path: string, init?: RequestInit) => Promise<Response>> {
59
+ currentThis.cellProps = structuredClone(DEFAULT_CONFIG);
60
+ const container = new Container(coreCommonStatic, coreNodeStatic, webCommonModule, webNodeModule, mvcNodeModule, autoBind());
61
+ ContainerProvider.set(container);
62
+ const app = container.get<Application>(Application);
63
+ await app.start();
64
+ server = HttpServerUtil.createHttpServer(HttpServerUtil.createHandler(container));
65
+ await new Promise<void>(r => server!.listen(0, '127.0.0.1', r));
66
+ const base = `http://127.0.0.1:${(server!.address() as AddressInfo).port}`;
67
+ return (path, init) => fetch(base + path, init);
68
+ }
69
+
70
+ const JSON_HEADERS = { 'content-type': 'application/json' };
71
+
72
+ describe('mvc 路由', () => {
73
+
74
+ it('按控制器前缀 + 方法路径匹配;HTTP 方法不同走不同处理函数', async () => {
75
+ @Controller('items')
76
+ class Items {
77
+ @Get()
78
+ list() { return ['a', 'b']; }
79
+ @Get(':id')
80
+ one(@Param('id') id: string) { return { id }; }
81
+ @Post()
82
+ create() { return 'created'; }
83
+ @Put(':id')
84
+ replace(@Param('id') id: string) { return `put ${id}`; }
85
+ @Patch(':id')
86
+ patch(@Param('id') id: string) { return `patch ${id}`; }
87
+ @Delete(':id')
88
+ remove(@Param('id') id: string) { return `deleted ${id}`; }
89
+ }
90
+ const f = await serve();
91
+ expect(await (await f('/items')).json()).to.deep.equal(['a', 'b']);
92
+ expect(await (await f('/items/42')).json()).to.deep.equal({ id: '42' });
93
+ expect(await (await f('/items', { method: 'POST' })).json()).to.equal('created');
94
+ expect(await (await f('/items/1', { method: 'PUT' })).json()).to.equal('put 1');
95
+ expect(await (await f('/items/1', { method: 'PATCH' })).json()).to.equal('patch 1');
96
+ expect(await (await f('/items/1', { method: 'DELETE' })).json()).to.equal('deleted 1');
97
+ expect(Items).to.be.a('function');
98
+ });
99
+
100
+ it('没有前缀的控制器;@All 匹配所有方法', async () => {
101
+ @Controller()
102
+ class Root {
103
+ @Get()
104
+ @Text()
105
+ home() { return 'home'; }
106
+ @All('any')
107
+ @Text()
108
+ any() { return 'any'; }
109
+ }
110
+ const f = await serve();
111
+ expect(await (await f('/')).text()).to.equal('home');
112
+ for (const method of ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']) {
113
+ expect(await (await f('/any', { method })).text()).to.equal('any');
114
+ }
115
+ expect(Root).to.be.a('function');
116
+ });
117
+
118
+ it('没有匹配的路由返回 404,错误信息里有方法和路径', async () => {
119
+ @Controller('only')
120
+ class Only {
121
+ @Get()
122
+ get() { return 1; }
123
+ }
124
+ const f = await serve();
125
+ const res = await f('/nowhere');
126
+ expect(res.status).to.equal(404);
127
+ expect(await res.text()).to.contain('/nowhere');
128
+ expect((await f('/only', { method: 'POST' })).status).to.equal(404);
129
+ expect(Only).to.be.a('function');
130
+ });
131
+ });
132
+
133
+ describe('mvc 参数解析', () => {
134
+
135
+ it('@Param / @Query / @Body / @Header 取单个值或整体', async () => {
136
+ @Controller('args')
137
+ class Args {
138
+ @Post(':a/:b')
139
+ all(
140
+ @Param('a') a: string, @Param() params: any,
141
+ @Query('q') q: string, @Query() query: any,
142
+ @Body('name') name: string, @Body() body: any,
143
+ @Header('x-probe') probe: string, @Header() headers: any
144
+ ) {
145
+ return { a, params, q, query, name, body, probe, hasHost: !!headers.host };
146
+ }
147
+ }
148
+ const f = await serve();
149
+ const res = await f('/args/1/2?q=x&r=y', { method: 'POST', headers: { ...JSON_HEADERS, 'x-probe': 'p' }, body: JSON.stringify({ name: 'n', n: 1 }) });
150
+ expect(res.status).to.equal(200);
151
+ expect(await res.json()).to.deep.equal({
152
+ a: '1', params: { a: '1', b: '2' }, q: 'x', query: { q: 'x', r: 'y' },
153
+ name: 'n', body: { name: 'n', n: 1 }, probe: 'p', hasHost: true,
154
+ });
155
+ expect(Args).to.be.a('function');
156
+ });
157
+
158
+ it('请求体:JSON、表单(urlencoded,支持嵌套)、纯文本', async () => {
159
+ @Controller('body')
160
+ class BodyCtl {
161
+ @Post()
162
+ echo(@Body() body: any) { return { body }; }
163
+ }
164
+ const f = await serve();
165
+ expect(await (await f('/body', { method: 'POST', headers: JSON_HEADERS, body: '{"x":[1,2]}' })).json()).to.deep.equal({ body: { x: [1, 2] } });
166
+ const form = await f('/body', { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'a=1&b[c]=2' });
167
+ expect(await form.json()).to.deep.equal({ body: { a: '1', b: { c: '2' } } });
168
+ const text = await f('/body', { method: 'POST', headers: { 'content-type': 'text/plain' }, body: 'hello' });
169
+ expect(await text.json()).to.deep.equal({ body: 'hello' });
170
+ expect(BodyCtl).to.be.a('function');
171
+ });
172
+
173
+ it('非法 JSON 请求体返回 400,处理函数不会被调用', async () => {
174
+ let called = false;
175
+ @Controller('bad')
176
+ class Bad {
177
+ @Post()
178
+ take() { called = true; return 1; }
179
+ }
180
+ const f = await serve();
181
+ const res = await f('/bad', { method: 'POST', headers: JSON_HEADERS, body: '{oops' });
182
+ expect(res.status).to.equal(400);
183
+ expect(await res.text()).to.not.match(/\n\s+at /);
184
+ expect(called).to.equal(false);
185
+ expect(Bad).to.be.a('function');
186
+ });
187
+
188
+ it.todo('期望:请求体解析失败(body-parser 的 err.status 为 4xx)时返回对应的 4xx,而不是 500', () => { });
189
+
190
+ it('@Req / @Res 拿到原始请求和响应', async () => {
191
+ @Controller('raw')
192
+ class Raw {
193
+ @Get()
194
+ @Text()
195
+ raw(@Req() req: any, @Res() res: any) {
196
+ res.setHeader('x-from-res', 'yes');
197
+ return `${req.method} ${req.path}`;
198
+ }
199
+ }
200
+ const f = await serve();
201
+ const res = await f('/raw');
202
+ expect(res.headers.get('x-from-res')).to.equal('yes');
203
+ expect(await res.text()).to.equal('GET /raw');
204
+ expect(Raw).to.be.a('function');
205
+ });
206
+
207
+ it('@Cookie 读请求 cookie;@Cookie(name, value) 在响应里设置 cookie', async () => {
208
+ @Controller('cookie')
209
+ class CookieCtl {
210
+ @Get('read')
211
+ read(@Cookie('who') who: string) { return { who: who ?? null }; }
212
+ @Get('write')
213
+ @Cookie('flavor', 'oat')
214
+ write() { return 'ok'; }
215
+ }
216
+ const f = await serve();
217
+ expect(await (await f('/cookie/read', { headers: { cookie: 'who=me' } })).json()).to.deep.equal({ who: 'me' });
218
+ const set = (await f('/cookie/write')).headers.get('set-cookie') ?? '';
219
+ expect(set).to.match(/flavor=oat/);
220
+ expect(CookieCtl).to.be.a('function');
221
+ });
222
+
223
+ it('@Session:写入的值在同一会话的下一次请求里能读到', async () => {
224
+ @Controller('session')
225
+ class SessionCtl {
226
+ @Get('set')
227
+ @Session('step', 'two')
228
+ set() { return 'set'; }
229
+ @Get('get')
230
+ get(@Session('step') step: string) { return { step: step ?? null }; }
231
+ }
232
+ const f = await serve();
233
+ const first = await f('/session/set');
234
+ const cookies = (first.headers.getSetCookie?.() ?? [first.headers.get('set-cookie') ?? ''])
235
+ .map(c => c.split(';')[0]).filter(Boolean).join('; ');
236
+ expect(cookies).to.not.equal('');
237
+ expect(await (await f('/session/get', { headers: { cookie: cookies } })).json()).to.deep.equal({ step: 'two' });
238
+ expect(await (await f('/session/get')).json()).to.deep.equal({ step: null });
239
+ expect(SessionCtl).to.be.a('function');
240
+ });
241
+ });
242
+
243
+ describe('mvc 响应', () => {
244
+
245
+ it('默认 JSON 视图;@Text 输出文本;@Json 显式 JSON;内容类型正确', async () => {
246
+ @Controller('views')
247
+ class Views {
248
+ @Get('default')
249
+ dflt() { return { ok: true }; }
250
+ @Get('text')
251
+ @Text()
252
+ text() { return 'plain'; }
253
+ @Get('json')
254
+ @Json()
255
+ json() { return [1, 2]; }
256
+ }
257
+ const f = await serve();
258
+ const d = await f('/views/default');
259
+ expect(d.headers.get('content-type')).to.match(/application\/json/);
260
+ expect(await d.json()).to.deep.equal({ ok: true });
261
+ const t = await f('/views/text');
262
+ expect(t.headers.get('content-type')).to.match(/text\/plain/);
263
+ expect(await t.text()).to.equal('plain');
264
+ expect(await (await f('/views/json')).json()).to.deep.equal([1, 2]);
265
+ expect(Views).to.be.a('function');
266
+ });
267
+
268
+ it('@Header(name, value) 设置响应头;async 处理函数的返回值同样生效', async () => {
269
+ @Controller('hdr')
270
+ class Hdr {
271
+ @Get()
272
+ @Header('x-powered', 'cell')
273
+ async get() {
274
+ await new Promise(r => setImmediate(r));
275
+ return { late: true };
276
+ }
277
+ }
278
+ const f = await serve();
279
+ const res = await f('/hdr');
280
+ expect(res.headers.get('x-powered')).to.equal('cell');
281
+ expect(await res.json()).to.deep.equal({ late: true });
282
+ expect(Hdr).to.be.a('function');
283
+ });
284
+
285
+ it('返回 undefined 时状态 200', async () => {
286
+ @Controller('void')
287
+ class Void {
288
+ @Delete()
289
+ remove(): void { }
290
+ }
291
+ const f = await serve();
292
+ const res = await f('/void', { method: 'DELETE' });
293
+ expect(res.status).to.equal(200);
294
+ expect(Void).to.be.a('function');
295
+ });
296
+ });
297
+
298
+ describe('mvc 异常', () => {
299
+
300
+ it('抛 HttpError 子类时用它的状态码(如 NotFoundError → 404),响应体是 JSON 且带错误信息', async () => {
301
+ @Controller('err')
302
+ class Err {
303
+ @Get('nf')
304
+ nf() { throw new NotFoundError('no such thing'); }
305
+ @Get('teapot')
306
+ teapot() { throw new HttpError(418, 'teapot'); }
307
+ }
308
+ const f = await serve();
309
+ const nf = await f('/err/nf');
310
+ expect(nf.status).to.equal(404);
311
+ expect(nf.headers.get('content-type')).to.match(/application\/json/);
312
+ expect(await nf.text()).to.contain('no such thing');
313
+ expect((await f('/err/teapot')).status).to.equal(418);
314
+ expect(Err).to.be.a('function');
315
+ });
316
+
317
+ it('抛普通 Error 时返回 500,应用继续服务后续请求', async () => {
318
+ @Controller('boom')
319
+ class Boom {
320
+ @Get()
321
+ boom() { throw new Error('kaboom'); }
322
+ @Get('ok')
323
+ ok() { return 'fine'; }
324
+ }
325
+ const f = await serve();
326
+ const res = await f('/boom');
327
+ expect(res.status).to.equal(500);
328
+ // 响应体不带调用栈
329
+ expect(await res.text()).to.not.match(/\n\s+at /);
330
+ expect(await (await f('/boom/ok')).json()).to.equal('fine');
331
+ expect(Boom).to.be.a('function');
332
+ });
333
+
334
+ it('@Catch:控制器里声明的异常处理方法接管匹配类型的错误', async () => {
335
+ class QuotaError extends Error { }
336
+ @Controller('catch')
337
+ class Catching {
338
+ @Get()
339
+ run() { throw new QuotaError('over quota'); }
340
+ @Get('other')
341
+ other() { throw new Error('other'); }
342
+ @Catch(QuotaError)
343
+ @Text()
344
+ onQuota(err: QuotaError) { return `handled: ${err.message}`; }
345
+ }
346
+ const f = await serve();
347
+ const res = await f('/catch');
348
+ expect(await res.text()).to.equal('handled: over quota');
349
+ expect((await f('/catch/other')).status).to.equal(500);
350
+ expect(Catching).to.be.a('function');
351
+ });
352
+ });
@@ -5,7 +5,7 @@ import { Context, Response } from '@celljs/web/lib/node';
5
5
  import { Stream } from 'stream';
6
6
  import { FILE_VIEW_NAME } from '../annotation/file';
7
7
  import { ViewMetadata } from '../annotation/view';
8
- import { createReadStream } from 'fs-extra';
8
+ import { createReadStream } from 'node:fs';
9
9
  import { join } from 'path';
10
10
 
11
11
  @Component(View)
@@ -59,7 +59,10 @@ export class FileView implements View {
59
59
 
60
60
  protected async handleError(response: Response, reason: string | Error, status: number = HttpStatus.INTERNAL_SERVER_ERROR): Promise<void> {
61
61
  this.logger.error(reason);
62
- response.status(status).send('Unable to download file.').end();
62
+ if (!response.headersSent) {
63
+ response.statusCode = status;
64
+ }
65
+ response.end('Unable to download file.');
63
66
  }
64
67
 
65
68
  support({ viewName }: ViewMetadata): Promise<boolean> {
@@ -1,13 +1,14 @@
1
1
  import { Component, Value } from '@celljs/core';
2
2
  import { View } from './view-protocol';
3
3
  import { Context } from '@celljs/web/lib/node';
4
- import Mustache from 'mustache';
5
4
  import { join } from 'path';
6
- import { readFile } from 'fs-extra';
5
+ import { readFile } from 'node:fs/promises';
7
6
  import { ViewMetadata } from '../annotation/view';
8
7
  import { HTML_VIEW_NAME } from '../annotation/html';
9
8
  import { MediaType } from '@celljs/http';
9
+ import { Template } from './template';
10
10
 
11
+ /** Renders `@Html('page.mustache')` with {@link Template}, from `cell.mustache.baseViewDir`. */
11
12
  @Component(View)
12
13
  export class HtmlView implements View {
13
14
 
@@ -16,16 +17,23 @@ export class HtmlView implements View {
16
17
  readonly priority = 500;
17
18
 
18
19
  @Value('cell.mustache')
19
- protected readonly options: any;
20
+ protected readonly options: { baseViewDir: string, cache?: boolean };
21
+
22
+ /** Compiled templates by file, when `cell.mustache.cache` is on. */
23
+ protected readonly templates = new Map<string, Template>();
20
24
 
21
25
  async render(model: any, { metadata }: ViewMetadata): Promise<void> {
22
26
  const response = Context.getCurrent().response;
23
27
  const { baseViewDir, cache } = this.options;
24
- const template = await readFile(join(__dirname, baseViewDir, metadata!.file), { encoding: 'utf8' });
25
- if (cache) {
26
- Mustache.parse(template);
28
+ const file = join(__dirname, baseViewDir, metadata!.file);
29
+ let template = this.templates.get(file);
30
+ if (!template) {
31
+ template = new Template(await readFile(file, { encoding: 'utf8' }));
32
+ if (cache) {
33
+ this.templates.set(file, template);
34
+ }
27
35
  }
28
- response.body = Mustache.render(template, model);
36
+ response.body = template.render(model);
29
37
  }
30
38
 
31
39
  support({ viewName, metadata }: ViewMetadata): Promise<boolean> {
@@ -2,5 +2,6 @@ export * from './json-view';
2
2
  export * from './text-view';
3
3
  export * from './view-provider';
4
4
  export * from './html-view';
5
+ export * from './template';
5
6
  export * from './file-view';
6
- export * from './json-view-template-renderer';
7
+ export * from './json-view-template-renderer';
@@ -0,0 +1,34 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { Template } from './template';
4
+
5
+ describe('Template', () => {
6
+ // What mustache 4.2.0 rendered.
7
+ const cases: [string, unknown, string][] = [
8
+ ['Hi {{name}}!', { name: '<b>&"\'/`=' }, 'Hi &lt;b&gt;&amp;&quot;&#39;&#x2F;&#x60;&#x3D;!'],
9
+ ['{{{raw}}}{{&raw}}', { raw: '<i>' }, '<i><i>'],
10
+ ['{{#list}}[{{.}}]{{/list}}', { list: [1, 2] }, '[1][2]'],
11
+ ['{{#user}}{{name}}{{/user}}{{^user}}none{{/user}}', { user: { name: 'u' } }, 'u'],
12
+ ['{{^items}}empty{{/items}}', { items: [] }, 'empty'],
13
+ ['{{a.b.c}}|{{missing}}|{{n}}', { a: { b: { c: 3 } }, n: 0 }, '3||0'],
14
+ ['<ul>\n {{#xs}}\n <li>{{name}}</li>\n {{/xs}}\n</ul>\n', { xs: [{ name: 'a' }, { name: 'b' }] }, '<ul>\n <li>a</li>\n <li>b</li>\n</ul>\n'],
15
+ ['{{! comment }}x{{#t}}y{{/t}}', { t: true }, 'xy'],
16
+ ['{{#o}}{{k}}-{{top}}{{/o}}', { o: { k: 1 }, top: 'T' }, '1-T'],
17
+ ['{{#f}}x{{/f}}', { f: false }, ''],
18
+ ['{{ name }}', { name: 'sp' }, 'sp'],
19
+ ['{{a.missing.deep}}', { a: {} }, ''],
20
+ ['{{#xs}}{{name}}{{/xs}}', { xs: [{ name: 'a' }, {}], name: 'outer' }, 'aouter'],
21
+ ['{{greet}}', { who: 'x', greet() { return `hi ${(this as { who: string }).who}`; } }, 'hi x']
22
+ ];
23
+ for (const [source, model, expected] of cases) {
24
+ it(`renders ${JSON.stringify(source)}`, () => {
25
+ expect(new Template(source).render(model)).to.equal(expected);
26
+ });
27
+ }
28
+
29
+ it('fails on templates it does not support or cannot read', () => {
30
+ for (const source of ['{{> header}}', '{{=<% %>=}}', '{{#a}}x', '{{/a}}', '{{#a}}{{/b}}', '{{name', '{{{raw}}']) {
31
+ expect(() => new Template(source), source).to.throw();
32
+ }
33
+ });
34
+ });
@@ -0,0 +1,170 @@
1
+ const ESCAPES: Record<string, string> = {
2
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#39;', '/': '&#x2F;', '`': '&#x60;', '=': '&#x3D;'
3
+ };
4
+
5
+ const UNSAFE = /[&<>"'`=/]/;
6
+
7
+ function escapeHtml(text: string): string {
8
+ return UNSAFE.test(text) ? text.replace(/[&<>"'`=/]/g, c => ESCAPES[c]) : text;
9
+ }
10
+
11
+ /** `path` is the name split at dots; empty for `.`. */
12
+ type Token =
13
+ | { type: 'text', value: string }
14
+ | { type: 'name' | '&', path: string[] }
15
+ | { type: '#' | '^', path: string[], children: Token[] };
16
+
17
+ function toPath(name: string): string[] {
18
+ return name === '.' ? [] : name.split('.');
19
+ }
20
+
21
+ /** Section, inverted section, end of section and comment tags alone on a line take the line with them. */
22
+ const STANDALONE = new Set(['#', '^', '/', '!']);
23
+
24
+ /**
25
+ * A logic-less template with the syntax of Mustache (the subset Cell supports):
26
+ *
27
+ * - `{{name}}` writes a value HTML-escaped, `{{{name}}}` and `{{& name}}` as it is; `name` can be a path (`user.name`)
28
+ * or `.` for the current item; a missing value writes nothing;
29
+ * - `{{#name}}...{{/name}}` repeats for each item of a list, enters an object, or shows when the value is truthy;
30
+ * - `{{^name}}...{{/name}}` shows when the value is falsy or an empty list;
31
+ * - `{{! comment }}` writes nothing.
32
+ *
33
+ * Partials (`{{> name}}`) and other delimiters (`{{=<% %>=}}`) are not supported and fail when the template is compiled.
34
+ */
35
+ export class Template {
36
+
37
+ protected readonly tokens: Token[];
38
+
39
+ constructor(protected readonly source: string) {
40
+ this.tokens = this.parse(source);
41
+ }
42
+
43
+ render(model: unknown): string {
44
+ return this.renderTokens(this.tokens, [model]);
45
+ }
46
+
47
+ protected parse(source: string): Token[] {
48
+ const root: Token[] = [];
49
+ const stack: { name: string, children: Token[] }[] = [];
50
+ let current = root;
51
+ let i = 0;
52
+ while (i < source.length) {
53
+ const open = source.indexOf('{{', i);
54
+ if (open < 0) {
55
+ current.push({ type: 'text', value: source.slice(i) });
56
+ break;
57
+ }
58
+ let text = source.slice(i, open);
59
+ let type: string;
60
+ let name: string;
61
+ let end: number;
62
+ if (source[open + 2] === '{') {
63
+ const close = source.indexOf('}}}', open + 3);
64
+ if (close < 0) {
65
+ throw new Error(`Unclosed tag at ${open}`);
66
+ }
67
+ type = '&';
68
+ name = source.slice(open + 3, close).trim();
69
+ end = close + 3;
70
+ } else {
71
+ const close = source.indexOf('}}', open + 2);
72
+ if (close < 0) {
73
+ throw new Error(`Unclosed tag at ${open}`);
74
+ }
75
+ const content = source.slice(open + 2, close).trim();
76
+ type = '#^/!&>='.includes(content[0]) ? content[0] : 'name';
77
+ name = type === 'name' ? content : content.slice(1).trim();
78
+ end = close + 2;
79
+ }
80
+ if (type === '>' || type === '=') {
81
+ throw new Error(`${type === '>' ? 'Partials' : 'Custom delimiters'} are not supported: ${source.slice(open, end)}`);
82
+ }
83
+ if (STANDALONE.has(type)) {
84
+ const lineStart = source.lastIndexOf('\n', open - 1) + 1;
85
+ const lineEnd = source.indexOf('\n', end);
86
+ const before = source.slice(Math.max(lineStart, i), open);
87
+ const after = source.slice(end, lineEnd < 0 ? source.length : lineEnd);
88
+ if (lineStart >= i && /^[ \t]*$/.test(before) && /^[ \t]*\r?$/.test(after)) {
89
+ text = text.slice(0, text.length - before.length);
90
+ end = lineEnd < 0 ? source.length : lineEnd + 1;
91
+ }
92
+ }
93
+ if (text) {
94
+ current.push({ type: 'text', value: text });
95
+ }
96
+ if (type === '#' || type === '^') {
97
+ const section: Token = { type, path: toPath(name), children: [] };
98
+ current.push(section);
99
+ stack.push({ name, children: current });
100
+ current = section.children;
101
+ } else if (type === '/') {
102
+ const section = stack.pop();
103
+ if (!section || section.name !== name) {
104
+ throw new Error(`Unopened section "${name}" at ${open}`);
105
+ }
106
+ current = section.children;
107
+ } else if (type !== '!') {
108
+ current.push({ type: type as 'name' | '&', path: toPath(name) });
109
+ }
110
+ i = end;
111
+ }
112
+ if (stack.length) {
113
+ throw new Error(`Unclosed section "${stack[stack.length - 1].name}"`);
114
+ }
115
+ return root;
116
+ }
117
+
118
+ protected lookup(path: string[], contexts: unknown[]): unknown {
119
+ if (path.length === 0) {
120
+ return contexts[contexts.length - 1];
121
+ }
122
+ const first = path[0];
123
+ for (let i = contexts.length - 1; i >= 0; i--) {
124
+ const context = contexts[i];
125
+ if (context !== null && typeof context === 'object' && first in context) {
126
+ let value = (context as Record<string, unknown>)[first];
127
+ for (let j = 1; j < path.length; j++) {
128
+ value = value === null || value === undefined ? undefined : (value as Record<string, unknown>)[path[j]];
129
+ }
130
+ return typeof value === 'function' ? value.call(context) : value;
131
+ }
132
+ }
133
+ return undefined;
134
+ }
135
+
136
+ protected renderTokens(tokens: Token[], contexts: unknown[]): string {
137
+ let out = '';
138
+ for (const token of tokens) {
139
+ if (token.type === 'text') {
140
+ out += token.value;
141
+ continue;
142
+ }
143
+ const value = this.lookup(token.path, contexts);
144
+ if (token.type === '#') {
145
+ if (Array.isArray(value)) {
146
+ for (const item of value) {
147
+ contexts.push(item);
148
+ out += this.renderTokens(token.children, contexts);
149
+ contexts.pop();
150
+ }
151
+ } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
152
+ if (value) {
153
+ contexts.push(value);
154
+ out += this.renderTokens(token.children, contexts);
155
+ contexts.pop();
156
+ }
157
+ } else if (value) {
158
+ out += this.renderTokens(token.children, contexts);
159
+ }
160
+ } else if (token.type === '^') {
161
+ if (!value || (Array.isArray(value) && value.length === 0)) {
162
+ out += this.renderTokens(token.children, contexts);
163
+ }
164
+ } else if (value !== null && value !== undefined) {
165
+ out += token.type === '&' ? String(value) : escapeHtml(String(value));
166
+ }
167
+ }
168
+ return out;
169
+ }
170
+ }