bajo-template 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ardhi Lukianto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # bajo-template
package/bajo/.alias ADDED
@@ -0,0 +1 @@
1
+ tpl
@@ -0,0 +1,9 @@
1
+ {
2
+ "layout": {
3
+ "fallback": true
4
+ },
5
+ "loopDetectorDur": "1m",
6
+ "cache": {
7
+ "maxAgeDur": "1s"
8
+ }
9
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "loopDetected%s": "Loop detected: %s (%s)"
3
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "loopDetected%s": "Loop detected: %s (%s)"
3
+ }
@@ -0,0 +1,50 @@
1
+ import crypto from 'crypto'
2
+
3
+ export function buildCompileImports (lang) {
4
+ const _ = this.app.bajo.lib._
5
+ return {
6
+ _,
7
+ _t: (text, ...args) => {
8
+ const params = [...args, { lang }]
9
+ return this.print.write(text, ...params)
10
+ },
11
+ _format: (val, type, opts = {}) => {
12
+ opts.lang = opts.lang ?? lang
13
+ return this.app.bajo.format(val, type, opts)
14
+ },
15
+ _routePath: (input) => {
16
+ if (!this.app.waibu) return input
17
+ return this.app.waibu.routePath(input)
18
+ },
19
+ _titleize: this.app.bajo.titleize,
20
+ _hasPlugin: name => this.app.bajo.pluginNames.includes(name),
21
+ _jsonStringify: this.app.waibuMpa.jsonStringify,
22
+ _parseMarkdown: content => {
23
+ if (!this.app.bajoMarkdown) return content
24
+ return this.app.bajoMarkdown.parseContent(content)
25
+ }
26
+ }
27
+ }
28
+
29
+ async function compile (content, locals, { lang, ttl = 0 } = {}) {
30
+ locals.attr = locals.attr ?? {}
31
+ const _ = this.app.bajo.lib._
32
+ const { template } = _
33
+ const cache = this.app.bajoCache
34
+ const canCache = this.config.cache !== false && cache && this.app.bajo.config.env !== 'dev'
35
+ const opts = {
36
+ imports: buildCompileImports.call(this, lang)
37
+ }
38
+
39
+ let item
40
+ if (canCache) {
41
+ const key = 'fn:' + crypto.createHash('md5').update(content).digest('hex')
42
+ const value = template(content, opts)
43
+ item = await cache.sync({ key, value, ttl })
44
+ } else {
45
+ item = template(content, opts)
46
+ }
47
+ return item(locals)
48
+ }
49
+
50
+ export default compile
@@ -0,0 +1,12 @@
1
+ const subNses = ['layout', 'template', 'partial']
2
+
3
+ function getResource (name) {
4
+ const { ns, path, subNs, subSubNs, qs } = this.app.bajo.breakNsPath(name)
5
+ const plugin = this.app.bajo.getPlugin(ns)
6
+ const dir = `${plugin.dir.pkg}/bajoTemplate`
7
+ if (!subNses.includes(subNs)) throw this.error('unknownResource%s', name)
8
+ const fullPath = subSubNs ? `${dir}/${subSubNs}/${subNs}${path}` : `${dir}/${subNs}${path}`
9
+ return { ns, subNs, subSubNs, path, qs, fullPath }
10
+ }
11
+
12
+ export default getResource
@@ -0,0 +1,18 @@
1
+ async function parseFrontMatter (input = '', lang) {
2
+ const { isEmpty, isPlainObject, isArray, filter, map } = this.app.bajo.lib._
3
+ const { parseObject } = this.app.bajo
4
+ const handlers = map(filter(this.app.bajo.configHandlers, h => !['.js'].includes(h.ext)), h => h.readHandler)
5
+ let success
6
+ for (const handler of handlers) {
7
+ if (success) break
8
+ try {
9
+ const result = await handler(input, true)
10
+ if (isPlainObject(result) || isArray(result)) success = result
11
+ } catch (err) {
12
+ }
13
+ }
14
+ if (isEmpty(success)) return {}
15
+ return parseObject(success, { parseValue: true, lang }) ?? {}
16
+ }
17
+
18
+ export default parseFrontMatter
@@ -0,0 +1,80 @@
1
+ import path from 'path'
2
+ import { buildCompileImports } from './compile.js'
3
+
4
+ async function handleInclude (content, locals, opts) {
5
+ const { isEmpty, omit, template, merge } = this.app.bajo.lib._
6
+ const { extractText, breakNsPath } = this.app.bajo
7
+ const start = '<!-- include '
8
+ const end = ' -->'
9
+ const imports = buildCompileImports.call(this, opts.lang)
10
+ while (content.includes(start) && content.includes(end)) {
11
+ const { pattern, result: rsc } = extractText(content, start, end)
12
+ if (!isEmpty(rsc)) {
13
+ let attr = {}
14
+ let [resource, sattr] = rsc.split('|')
15
+ if (!isEmpty(sattr)) {
16
+ try {
17
+ attr = JSON.parse(sattr)
18
+ } catch (err) {}
19
+ }
20
+ const fn = template(resource, { imports })
21
+ resource = fn(locals)
22
+ const { subNs } = breakNsPath(resource)
23
+ let result = ''
24
+ if (subNs === 'partial') {
25
+ const { req, reply } = opts
26
+ const nopts = omit(opts, ['req', 'reply', 'postProcessor'])
27
+ nopts.partial = true
28
+ nopts.req = req
29
+ nopts.reply = reply
30
+ const nlocals = merge({}, locals, attr)
31
+ result = await this.render(resource, nlocals, nopts)
32
+ }
33
+ content = content.replace(pattern, result)
34
+ }
35
+ }
36
+ return content
37
+ }
38
+
39
+ export async function _renderString (input, locals = {}, opts = {}) {
40
+ const { merge, without, isString } = this.app.bajo.lib._
41
+ let { content, frontMatter } = this.splitContent(input)
42
+ let layout
43
+ if (!opts.partial) {
44
+ const pageFm = await this.parseFrontMatter(frontMatter, opts.lang)
45
+ locals.page = merge(locals.page, pageFm)
46
+ layout = locals.page.layout ?? opts.layout ?? (locals.page.ns ? `${locals.page.ns}.layout:/default.html` : 'main.layout:/default.html')
47
+ const ext = path.extname(layout)
48
+ const { file } = this.resolveLayout(layout, opts)
49
+ let { content: layoutContent, frontMatter: layoutFm } = this.splitContent(file, true)
50
+ layoutFm = await this.parseFrontMatter(layoutFm, opts.lang)
51
+ const keys = without(Object.keys(layoutFm), 'css', 'scripts')
52
+ if (['.html'].includes(ext)) {
53
+ for (const item of ['css', 'scripts']) {
54
+ locals.page[item] = locals.page[item] ?? []
55
+ if (isString(locals.page[item])) locals.page[item] = [locals.page[item]]
56
+ layoutFm[item] = layoutFm[item] ?? []
57
+ if (isString(layoutFm[item])) layoutFm[item] = [layoutFm[item]]
58
+ locals.page[item].unshift(...layoutFm[item])
59
+ }
60
+ }
61
+ for (const key of keys) {
62
+ locals.page[key] = locals.page[key] ?? layoutFm[key]
63
+ }
64
+ if (layoutFm.title && !locals.page.title) locals.page.title = layoutFm.title
65
+ content = layoutContent.replace('<!-- body -->', content)
66
+ const appTitle = this.print.write(locals.page.appTitle, { lang: opts.lang })
67
+ const fullTitle = locals.page.title ? `${locals.page.title} - ${appTitle}` : appTitle
68
+ locals.page.fullTitle = locals.fullTitle ?? fullTitle
69
+ }
70
+ content = await handleInclude.call(this, content, locals, opts)
71
+ return await this.compile(content, locals, { lang: opts.lang, ttl: this.config.cache.maxAgeDur })
72
+ }
73
+
74
+ async function renderString (content, locals = {}, opts = {}) {
75
+ let text = await _renderString.call(this, content, locals, opts)
76
+ if (opts.postProcessor) text = await opts.postProcessor({ text, locals, opts })
77
+ return text
78
+ }
79
+
80
+ export default renderString
@@ -0,0 +1,74 @@
1
+ import crypto from 'crypto'
2
+ import { _renderString } from './render-string.js'
3
+
4
+ let loopDetector = {}
5
+
6
+ function _clearLoopDetector () {
7
+ const { omit } = this.app.bajo.lib._
8
+ const now = Date.now()
9
+ const omitted = []
10
+ for (const groupId in loopDetector) {
11
+ const history = loopDetector[groupId]
12
+ if ((history.ts + this.config.loopDetectorDur) < now) omitted.push(groupId)
13
+ }
14
+ loopDetector = omit(loopDetector, omitted)
15
+ }
16
+
17
+ function _detectLoop (tpl, file, opts) {
18
+ const { last } = this.app.bajo.lib._
19
+ if (opts.groupId) {
20
+ if (loopDetector[opts.groupId]) {
21
+ if (last(loopDetector[opts.groupId].file) === file) throw this.plugin.error('loopDetected%s%s', tpl, file)
22
+ loopDetector[opts.groupId].file.push(file)
23
+ } else {
24
+ loopDetector[opts.groupId] = {
25
+ ts: Date.now(),
26
+ file: [file]
27
+ }
28
+ }
29
+ }
30
+ }
31
+
32
+ async function _render (tpl, locals = {}, opts = {}) {
33
+ _clearLoopDetector.call(this)
34
+ const { trim, isEmpty } = this.app.bajo.lib._
35
+ const { fs } = this.app.bajo.lib
36
+ const { breakNsPath } = this.app.bajo
37
+
38
+ const { subNs } = breakNsPath(tpl)
39
+ let resp
40
+ if (subNs === 'template') {
41
+ resp = this.resolveTemplate(tpl, opts)
42
+ } else if (subNs === 'partial') {
43
+ resp = this.resolvePartial(tpl, opts)
44
+ }
45
+ const { file } = resp
46
+ _detectLoop.call(this, tpl, file, opts)
47
+ let content = trim(fs.readFileSync(file, 'utf8'))
48
+ if (isEmpty(content) && subNs === 'template') {
49
+ content = '<!-- include ' + tpl.replace('.template', '.partial') + ' -->'
50
+ }
51
+ opts.partial = opts.partial ?? subNs === 'partial'
52
+ return await _renderString.call(this, content, locals, opts)
53
+ }
54
+
55
+ async function render (tpl, locals = {}, opts = {}) {
56
+ const { runHook, breakNsPath } = this.app.bajo
57
+ const { upperFirst } = this.app.bajo.lib._
58
+ const cache = this.app.bajoCache
59
+ const key = crypto.createHash('md5').update(`${tpl}:${JSON.stringify(locals)}`).digest('hex')
60
+ const { subNs } = breakNsPath(tpl)
61
+ const canCache = subNs === 'template' && this.config.cache !== false && cache && this.app.bajo.config.env !== 'dev'
62
+ if (canCache) {
63
+ const item = await cache.get({ key })
64
+ if (item) return item
65
+ }
66
+ await runHook(`${this.name}:beforeRender${upperFirst(subNs)}`, { tpl, locals, opts })
67
+ let text = await _render.call(this, tpl, locals, opts)
68
+ if (opts.postProcessor) text = await opts.postProcessor({ text, locals, opts })
69
+ await runHook(`${this.name}:afterRender${upperFirst(subNs)}`, { tpl, locals, opts, text })
70
+ if (canCache) await cache.set({ key, value: text, ttl: this.config.cache.maxAgeDur })
71
+ return text
72
+ }
73
+
74
+ export default render
@@ -0,0 +1,34 @@
1
+ import resolveResource, { filecheck } from '../../lib/resolve-resource.js'
2
+
3
+ function fallbackHandler ({ file, exts, ns, subSubNs, type, theme }) {
4
+ const dir = ''
5
+ const base = 'default'
6
+ if (!this.config.layout.fallback) return false
7
+ // check main: theme specific
8
+ if (theme && !file) {
9
+ const check = `${this.app.main.dir.pkg}/${this.name}/${type}/_${theme}`
10
+ file = filecheck.call(this, { dir, base, exts, check })
11
+ }
12
+ // check mail: common
13
+ if (!file) {
14
+ const check = `${this.app.main.dir.pkg}/${this.name}/${type}`
15
+ file = filecheck.call(this, { dir, base, exts, check })
16
+ }
17
+ // check fallback: common
18
+ if (!file) {
19
+ const check = `${this.app[ns].dir.pkg}/${this.name}/${subSubNs ? (subSubNs + '/') : ''}${type}`
20
+ file = filecheck.call(this, { dir, base, exts, check })
21
+ }
22
+ // check general fallback
23
+ if (!file) {
24
+ const check = `${this.dir.pkg}/${this.name}/${subSubNs ? (subSubNs + '/') : ''}${type}`
25
+ file = filecheck.call(this, { dir, base, exts, check })
26
+ }
27
+ return file
28
+ }
29
+
30
+ function resolveLayout (item = '', opts = {}) {
31
+ return resolveResource.call(this, 'layout', item, opts, fallbackHandler)
32
+ }
33
+
34
+ export default resolveLayout
@@ -0,0 +1,7 @@
1
+ import resolveResource from '../../lib/resolve-resource.js'
2
+
3
+ function resolveTemplate (item = '', opts = {}) {
4
+ return resolveResource.call(this, 'partial', item, opts)
5
+ }
6
+
7
+ export default resolveTemplate
@@ -0,0 +1,7 @@
1
+ import resolveResource from '../../lib/resolve-resource.js'
2
+
3
+ function resolveTemplate (item = '', opts = {}) {
4
+ return resolveResource.call(this, 'template', item, opts)
5
+ }
6
+
7
+ export default resolveTemplate
@@ -0,0 +1,23 @@
1
+ const start = '---\n'
2
+ const end = '\n---'
3
+
4
+ function splitContent (input, readFile) {
5
+ const { fs } = this.app.bajo.lib
6
+ let content = readFile ? fs.readFileSync(input, 'utf8') : input
7
+ let text = content.replaceAll('\r\n', '\n')
8
+ const open = text.indexOf(start)
9
+ let frontMatter
10
+ if (open > -1) {
11
+ text = text.slice(open + start.length)
12
+ const close = text.indexOf(end)
13
+ if (close > -1) {
14
+ frontMatter = text.slice(0, close)
15
+ content = text.slice(close + end.length)
16
+ }
17
+ }
18
+ frontMatter = frontMatter ?? {}
19
+ content = content ?? ''
20
+ return { frontMatter, content }
21
+ }
22
+
23
+ export default splitContent
@@ -0,0 +1,5 @@
1
+ <c:page-start>
2
+ <title><%= page.title %></title>
3
+ </c:page-start>
4
+ <!-- body -->
5
+ <c:page-end />
@@ -0,0 +1,18 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title><%= page.fullTitle %></title>
6
+ <style type="text/css">
7
+ </style>
8
+ </head>
9
+ <body>
10
+ <% if (arguments[0].firstName && arguments[0].lastName) { %>
11
+ <p>Dear <%= firstName %> <%= lastName %>,</p>
12
+ <% } %>
13
+ <!-- body -->
14
+ <p>Sincerely,</p>
15
+
16
+ <p><%= _meta.site.title %></p>
17
+ </body>
18
+ </html>
@@ -0,0 +1,18 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title><%= page.fullTitle %></title>
6
+ <style type="text/css">
7
+ </style>
8
+ </head>
9
+ <body>
10
+ <% if (arguments[0].firstName && arguments[0].lastName) { %>
11
+ <p>Yth <%= firstName %> <%= lastName %>,</p>
12
+ <% } %>
13
+ <!-- body -->
14
+ <p>Hormat kami,</p>
15
+
16
+ <p><%= _meta.site.title %></p>
17
+ </body>
18
+ </html>
@@ -0,0 +1,72 @@
1
+ import _path from 'path'
2
+ const cache = {}
3
+
4
+ export function filecheck ({ check, dir, base, exts }) {
5
+ const { fs } = this.app.bajo.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
+ function resolveResource (type, item = '', opts = {}, fallbackHandler) {
19
+ const { getPluginDataDir } = this.app.bajo
20
+ const { trim, uniq } = this.app.bajo.lib._
21
+ const env = this.app.bajo.config.env
22
+ if (env !== 'dev' && cache[item]) return cache[item]
23
+
24
+ let { ns, subSubNs, path } = this.getResource(item)
25
+ const ext = _path.extname(path)
26
+ path = trim(path, '/')
27
+ const dir = _path.dirname(path)
28
+ const base = _path.basename(path, ext)
29
+ const fallbackLang = this.app.bajo.config.intl.fallback
30
+ const exts = uniq([`.${fallbackLang}${ext}`, ext])
31
+ if (opts.lang) exts.unshift(`.${opts.lang}${ext}`)
32
+
33
+ const extension = subSubNs ? `extend/${subSubNs}/` : ''
34
+ let file
35
+ // check override: theme specific
36
+ if (opts.theme) {
37
+ const check = `${getPluginDataDir(ns)}/${this.name}/${extension}${type}/_${opts.theme}`
38
+ file = filecheck.call(this, { dir, base, exts, check })
39
+ }
40
+ // check override: common
41
+ if (!file) {
42
+ const check = `${getPluginDataDir(ns)}/${this.name}/${extension}${type}`
43
+ file = filecheck.call(this, { dir, base, exts, check })
44
+ }
45
+ // check main override: theme specific
46
+ if (opts.theme && !file) {
47
+ const check = `${this.app.main.dir.pkg}/${this.name}/extend/${ns}/${type}/_${opts.theme}`
48
+ file = filecheck.call(this, { dir, base, exts, check })
49
+ }
50
+ // check main override: common
51
+ if (!file) {
52
+ const check = `${this.app.main.dir.pkg}/${this.name}/extend/${ns}/${type}`
53
+ file = filecheck.call(this, { dir, base, exts, check })
54
+ }
55
+ // check real: theme specific
56
+ if (opts.theme && !file) {
57
+ const check = `${this.app[ns].dir.pkg}/${this.name}/${extension}${type}/_${opts.theme}`
58
+ file = filecheck.call(this, { dir, base, exts, check })
59
+ }
60
+ // check real: common
61
+ if (!file) {
62
+ const check = `${this.app[ns].dir.pkg}/${this.name}/${extension}${type}`
63
+ file = filecheck.call(this, { dir, base, exts, check })
64
+ }
65
+ if (fallbackHandler) file = fallbackHandler.call(this, { file, dir, base, exts, ns, subSubNs, type, theme: opts.theme })
66
+ if (!file) throw this.error('cantFind%s%s', type, item)
67
+ const result = { file, ns, layout: opts.layout }
68
+ if (env !== 'dev') cache[item] = result
69
+ return result
70
+ }
71
+
72
+ export default resolveResource
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "bajo-template",
3
+ "version": "1.0.0",
4
+ "description": "Template Renderer for Bajo Framework",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "type": "module",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/ardhi/bajo-template.git"
13
+ },
14
+ "keywords": [
15
+ "template",
16
+ "bajo",
17
+ "framework",
18
+ "modular"
19
+ ],
20
+ "author": "Ardhi Lukianto <ardhi@lukianto.com>",
21
+ "license": "MIT",
22
+ "bugs": {
23
+ "url": "https://github.com/ardhi/bajo-template/issues"
24
+ },
25
+ "homepage": "https://github.com/ardhi/bajo-template#readme"
26
+ }