bajo-template 1.1.0 → 1.1.2

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.
@@ -1,5 +1,3 @@
1
- <c:page-start>
2
- <title><%= page.title %></title>
3
- </c:page-start>
1
+ <c:page-start />
4
2
  <!-- body -->
5
3
  <c:page-end />
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bajo-template",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "Template Renderer for Bajo Framework",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -0,0 +1,312 @@
1
+ import resolveResource, { filecheck } from '../lib/resolve-resource.js'
2
+ import crypto from 'crypto'
3
+ import path from 'path'
4
+
5
+ async function factory (pkgName) {
6
+ const me = this
7
+
8
+ return class BajoTemplate extends this.lib.BajoPlugin {
9
+ constructor () {
10
+ super(pkgName, me.app)
11
+ this.alias = 'tpl'
12
+ this.config = {
13
+ layout: {
14
+ fallback: true
15
+ },
16
+ loopDetectorDur: '1m',
17
+ cache: {
18
+ maxAgeDur: '1s'
19
+ }
20
+ }
21
+ this.loopDetector = {}
22
+ }
23
+
24
+ buildCompileImports = (lang) => {
25
+ const _ = this.app.bajo.lib._
26
+ return {
27
+ _,
28
+ _t: (text, ...args) => {
29
+ const params = [...args, { lang }]
30
+ return this.print.write(text, ...params)
31
+ },
32
+ _format: (val, type, opts = {}) => {
33
+ opts.lang = opts.lang ?? lang
34
+ return this.app.bajo.format(val, type, opts)
35
+ },
36
+ _routePath: (input) => {
37
+ if (!this.app.waibu) return input
38
+ return this.app.waibu.routePath(input)
39
+ },
40
+ _titleize: this.app.bajo.titleize,
41
+ _hasPlugin: name => this.app.bajo.pluginNames.includes(name),
42
+ _jsonStringify: this.app.waibuMpa.jsonStringify,
43
+ _parseMarkdown: content => {
44
+ if (!this.app.bajoMarkdown) return content
45
+ return this.app.bajoMarkdown.parseContent(content)
46
+ }
47
+ }
48
+ }
49
+
50
+ _clearLoopDetector = () => {
51
+ const { omit } = this.app.bajo.lib._
52
+ const now = Date.now()
53
+ const omitted = []
54
+ for (const groupId in this.loopDetector) {
55
+ const history = this.loopDetector[groupId]
56
+ if ((history.ts + this.config.loopDetectorDur) < now) omitted.push(groupId)
57
+ }
58
+ this.loopDetector = omit(this.loopDetector, omitted)
59
+ }
60
+
61
+ _detectLoop = (tpl, file, opts) => {
62
+ const { last } = this.app.bajo.lib._
63
+ if (opts.groupId) {
64
+ if (this.loopDetector[opts.groupId]) {
65
+ if (last(this.loopDetector[opts.groupId].file) === file && path.basename(file)[0] !== '~') throw this.error('loopDetected%s%s', tpl, file)
66
+ this.loopDetector[opts.groupId].file.push(file)
67
+ } else {
68
+ this.loopDetector[opts.groupId] = {
69
+ ts: Date.now(),
70
+ file: [file]
71
+ }
72
+ }
73
+ }
74
+ }
75
+
76
+ _render = async (tpl, locals = {}, opts = {}) => {
77
+ this._clearLoopDetector()
78
+ const { trim, isEmpty } = this.app.bajo.lib._
79
+ const { fs } = this.app.bajo.lib
80
+ const { breakNsPath } = this.app.bajo
81
+
82
+ const { subNs } = breakNsPath(tpl)
83
+ let resp
84
+ if (subNs === 'template') {
85
+ resp = this.resolveTemplate(tpl, opts)
86
+ } else if (subNs === 'partial') {
87
+ resp = this.resolvePartial(tpl, opts)
88
+ }
89
+ if (!resp) throw this.error('resourceNotFound%s', tpl)
90
+ const { file } = resp
91
+ this._detectLoop(tpl, file, opts)
92
+ const fileContent = trim(fs.readFileSync(file, 'utf8'))
93
+ let { content, frontMatter } = this.splitContent(fileContent)
94
+ if (isEmpty(content) && (subNs === 'template')) content = '<!-- include ' + tpl.replace('.template', '.partial') + ' -->'
95
+ opts.ext = path.extname(file)
96
+ opts.frontMatter = frontMatter
97
+ opts.partial = opts.partial ?? subNs === 'partial'
98
+ return await this._renderString(content, locals, opts)
99
+ }
100
+
101
+ _handleInclude = async (content, locals = {}, opts = {}) => {
102
+ const { isEmpty, omit, template, merge } = this.app.bajo.lib._
103
+ const { extractText, breakNsPath } = this.app.bajo
104
+ const start = '<!-- include '
105
+ const end = ' -->'
106
+ const imports = this.buildCompileImports(opts.lang)
107
+ while (content.includes(start) && content.includes(end)) {
108
+ const { pattern, result: rsc } = extractText(content, start, end)
109
+ if (!isEmpty(rsc)) {
110
+ let attr = {}
111
+ let [resource, sattr] = rsc.split('|')
112
+ if (!isEmpty(sattr)) {
113
+ try {
114
+ attr = JSON.parse(sattr)
115
+ } catch (err) {}
116
+ }
117
+ const fn = template(resource, { imports })
118
+ resource = fn(locals)
119
+ const { subNs } = breakNsPath(resource)
120
+ let result = ''
121
+ if (subNs === 'partial') {
122
+ const { req, reply } = opts
123
+ const nopts = omit(opts, ['req', 'reply', 'postProcessor'])
124
+ nopts.partial = true
125
+ nopts.req = req
126
+ nopts.reply = reply
127
+ const nlocals = merge({}, locals, attr)
128
+ result = await this.render(resource, nlocals, nopts)
129
+ }
130
+ content = content.replace(pattern, result)
131
+ }
132
+ }
133
+ return content
134
+ }
135
+
136
+ _renderString = async (content, locals = {}, opts = {}) => {
137
+ const { merge, without, isString, omit } = this.app.bajo.lib._
138
+ if (opts.ext === '.md' && this.app.bajoMarkdown) {
139
+ content = await this.compile(content, locals, { lang: opts.lang, ttl: -1 }) // markdown can't process template tags, hence preprocess here
140
+ content = this.app.bajoMarkdown.parse(content)
141
+ }
142
+ let layout
143
+ if (!opts.partial) {
144
+ const pageFm = await this.parseFrontMatter(opts.frontMatter, opts.lang)
145
+ if (pageFm.layout) opts.layout = pageFm.layout
146
+ locals.page = merge(locals.page, omit(pageFm, ['layout']))
147
+ layout = opts.layout ?? (locals.page.ns ? `${locals.page.ns}.layout:/default.html` : 'main.layout:/default.html')
148
+ const ext = path.extname(layout)
149
+ const { file } = this.resolveLayout(layout, opts)
150
+ let { content: layoutContent, frontMatter: layoutFm } = this.splitContent(file, true)
151
+ layoutFm = await this.parseFrontMatter(layoutFm, opts.lang)
152
+ const keys = without(Object.keys(layoutFm), 'css', 'scripts')
153
+ if (['.html'].includes(ext)) {
154
+ for (const item of ['css', 'scripts']) {
155
+ locals.page[item] = locals.page[item] ?? []
156
+ if (isString(locals.page[item])) locals.page[item] = [locals.page[item]]
157
+ layoutFm[item] = layoutFm[item] ?? []
158
+ if (isString(layoutFm[item])) layoutFm[item] = [layoutFm[item]]
159
+ locals.page[item].unshift(...layoutFm[item])
160
+ }
161
+ }
162
+ for (const key of keys) {
163
+ locals.page[key] = locals.page[key] ?? layoutFm[key]
164
+ }
165
+ if (layoutFm.title && !locals.page.title) locals.page.title = layoutFm.title
166
+ content = layoutContent.replace('<!-- body -->', content)
167
+ const appTitle = this.print.write(locals.page.appTitle, { lang: opts.lang })
168
+ const fullTitle = locals.page.title ? `${locals.page.title} - ${appTitle}` : appTitle
169
+ locals.page.fullTitle = locals.fullTitle ?? fullTitle
170
+ }
171
+ content = await this.compile(content, locals, { lang: opts.lang, ttl: this.config.cache.maxAgeDur })
172
+ return await this._handleInclude(content, locals, opts)
173
+ }
174
+
175
+ getResource = (name) => {
176
+ const subNses = ['layout', 'template', 'partial']
177
+ const { ns, path, subNs, subSubNs, qs } = this.app.bajo.breakNsPath(name)
178
+ const plugin = this.app.bajo.getPlugin(ns)
179
+ const dir = `${plugin.dir.pkg}/bajoTemplate`
180
+ if (!subNses.includes(subNs)) throw this.error('unknownResource%s', name)
181
+ const fullPath = subSubNs ? `${dir}/${subSubNs}/${subNs}${path}` : `${dir}/${subNs}${path}`
182
+ return { ns, subNs, subSubNs, path, qs, fullPath }
183
+ }
184
+
185
+ parseFrontMatter = async (input = '', lang) => {
186
+ const { isEmpty, isPlainObject, isArray, filter, map } = this.app.bajo.lib._
187
+ const { parseObject } = this.app.bajo
188
+ const handlers = map(filter(this.app.bajo.configHandlers, h => !['.js'].includes(h.ext)), h => h.readHandler)
189
+ let success
190
+ for (const handler of handlers) {
191
+ if (success) break
192
+ try {
193
+ const result = await handler(input, true)
194
+ if (isPlainObject(result) || isArray(result)) success = result
195
+ } catch (err) {
196
+ }
197
+ }
198
+ if (isEmpty(success)) return {}
199
+ return parseObject(success, { parseValue: true, lang }) ?? {}
200
+ }
201
+
202
+ compile = async (content, locals, { lang, ttl = 0 } = {}) => {
203
+ locals.attr = locals.attr ?? {}
204
+ const _ = this.app.bajo.lib._
205
+ const { template } = _
206
+ const cache = this.app.bajoCache
207
+ let canCache = this.config.cache !== false && cache && this.app.bajo.config.env !== 'dev'
208
+ if (ttl === -1) canCache = false
209
+ const opts = {
210
+ imports: this.buildCompileImports(lang)
211
+ }
212
+
213
+ let item
214
+ if (canCache) {
215
+ const key = 'fn:' + crypto.createHash('md5').update(content).digest('hex')
216
+ const value = template(content, opts)
217
+ item = await cache.sync({ key, value, ttl })
218
+ } else {
219
+ item = template(content, opts)
220
+ }
221
+ return item(locals)
222
+ }
223
+
224
+ renderString = async (content, locals = {}, opts = {}) => {
225
+ let text = await this._renderString(content, locals, opts)
226
+ if (opts.postProcessor) text = await opts.postProcessor({ text, locals, opts })
227
+ return text
228
+ }
229
+
230
+ render = async (tpl, locals = {}, opts = {}) => {
231
+ const { runHook, breakNsPath } = this.app.bajo
232
+ const { upperFirst } = this.app.bajo.lib._
233
+ const cache = this.app.bajoCache
234
+ const key = crypto.createHash('md5').update(`${tpl}:${JSON.stringify(locals)}`).digest('hex')
235
+ const { subNs } = breakNsPath(tpl)
236
+ const canCache = subNs === 'template' && this.config.cache !== false && cache && this.app.bajo.config.env !== 'dev'
237
+ if (canCache) {
238
+ const item = await cache.get({ key })
239
+ if (item) return item
240
+ }
241
+ await runHook(`${this.name}:beforeRender${upperFirst(subNs)}`, { tpl, locals, opts })
242
+ let text = await this._render(tpl, locals, opts)
243
+ if (opts.postProcessor) text = await opts.postProcessor({ text, locals, opts })
244
+ await runHook(`${this.name}:afterRender${upperFirst(subNs)}`, { tpl, locals, opts, text })
245
+ if (canCache) await cache.set({ key, value: text, ttl: opts.cacheMaxAge ?? this.config.cache.maxAgeDur })
246
+ return text
247
+ }
248
+
249
+ resolveLayout = (item = '', opts = {}) => {
250
+ const fallbackHandler = ({ file, exts, ns, subSubNs, type, theme }) => {
251
+ const dir = ''
252
+ const base = 'default'
253
+ if (!this.config.layout.fallback) return false
254
+ // check main: theme specific
255
+ if (theme && !file) {
256
+ const check = `${this.app.main.dir.pkg}/${this.name}/${type}/_${theme}`
257
+ file = filecheck.call(this, { dir, base, exts, check })
258
+ }
259
+ // check mail: common
260
+ if (!file) {
261
+ const check = `${this.app.main.dir.pkg}/${this.name}/${type}`
262
+ file = filecheck.call(this, { dir, base, exts, check })
263
+ }
264
+ // check fallback: common
265
+ if (!file) {
266
+ const check = `${this.app[ns].dir.pkg}/${this.name}/${subSubNs ? (subSubNs + '/') : ''}${type}`
267
+ file = filecheck.call(this, { dir, base, exts, check })
268
+ }
269
+ // check general fallback
270
+ if (!file) {
271
+ const check = `${this.dir.pkg}/${this.name}/${subSubNs ? (subSubNs + '/') : ''}${type}`
272
+ file = filecheck.call(this, { dir, base, exts, check })
273
+ }
274
+ return file
275
+ }
276
+
277
+ return resolveResource.call(this, 'layout', item, opts, fallbackHandler)
278
+ }
279
+
280
+ resolvePartial = (item = '', opts = {}) => {
281
+ return resolveResource.call(this, 'partial', item, opts)
282
+ }
283
+
284
+ resolveTemplate = (item = '', opts = {}) => {
285
+ return resolveResource.call(this, 'template', item, opts)
286
+ }
287
+
288
+ splitContent = (input, readFile) => {
289
+ const { fs } = this.app.bajo.lib
290
+ const start = '---\n'
291
+ const end = '\n---'
292
+
293
+ let content = readFile ? fs.readFileSync(input, 'utf8') : input
294
+ let text = content.replaceAll('\r\n', '\n')
295
+ const open = text.indexOf(start)
296
+ let frontMatter
297
+ if (open > -1) {
298
+ text = text.slice(open + start.length)
299
+ const close = text.indexOf(end)
300
+ if (close > -1) {
301
+ frontMatter = text.slice(0, close)
302
+ content = text.slice(close + end.length)
303
+ }
304
+ }
305
+ frontMatter = frontMatter ?? ''
306
+ content = content ?? ''
307
+ return { frontMatter, content }
308
+ }
309
+ }
310
+ }
311
+
312
+ export default factory
package/plugin/.alias DELETED
@@ -1 +0,0 @@
1
- tpl
@@ -1,9 +0,0 @@
1
- {
2
- "layout": {
3
- "fallback": true
4
- },
5
- "loopDetectorDur": "1m",
6
- "cache": {
7
- "maxAgeDur": "1s"
8
- }
9
- }
@@ -1,51 +0,0 @@
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
- let canCache = this.config.cache !== false && cache && this.app.bajo.config.env !== 'dev'
35
- if (ttl === -1) canCache = false
36
- const opts = {
37
- imports: buildCompileImports.call(this, lang)
38
- }
39
-
40
- let item
41
- if (canCache) {
42
- const key = 'fn:' + crypto.createHash('md5').update(content).digest('hex')
43
- const value = template(content, opts)
44
- item = await cache.sync({ key, value, ttl })
45
- } else {
46
- item = template(content, opts)
47
- }
48
- return item(locals)
49
- }
50
-
51
- export default compile
@@ -1,12 +0,0 @@
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
@@ -1,18 +0,0 @@
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
@@ -1,84 +0,0 @@
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 (content, locals = {}, opts = {}) {
40
- const { merge, without, isString, omit } = this.app.bajo.lib._
41
- if (opts.ext === '.md' && this.app.bajoMarkdown) {
42
- content = await this.compile(content, locals, { lang: opts.lang, ttl: -1 }) // markdown can't process template tags, hence preprocess here
43
- content = this.app.bajoMarkdown.parse(content)
44
- }
45
- let layout
46
- if (!opts.partial) {
47
- const pageFm = await this.parseFrontMatter(opts.frontMatter, opts.lang)
48
- if (pageFm.layout) opts.layout = pageFm.layout
49
- locals.page = merge(locals.page, omit(pageFm, ['layout']))
50
- layout = opts.layout ?? (locals.page.ns ? `${locals.page.ns}.layout:/default.html` : 'main.layout:/default.html')
51
- const ext = path.extname(layout)
52
- const { file } = this.resolveLayout(layout, opts)
53
- let { content: layoutContent, frontMatter: layoutFm } = this.splitContent(file, true)
54
- layoutFm = await this.parseFrontMatter(layoutFm, opts.lang)
55
- const keys = without(Object.keys(layoutFm), 'css', 'scripts')
56
- if (['.html'].includes(ext)) {
57
- for (const item of ['css', 'scripts']) {
58
- locals.page[item] = locals.page[item] ?? []
59
- if (isString(locals.page[item])) locals.page[item] = [locals.page[item]]
60
- layoutFm[item] = layoutFm[item] ?? []
61
- if (isString(layoutFm[item])) layoutFm[item] = [layoutFm[item]]
62
- locals.page[item].unshift(...layoutFm[item])
63
- }
64
- }
65
- for (const key of keys) {
66
- locals.page[key] = locals.page[key] ?? layoutFm[key]
67
- }
68
- if (layoutFm.title && !locals.page.title) locals.page.title = layoutFm.title
69
- content = layoutContent.replace('<!-- body -->', content)
70
- const appTitle = this.print.write(locals.page.appTitle, { lang: opts.lang })
71
- const fullTitle = locals.page.title ? `${locals.page.title} - ${appTitle}` : appTitle
72
- locals.page.fullTitle = locals.fullTitle ?? fullTitle
73
- }
74
- content = await this.compile(content, locals, { lang: opts.lang, ttl: this.config.cache.maxAgeDur })
75
- return await handleInclude.call(this, content, locals, opts)
76
- }
77
-
78
- async function renderString (content, locals = {}, opts = {}) {
79
- let text = await _renderString.call(this, content, locals, opts)
80
- if (opts.postProcessor) text = await opts.postProcessor({ text, locals, opts })
81
- return text
82
- }
83
-
84
- export default renderString
@@ -1,77 +0,0 @@
1
- import crypto from 'crypto'
2
- import { _renderString } from './render-string.js'
3
- import path from 'path'
4
-
5
- let loopDetector = {}
6
-
7
- function _clearLoopDetector () {
8
- const { omit } = this.app.bajo.lib._
9
- const now = Date.now()
10
- const omitted = []
11
- for (const groupId in loopDetector) {
12
- const history = loopDetector[groupId]
13
- if ((history.ts + this.config.loopDetectorDur) < now) omitted.push(groupId)
14
- }
15
- loopDetector = omit(loopDetector, omitted)
16
- }
17
-
18
- function _detectLoop (tpl, file, opts) {
19
- const { last } = this.app.bajo.lib._
20
- if (opts.groupId) {
21
- if (loopDetector[opts.groupId]) {
22
- if (last(loopDetector[opts.groupId].file) === file && path.basename(file)[0] !== '~') throw this.error('loopDetected%s%s', tpl, file)
23
- loopDetector[opts.groupId].file.push(file)
24
- } else {
25
- loopDetector[opts.groupId] = {
26
- ts: Date.now(),
27
- file: [file]
28
- }
29
- }
30
- }
31
- }
32
-
33
- async function _render (tpl, locals = {}, opts = {}) {
34
- _clearLoopDetector.call(this)
35
- const { trim, isEmpty } = this.app.bajo.lib._
36
- const { fs } = this.app.bajo.lib
37
- const { breakNsPath } = this.app.bajo
38
-
39
- const { subNs } = breakNsPath(tpl)
40
- let resp
41
- if (subNs === 'template') {
42
- resp = this.resolveTemplate(tpl, opts)
43
- } else if (subNs === 'partial') {
44
- resp = this.resolvePartial(tpl, opts)
45
- }
46
- if (!resp) throw this.error('resourceNotFound%s', tpl)
47
- const { file } = resp
48
- _detectLoop.call(this, tpl, file, opts)
49
- const fileContent = trim(fs.readFileSync(file, 'utf8'))
50
- let { content, frontMatter } = this.splitContent(fileContent)
51
- if (isEmpty(content) && (subNs === 'template')) content = '<!-- include ' + tpl.replace('.template', '.partial') + ' -->'
52
- opts.ext = path.extname(file)
53
- opts.frontMatter = frontMatter
54
- opts.partial = opts.partial ?? subNs === 'partial'
55
- return await _renderString.call(this, content, locals, opts)
56
- }
57
-
58
- async function render (tpl, locals = {}, opts = {}) {
59
- const { runHook, breakNsPath } = this.app.bajo
60
- const { upperFirst } = this.app.bajo.lib._
61
- const cache = this.app.bajoCache
62
- const key = crypto.createHash('md5').update(`${tpl}:${JSON.stringify(locals)}`).digest('hex')
63
- const { subNs } = breakNsPath(tpl)
64
- const canCache = subNs === 'template' && this.config.cache !== false && cache && this.app.bajo.config.env !== 'dev'
65
- if (canCache) {
66
- const item = await cache.get({ key })
67
- if (item) return item
68
- }
69
- await runHook(`${this.name}:beforeRender${upperFirst(subNs)}`, { tpl, locals, opts })
70
- let text = await _render.call(this, tpl, locals, opts)
71
- if (opts.postProcessor) text = await opts.postProcessor({ text, locals, opts })
72
- await runHook(`${this.name}:afterRender${upperFirst(subNs)}`, { tpl, locals, opts, text })
73
- if (canCache) await cache.set({ key, value: text, ttl: opts.cacheMaxAge ?? this.config.cache.maxAgeDur })
74
- return text
75
- }
76
-
77
- export default render
@@ -1,34 +0,0 @@
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
@@ -1,7 +0,0 @@
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
@@ -1,7 +0,0 @@
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
@@ -1,23 +0,0 @@
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