bajo-template 2.8.0 → 2.9.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,275 @@
1
+ /* global describe, it, beforeEach */
2
+
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { expect } from 'chai'
7
+
8
+ import factory from '../index.js'
9
+
10
+ const createTempRoot = () => fs.mkdtempSync(path.join(os.tmpdir(), 'bajo-template-test-'))
11
+
12
+ describe('BajoTemplate', () => {
13
+ let app
14
+ let BajoTemplate
15
+
16
+ beforeEach(async () => {
17
+ const lodashLike = {
18
+ get: (obj, p, defValue) => {
19
+ const parts = p.split('.')
20
+ let cur = obj
21
+ for (const part of parts) {
22
+ if (cur == null || !(part in cur)) return defValue
23
+ cur = cur[part]
24
+ }
25
+ return cur
26
+ },
27
+ omit: (obj, keys) => Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k))),
28
+ last: (arr) => arr[arr.length - 1],
29
+ isEmpty: (val) => {
30
+ if (val == null) return true
31
+ if (Array.isArray(val) || typeof val === 'string') return val.length === 0
32
+ if (typeof val === 'object') return Object.keys(val).length === 0
33
+ return false
34
+ },
35
+ isPlainObject: (val) => Object.prototype.toString.call(val) === '[object Object]',
36
+ isArray: Array.isArray,
37
+ filter: (arr, fn) => arr.filter(fn),
38
+ map: (arr, fn) => arr.map(fn),
39
+ template: (content) => {
40
+ return (locals) => `compiled:${content}:${locals.name ?? ''}`
41
+ }
42
+ }
43
+
44
+ app = {
45
+ lib: {
46
+ fs,
47
+ _: lodashLike,
48
+ aneka: {
49
+ titleize: (text) => text.split(' ').map(w => w[0].toUpperCase() + w.slice(1)).join(' ')
50
+ },
51
+ parseObject: (obj, opts) => ({ obj, opts })
52
+ },
53
+ baseClass: {
54
+ Base: class Base {
55
+ constructor (pkgName, appRef) {
56
+ this.pkgName = pkgName
57
+ this.app = appRef
58
+ this.ns = 'bajoTemplate'
59
+ }
60
+
61
+ t (text, ...params) {
62
+ return `${text}:${params.length}`
63
+ }
64
+
65
+ error (msg, ...params) {
66
+ return new Error([msg, ...params].join('|'))
67
+ }
68
+ }
69
+ },
70
+ bajo: {
71
+ format: (val, type, opts) => `${type}:${val}:${opts.lang}`,
72
+ breakNsPath: (key) => ({ path: key.split(':')[1] ?? '' }),
73
+ config: {
74
+ intl: { fallback: 'en' },
75
+ env: 'dev'
76
+ }
77
+ },
78
+ getAllNs: () => ['bajoTemplate', 'waibuMpa'],
79
+ waibu: {
80
+ getSetting: (key, { defValue }) => `setting:${key}:${defValue}`
81
+ },
82
+ waibuMpa: {
83
+ jsonStringify: (v) => JSON.stringify(v)
84
+ },
85
+ configHandlers: []
86
+ }
87
+
88
+ BajoTemplate = await factory.call({ app }, 'bajo-template')
89
+ })
90
+
91
+ it('initializes default configuration', () => {
92
+ const tpl = new BajoTemplate()
93
+
94
+ expect(tpl.config.layout.fallback).to.equal(true)
95
+ expect(tpl.config.loopDetectorDur).to.equal('1m')
96
+ expect(tpl.config.cache.ttlDur).to.equal('1s')
97
+ expect(tpl.loopDetector).to.deep.equal({})
98
+ })
99
+
100
+ it('buildCompileImports exposes utility functions', () => {
101
+ const tpl = new BajoTemplate()
102
+ const locals = { schema: { view: { site: { title: 'Local title' } } } }
103
+ const req = { lang: 'id' }
104
+
105
+ const imports = tpl.buildCompileImports(locals, req)
106
+
107
+ expect(imports._titleize('hello world')).to.equal('Hello World')
108
+ expect(imports._hasPlugin('waibuMpa')).to.equal(true)
109
+ expect(imports._jsonStringify({ a: 1 })).to.equal('{"a":1}')
110
+ expect(imports._format(7, 'number')).to.equal('number:7:id')
111
+ expect(imports._getSetting('main:/site/title', 'Default')).to.equal('Local title')
112
+ })
113
+
114
+ it('buildCompileImports _excerpt delegates to getExcerpt', () => {
115
+ const tpl = new BajoTemplate()
116
+ const imports = tpl.buildCompileImports({}, { lang: 'en' })
117
+
118
+ expect(imports._excerpt('one two three four', 2)).to.equal('one two...')
119
+ })
120
+
121
+ it('clearLoopDetector removes expired entries only', () => {
122
+ const tpl = new BajoTemplate()
123
+ tpl.config.loopDetectorDur = 100
124
+ tpl.loopDetector = {
125
+ old: { ts: Date.now() - 1000, file: ['a'] },
126
+ fresh: { ts: Date.now(), file: ['b'] }
127
+ }
128
+
129
+ tpl._clearLoopDetector()
130
+
131
+ expect(Object.keys(tpl.loopDetector)).to.deep.equal(['fresh'])
132
+ })
133
+
134
+ it('detectLoop records history and throws on repeated same file', () => {
135
+ const tpl = new BajoTemplate()
136
+ const opts = { groupId: 'g1' }
137
+ const file = '/tmp/view.html'
138
+
139
+ tpl._detectLoop('x.template:/view.html', file, opts)
140
+ expect(tpl.loopDetector.g1.file).to.deep.equal([file])
141
+
142
+ expect(() => tpl._detectLoop('x.template:/view.html', file, opts)).to.throw('loopDetected')
143
+ })
144
+
145
+ it('detectLoop allows repeated file when basename starts with tilde', () => {
146
+ const tpl = new BajoTemplate()
147
+ const opts = { groupId: 'g2' }
148
+ const file = '/tmp/~view.html'
149
+
150
+ tpl._detectLoop('x.template:/~view.html', file, opts)
151
+ expect(() => tpl._detectLoop('x.template:/~view.html', file, opts)).to.not.throw()
152
+ })
153
+
154
+ it('splitContent parses front matter and body from text', () => {
155
+ const tpl = new BajoTemplate()
156
+ const input = '---\ntitle: Test\n---\nBody content'
157
+ const result = tpl.splitContent(input, false)
158
+
159
+ expect(result.frontMatter.trim()).to.equal('title: Test')
160
+ expect(result.content.trim()).to.equal('Body content')
161
+ })
162
+
163
+ it('splitContent reads file input when readFile is true', () => {
164
+ const tpl = new BajoTemplate()
165
+ const root = createTempRoot()
166
+ const file = path.join(root, 'sample.txt')
167
+ fs.writeFileSync(file, '---\nname: A\n---\nHello', 'utf8')
168
+
169
+ const result = tpl.splitContent(file, true)
170
+
171
+ expect(result.frontMatter.trim()).to.equal('name: A')
172
+ expect(result.content.trim()).to.equal('Hello')
173
+ fs.rmSync(root, { recursive: true, force: true })
174
+ })
175
+
176
+ it('getExcerpt and getTruncated return expected text', () => {
177
+ const tpl = new BajoTemplate()
178
+
179
+ expect(tpl.getExcerpt('one two three four', 2)).to.equal('one two...')
180
+ expect(tpl.getExcerpt('one two', 5)).to.equal('one two')
181
+ expect(tpl.getTruncated('abcdef', 3)).to.equal('abc...')
182
+ expect(tpl.getTruncated('abc', 10)).to.equal('abc')
183
+ expect(tpl.getExcerpt('one two three', 2, ' (more)')).to.equal('one two (more)')
184
+ })
185
+
186
+ it('parseFrontMatter tries handlers and parses first valid object/array', async () => {
187
+ const tpl = new BajoTemplate()
188
+ const calls = []
189
+ app.configHandlers = [
190
+ {
191
+ ext: '.js',
192
+ readHandler: async () => {
193
+ calls.push('.js')
194
+ return { ignored: true }
195
+ }
196
+ },
197
+ {
198
+ ext: '.yaml',
199
+ readHandler: async () => {
200
+ calls.push('.yaml')
201
+ throw new Error('bad')
202
+ }
203
+ },
204
+ {
205
+ ext: '.toml',
206
+ readHandler: async (input, parseValue) => {
207
+ calls.push([input, parseValue])
208
+ return { title: 'ok' }
209
+ }
210
+ }
211
+ ]
212
+
213
+ const out = await tpl.parseFrontMatter('title = "ok"', 'id')
214
+
215
+ expect(calls).to.deep.equal(['.yaml', ['title = "ok"', true]])
216
+ expect(out).to.deep.equal({ obj: { title: 'ok' }, opts: { parseValue: false, lang: 'id' } })
217
+ })
218
+
219
+ it('parseFrontMatter returns empty object when no handler succeeds', async () => {
220
+ const tpl = new BajoTemplate()
221
+ app.configHandlers = [
222
+ { ext: '.yaml', readHandler: async () => '' },
223
+ { ext: '.toml', readHandler: async () => null }
224
+ ]
225
+
226
+ const out = await tpl.parseFrontMatter('x', 'en')
227
+ expect(out).to.deep.equal({})
228
+ })
229
+
230
+ it('compile reads from cache when available', async () => {
231
+ const tpl = new BajoTemplate()
232
+ const cached = (locals) => `cached:${locals.name}`
233
+ let templateCalled = false
234
+
235
+ app.lib._.template = () => {
236
+ templateCalled = true
237
+ return () => 'should-not-run'
238
+ }
239
+ app.bajoCache = {
240
+ get: async () => cached,
241
+ set: async () => {}
242
+ }
243
+
244
+ const out = await tpl.compile('hello', { name: 'A' }, { ttl: 5 })
245
+ expect(out).to.equal('cached:A')
246
+ expect(templateCalled).to.equal(false)
247
+ })
248
+
249
+ it('compile writes cache when not available', async () => {
250
+ const tpl = new BajoTemplate()
251
+ const setCalls = []
252
+ app.bajoCache = {
253
+ get: async () => undefined,
254
+ set: async (payload) => setCalls.push(payload)
255
+ }
256
+
257
+ const out = await tpl.compile('hello', { name: 'B' }, { ttl: 123 })
258
+
259
+ expect(out).to.equal('compiled:hello:B')
260
+ expect(setCalls).to.have.lengthOf(1)
261
+ expect(setCalls[0].ttl).to.equal(123)
262
+ expect(setCalls[0].key.startsWith('fn:')).to.equal(true)
263
+ })
264
+
265
+ it('renderString applies optional postProcessor', async () => {
266
+ const tpl = new BajoTemplate()
267
+ tpl._renderString = async () => 'rendered'
268
+
269
+ const out = await tpl.renderString('x', {}, {
270
+ postProcessor: async ({ text }) => text + ':post'
271
+ })
272
+
273
+ expect(out).to.equal('rendered:post')
274
+ })
275
+ })
package/wiki/CHANGES.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changes
2
2
 
3
+ ## 2026-06-27
4
+
5
+ - [2.9.0] Add documentations
6
+ - [2.9.0] Add tests
7
+ - [2.9.0] Add ```resolveResource()```
8
+ - [2.9.0] Add ```_findFile()```
9
+ - [2.9.1] Bug fix in ```parseFrontMatter()```
10
+
3
11
  ## 2026-06-12
4
12
 
5
13
  - [2.8.0] Necessary updates to ```bajo@2.18.0``` specs
@@ -1,90 +0,0 @@
1
- import _path from 'path'
2
- const cache = {}
3
-
4
- export function filecheck ({ check, dir, base, exts }) {
5
- const { fs } = this.app.lib
6
- let file
7
- for (const ext of exts) {
8
- let path = `${check}/${dir}/${base}${ext}`
9
- if (['', '.'].includes(dir)) path = `${check}/${base}${ext}`
10
- if (fs.existsSync(path)) {
11
- file = path
12
- break
13
- }
14
- }
15
- return file
16
- }
17
-
18
- export function checking ({ type, ns, subSubNs, dir, base, exts, theme, req } = {}) {
19
- const extension = subSubNs ? `${subSubNs}/` : ''
20
- let file
21
- // check main override: domain specific
22
- if (this.app.waibu && req) {
23
- const hostname = this.app.waibu.getHostname(req)
24
- const check = `${this.app.main.dir.pkg}/extend/${this.ns}/${hostname}/${ns}/${extension}${type}`
25
- file = filecheck.call(this, { dir, base, exts, check })
26
- }
27
- // check main override: theme specific
28
- if (theme && !file) {
29
- const check = `${this.app.main.dir.pkg}/extend/${this.ns}/${theme.name}/${ns}/${extension}${type}`
30
- file = filecheck.call(this, { dir, base, exts, check })
31
- }
32
- // check main override: common
33
- if (!file) {
34
- const check = `${this.app.main.dir.pkg}/extend/${this.ns}/${ns}/${extension}${type}`
35
- file = filecheck.call(this, { dir, base, exts, check })
36
- }
37
- // check override: theme specific
38
- if (theme && !file) {
39
- const check = `${theme.plugin.dir.pkg}/extend/${this.ns}/${theme.name}/${ns}/${extension}${type}`
40
- file = filecheck.call(this, { dir, base, exts, check })
41
- }
42
- // check override: theme specific (common)
43
- if (theme && !file) {
44
- const check = `${theme.plugin.dir.pkg}/extend/${this.ns}/_common/${ns}/${extension}${type}`
45
- file = filecheck.call(this, { dir, base, exts, check })
46
- }
47
- // check real: theme specific
48
- if (theme && !file) {
49
- const check = `${this.app[ns].dir.pkg}/extend/${this.ns}/${theme.name}/${extension}${type}`
50
- file = filecheck.call(this, { dir, base, exts, check })
51
- }
52
- // check real: common
53
- if (!file) {
54
- const check = `${this.app[ns].dir.pkg}/extend/${this.ns}/${extension}${type}`
55
- file = filecheck.call(this, { dir, base, exts, check })
56
- }
57
- return file
58
- }
59
-
60
- function resolveResource (type, item = '', opts = {}, fallbackHandler) {
61
- const { trim, find, uniq } = this.app.lib._
62
- const { fs } = this.app.lib
63
- const env = this.app.bajo.config.env
64
- if (env !== 'dev' && cache[item]) return cache[item]
65
-
66
- let { ns, subSubNs, path } = this.getResource(item)
67
- const ext = _path.extname(path)
68
- path = trim(path, '/')
69
- const dir = _path.dirname(path)
70
- const base = _path.basename(path, ext)
71
- const fallbackLang = this.app.bajo.config.intl.fallback
72
- const exts = uniq([`.${fallbackLang}${ext}`, ext])
73
- if (opts.lang) exts.unshift(`.${opts.lang}${ext}`)
74
- let theme
75
- if (opts.theme && this.app.waibuMpa && opts.req) theme = find(this.app.waibuMpa.themes, { name: opts.theme })
76
- let file = checking.call(this, { type, ns, subSubNs, dir, base, exts, theme, req: opts.req })
77
- if (!file) {
78
- if (fallbackHandler) file = fallbackHandler.call(this, { dir, base, exts, ns, subSubNs, type, theme, req: opts.req })
79
- if (opts.default) {
80
- const fname = this.getResource(opts.default).fullPath
81
- if (fs.existsSync(fname)) file = fname
82
- }
83
- if (!file) throw this.error('cantFind%s%s', type, item)
84
- }
85
- const result = { file, ns, layout: opts.layout }
86
- if (env !== 'dev') cache[item] = result
87
- return result
88
- }
89
-
90
- export default resolveResource