@vituum/vite-plugin-latte 0.1.21 → 1.0.0-alpha.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.
package/handler.js CHANGED
@@ -7,6 +7,8 @@ const type = process.argv[3]
7
7
 
8
8
  params = params.map(value => Buffer.from(value, 'base64').toString('utf-8'))
9
9
 
10
- const output = await vite.plugins.filter(({ name }) => name === '@vituum/vite-plugin-latte')[0]._params[type][name](...params)
10
+ const output = await vite.plugins.find(plugin => plugin[0]?.name === '@vituum/vite-plugin-latte')[0]._options[type][name](...params)
11
11
 
12
- console.log(Buffer.from(output.toString(), 'utf-8').toString('base64'))
12
+ if (output) {
13
+ console.log(Buffer.from(output.toString(), 'utf-8').toString('base64'))
14
+ }
package/index.js CHANGED
@@ -1,28 +1,30 @@
1
- import { resolve, dirname } from 'path'
2
- import { fileURLToPath } from 'url'
3
- import fs from 'fs'
1
+ import { resolve, dirname, join } from 'node:path'
2
+ import { fileURLToPath } from 'node:url'
3
+ import fs from 'node:fs'
4
4
  import process from 'node:process'
5
- import * as childProcess from 'child_process'
5
+ import * as childProcess from 'node:child_process'
6
6
  import FastGlob from 'fast-glob'
7
- import lodash from 'lodash'
8
7
  import { minimatch } from 'minimatch'
9
- import chalk from 'chalk'
8
+ import { getPackageInfo, pluginError, pluginReload, merge, pluginBundle } from 'vituum/utils/common.js'
9
+ import { renameBuildEnd, renameBuildStart } from 'vituum/utils/build.js'
10
10
 
11
- const defaultParams = {
11
+ const { name } = getPackageInfo(import.meta.url)
12
+
13
+ /**
14
+ * @type {import('@vituum/vite-plugin-latte/types/index.d.ts').PluginUserConfig} options
15
+ */
16
+ const defaultOptions = {
12
17
  reload: true,
13
18
  root: null,
14
- bin: 'php',
15
19
  filters: {},
16
20
  functions: {},
17
21
  tags: {},
18
22
  globals: {},
19
- data: '',
20
- isStringFilter: undefined,
21
- ignoredPaths: [],
22
- filetypes: {
23
- html: /.(json.html|latte.json.html|latte.html)$/,
24
- json: /.(json.latte.html)$/
25
- }
23
+ data: ['src/data/**/*.json'],
24
+ formats: ['latte', 'json.latte', 'json'],
25
+ bin: 'php',
26
+ renderTransformedHtml: () => false,
27
+ ignoredPaths: []
26
28
  }
27
29
 
28
30
  const execSync = (cmd) => {
@@ -38,7 +40,9 @@ const execSync = (cmd) => {
38
40
  }
39
41
  }
40
42
 
41
- const renderTemplate = (path, params, content) => {
43
+ const renderTemplate = ({ path, filename, cwd, packageRoot }, params, content) => {
44
+ const renderTransformedHtml = params.renderTransformedHtml(filename)
45
+
42
46
  if (params.data) {
43
47
  const normalizePaths = Array.isArray(params.data) ? params.data.map(path => path.replace(/\\/g, '/')) : params.data.replace(/\\/g, '/')
44
48
 
@@ -57,100 +61,102 @@ const renderTemplate = (path, params, content) => {
57
61
  }
58
62
  })
59
63
 
60
- if (params.isString) {
64
+ if (renderTransformedHtml) {
61
65
  const timestamp = Math.floor(Date.now() * Math.random())
62
66
 
63
67
  params.contentTimestamp = timestamp
64
68
 
65
- if (!fs.existsSync(resolve(params.packageRoot, 'temp'))) {
66
- fs.mkdirSync(resolve(params.packageRoot, 'temp'))
69
+ if (!fs.existsSync(resolve(packageRoot, 'temp'))) {
70
+ fs.mkdirSync(resolve(packageRoot, 'temp'))
67
71
  }
68
72
 
69
- fs.writeFileSync(resolve(params.packageRoot, `temp/${timestamp}.html`), content)
73
+ fs.writeFileSync(resolve(packageRoot, `temp/${timestamp}.html`), content)
70
74
  }
71
75
 
72
- return execSync(`${params.bin} ${params.packageRoot}/index.php ${params.root + path} ${JSON.stringify(JSON.stringify(params))}`)
76
+ return execSync(`${params.bin} ${packageRoot}/index.php ${join(params.root, path)} ${JSON.stringify(JSON.stringify(Object.assign({ packageRoot, cwd, renderTransformedHtml }, params)))}`)
73
77
  }
74
78
 
75
- const latte = (params = {}) => {
76
- params.cwd = process.cwd()
79
+ /**
80
+ * @param {import('@vituum/vite-plugin-latte/types/index.d.ts').PluginUserConfig} options
81
+ * @returns [import('vite').Plugin]
82
+ */
83
+ const plugin = (options = {}) => {
84
+ let resolvedConfig
85
+ let userEnv
77
86
 
78
- params = lodash.merge(defaultParams, params)
87
+ options = merge(defaultOptions, options)
79
88
 
80
- params.packageRoot = dirname((fileURLToPath(import.meta.url)))
89
+ const cwd = process.cwd()
90
+ const packageRoot = dirname((fileURLToPath(import.meta.url)))
81
91
 
82
- if (fs.existsSync(resolve(params.packageRoot, 'temp'))) {
83
- fs.rmSync(resolve(params.packageRoot, 'temp'), { recursive: true, force: true })
92
+ if (fs.existsSync(resolve(packageRoot, 'temp'))) {
93
+ fs.rmSync(resolve(packageRoot, 'temp'), { recursive: true, force: true })
84
94
  }
85
95
 
86
- if (params.bin === 'docker') {
87
- params.bin = `docker run --rm --name index -v "${process.cwd()}":/usr/src/app -w /usr/src/app php:8-cli php`
96
+ if (options.bin === 'docker') {
97
+ options.bin = `docker run --rm --name index -v "${process.cwd()}":/usr/src/app -w /usr/src/app php:8-cli php`
88
98
  }
89
99
 
90
- return {
91
- _params: params,
92
- name: '@vituum/vite-plugin-latte',
93
- config: ({ root }) => {
94
- if (!params.root) {
95
- params.root = root
100
+ return [{
101
+ _options: options,
102
+ name,
103
+ config (userConfig, env) {
104
+ userEnv = env
105
+ },
106
+ configResolved (config) {
107
+ resolvedConfig = config
108
+
109
+ if (!options.root) {
110
+ options.root = config.root
96
111
  }
97
112
  },
113
+ buildStart: async () => {
114
+ if (userEnv.command !== 'build') {
115
+ return
116
+ }
117
+
118
+ await renameBuildStart(resolvedConfig.build.rollupOptions.input, options.formats)
119
+ },
120
+ buildEnd: async () => {
121
+ if (userEnv.command !== 'build') {
122
+ return
123
+ }
124
+
125
+ await renameBuildEnd(resolvedConfig.build.rollupOptions.input, options.formats)
126
+ },
98
127
  transformIndexHtml: {
99
128
  enforce: 'pre',
100
- async transform(content, { path, filename, server }) {
129
+ async transform (content, { path, filename, server }) {
101
130
  path = path.replace('?raw', '')
102
131
  filename = filename.replace('?raw', '')
103
132
 
104
- if (params.ignoredPaths.filter(ignoredPaths => minimatch(path.replace('.html', '').replace('.vituum', ''), ignoredPaths)).length !== 0) {
133
+ if (options.ignoredPaths.find(ignoredPath => minimatch(path.replace('.html', ''), ignoredPath) === true)) {
105
134
  return content
106
135
  }
107
136
 
108
- if (
109
- !params.filetypes.html.test(path) &&
110
- !params.filetypes.json.test(path) &&
111
- !content.startsWith('<script type="application/json" data-format="latte"')
112
- ) {
137
+ if (!options.formats.find(format => path.endsWith(`${format}.html`))) {
113
138
  return content
114
139
  }
115
140
 
116
- if (typeof params.isStringFilter === 'function' && params.isStringFilter(filename)) {
117
- params.isString = true
118
- } else {
119
- params.isString = false
120
- }
141
+ const render = renderTemplate({ path, filename, cwd, packageRoot }, options, content)
142
+ const warningLog = render.output.includes('Warning: Undefined')
121
143
 
122
- const renderLatte = renderTemplate(path, params, content)
123
- const warningLog = renderLatte.output.includes('Warning: Undefined')
144
+ if (render.error || warningLog) {
145
+ const message = warningLog ? 'Warning: Undefined' + render.output.split('Warning: Undefined').pop() : render.output
146
+ const renderError = pluginError(message, server, name)
124
147
 
125
- if (renderLatte.error || warningLog) {
126
- if (!server) {
127
- console.error(chalk.red(renderLatte.output))
148
+ if (renderError && server) {
128
149
  return
150
+ } else if (renderError) {
151
+ return renderError
129
152
  }
130
-
131
- const message = warningLog ? 'Warning: Undefined' + renderLatte.output.split('Warning: Undefined').pop() : renderLatte.output
132
-
133
- setTimeout(() => server.ws.send({
134
- type: 'error',
135
- err: {
136
- message,
137
- plugin: '@vituum/vite-plugin-latte'
138
- }
139
- }), 50)
140
153
  }
141
154
 
142
- return renderLatte.output
155
+ return render.output
143
156
  }
144
157
  },
145
- handleHotUpdate({ file, server }) {
146
- if (
147
- (typeof params.reload === 'function' && params.reload(file)) ||
148
- (typeof params.reload === 'boolean' && params.reload && (params.filetypes.html.test(file) || params.filetypes.json.test(file)))
149
- ) {
150
- server.ws.send({ type: 'full-reload' })
151
- }
152
- }
153
- }
158
+ handleHotUpdate: ({ file, server }) => pluginReload({ file, server }, options)
159
+ }, pluginBundle(options.formats)]
154
160
  }
155
161
 
156
- export default latte
162
+ export default plugin
package/index.php CHANGED
@@ -164,7 +164,7 @@ if (!file_exists(str_replace($config->cwd, ROOT_DIR, $params->template))) {
164
164
  throw new Error('File not found ' . str_replace($config->cwd, ROOT_DIR, $params->template));
165
165
  }
166
166
 
167
- if (isset($config->isString) && $config->isString) {
167
+ if (isset($config->renderTransformedHtml) && $config->renderTransformedHtml) {
168
168
  if (isset($config->contentTimestamp)) {
169
169
  $content = file_get_contents(__DIR__ . '/temp/' . $config->contentTimestamp . '.html');
170
170
  unlink(__DIR__ . '/temp/' . $config->contentTimestamp . '.html');
@@ -6,6 +6,6 @@ class AssetFilter
6
6
  {
7
7
  public static function execute($source): string
8
8
  {
9
- return str_starts_with($source, 'http') ? $source : str_replace("/src/", "/", $source);
9
+ return $source;
10
10
  }
11
11
  }
package/package.json CHANGED
@@ -1,31 +1,38 @@
1
1
  {
2
2
  "name": "@vituum/vite-plugin-latte",
3
- "version": "0.1.21",
3
+ "version": "1.0.0-alpha.2",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "dev": "vite dev",
8
- "build": "vite build && mv public/views/* public && rm -rf public/views",
8
+ "build": "vite build",
9
9
  "preview": "vite preview"
10
10
  },
11
11
  "dependencies": {
12
+ "vituum": "^1.0.0-alpha.16",
12
13
  "fast-glob": "^3.2.12",
13
14
  "lodash": "^4.17.21",
14
- "chalk": "^5.2.0",
15
- "minimatch": "^9.0.0"
15
+ "minimatch": "^9.0.1"
16
16
  },
17
17
  "devDependencies": {
18
- "vite": "^4.2.2",
19
- "eslint": "^8.38.0",
20
- "eslint-config-standard": "^17.0.0"
18
+ "@types/node": "^20.3.1",
19
+ "vite": "^4.3.9",
20
+ "eslint": "^8.42.0",
21
+ "eslint-config-standard": "^17.1.0",
22
+ "typescript": "^5.1.3"
21
23
  },
22
24
  "files": [
23
25
  "index.js",
24
26
  "handler.js",
25
27
  "index.php",
26
28
  "latte",
27
- "vendor"
29
+ "vendor",
30
+ "types"
28
31
  ],
32
+ "exports": {
33
+ ".": "./index.js",
34
+ "./types": "./types/*"
35
+ },
29
36
  "engines": {
30
37
  "node": ">=16.0.0",
31
38
  "npm": ">=8.0.0"
@@ -0,0 +1,13 @@
1
+ export interface PluginUserConfig {
2
+ reload?: boolean | Function
3
+ root?: string
4
+ filters?: Object
5
+ functions?: Object
6
+ tags?: Object
7
+ globals?: Object
8
+ data?: string | string[]
9
+ formats?: string[]
10
+ bin?: string
11
+ renderTransformedHtml?: (filename: string) => boolean
12
+ ignoredPaths?: string[]
13
+ }