kirbyup 3.4.1 → 3.5.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/README.md +18 -21
- package/bin/kirbyup.mjs +1 -1
- package/dist/client/{config.d.ts → config.d.mts} +1 -2
- package/dist/client/{config.js → config.mjs} +1 -2
- package/dist/client/plugin.mjs +20 -0
- package/dist/node/cli.d.mts +1 -0
- package/dist/node/{cli-start.js → cli.mjs} +5 -5
- package/dist/node/{index.d.ts → index.d.mts} +1 -2
- package/dist/node/index.mjs +2 -0
- package/dist/node-UMSghnjT.mjs +470 -0
- package/dist/types-C3c_wslr.d.mts +43 -0
- package/package.json +32 -49
- package/dist/client/plugin.js +0 -14
- package/dist/node/cli.d.ts +0 -1
- package/dist/node/cli.js +0 -8
- package/dist/node/config.js +0 -22
- package/dist/node/errors.js +0 -18
- package/dist/node/index.js +0 -175
- package/dist/node/plugins/build-cleanup.js +0 -21
- package/dist/node/plugins/glob-import.js +0 -35
- package/dist/node/plugins/hmr.js +0 -57
- package/dist/node/plugins/utils.js +0 -113
- package/dist/node/types.d.ts +0 -44
- package/dist/node/utils.js +0 -26
- package/dist/package.js +0 -6
- /package/dist/client/{plugin.d.ts → plugin.d.mts} +0 -0
package/README.md
CHANGED
|
@@ -2,25 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
# kirbyup
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
The official bundler for Kirby Panel plugins with zero-config usage and built-in HMR.
|
|
5
|
+
The official bundler for Kirby Panel plugins. Zero-config, built-in HMR.
|
|
8
6
|
|
|
9
7
|
- [✨ Release Notes](https://github.com/johannschopplich/kirbyup/releases)
|
|
10
8
|
- [📖 Read the documentation](https://kirbyup.getkirby.com)
|
|
11
9
|
|
|
12
10
|
## Key Features
|
|
13
11
|
|
|
14
|
-
- 🔄 [Hot
|
|
15
|
-
- 🎒 PostCSS
|
|
16
|
-
-
|
|
17
|
-
- 🔌
|
|
18
|
-
- 🦔 [
|
|
12
|
+
- 🔄 [Hot Module Replacement](https://kirbyup.getkirby.com/guide/getting-started.html#development)
|
|
13
|
+
- 🎒 [PostCSS & Sass](https://kirbyup.getkirby.com/guide/postcss)
|
|
14
|
+
- 🧩 [kirbyuse Integration](https://kirbyup.getkirby.com/guide/kirbyuse)
|
|
15
|
+
- 🔌 [Environment Variables](https://kirbyup.getkirby.com/guide/environment-variables)
|
|
16
|
+
- 🦔 [Configuration File](https://kirbyup.getkirby.com/guide/config-file)
|
|
17
|
+
- 🧭 [Path Aliases](https://kirbyup.getkirby.com/guide/path-aliases)
|
|
19
18
|
|
|
20
19
|
## Setup
|
|
21
20
|
|
|
22
21
|
> [!TIP]
|
|
23
|
-
>
|
|
22
|
+
> Skip starting from scratch and pick one of the following starters:
|
|
23
|
+
> - [`eslint`](./examples/eslint)
|
|
24
|
+
> - [`unocss`](./examples/unocss)
|
|
24
25
|
|
|
25
26
|
```bash
|
|
26
27
|
# pnpm
|
|
@@ -28,16 +29,12 @@ pnpm add -D kirbyup
|
|
|
28
29
|
|
|
29
30
|
# npm
|
|
30
31
|
npm i -D kirbyup
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
## Basic Usage
|
|
34
32
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
> - [`tailwindcss`](./examples/tailwindcss)
|
|
33
|
+
# yarn
|
|
34
|
+
yarn add -D kirbyup
|
|
35
|
+
```
|
|
39
36
|
|
|
40
|
-
|
|
37
|
+
After installation, add these scripts to your `package.json`:
|
|
41
38
|
|
|
42
39
|
```json
|
|
43
40
|
{
|
|
@@ -46,18 +43,18 @@ Having installed kirbyup, you can add the following scripts as shortcuts to the
|
|
|
46
43
|
"build": "kirbyup src/index.js"
|
|
47
44
|
},
|
|
48
45
|
"devDependencies": {
|
|
49
|
-
"kirbyup": "^3.
|
|
46
|
+
"kirbyup": "^3.5.0"
|
|
50
47
|
}
|
|
51
48
|
}
|
|
52
49
|
```
|
|
53
50
|
|
|
54
|
-
##
|
|
51
|
+
## Development
|
|
55
52
|
|
|
56
53
|
1. Clone this repository
|
|
57
54
|
2. Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`
|
|
58
55
|
3. Install dependencies using `pnpm install`
|
|
59
|
-
4.
|
|
60
|
-
5.
|
|
56
|
+
4. Build with `pnpm run build`
|
|
57
|
+
5. Run tests with `pnpm test`
|
|
61
58
|
|
|
62
59
|
## License
|
|
63
60
|
|
package/bin/kirbyup.mjs
CHANGED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region src/client/plugin.ts
|
|
2
|
+
const kirbyup = Object.freeze({
|
|
3
|
+
/**
|
|
4
|
+
* Auto-import Kirby Panel components, transformed by
|
|
5
|
+
* kirbyup's glob-import plugin for Vite.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* kirbyup.import('./components/blocks/*.vue')
|
|
9
|
+
*/
|
|
10
|
+
import(glob) {
|
|
11
|
+
return Object.entries(glob).reduce((accumulator, [path, component]) => {
|
|
12
|
+
accumulator[getComponentName(path)] = component.default;
|
|
13
|
+
return accumulator;
|
|
14
|
+
}, {});
|
|
15
|
+
} });
|
|
16
|
+
function getComponentName(path) {
|
|
17
|
+
return path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")).toLowerCase();
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
export { kirbyup };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { name,
|
|
2
|
-
import { build, serve } from "./index.js";
|
|
1
|
+
import { a as version, i as name, n as serve, r as handleError, t as build } from "../node-UMSghnjT.mjs";
|
|
3
2
|
import { cac } from "cac";
|
|
4
|
-
|
|
5
3
|
//#region src/node/cli-start.ts
|
|
6
4
|
async function startCli(cwd = process.cwd(), argv = process.argv) {
|
|
7
5
|
const cli = cac(name);
|
|
@@ -37,6 +35,8 @@ async function startCli(cwd = process.cwd(), argv = process.argv) {
|
|
|
37
35
|
cli.parse(argv, { run: false });
|
|
38
36
|
await cli.runMatchedCommand();
|
|
39
37
|
}
|
|
40
|
-
|
|
41
38
|
//#endregion
|
|
42
|
-
|
|
39
|
+
//#region src/node/cli.ts
|
|
40
|
+
startCli().catch(handleError);
|
|
41
|
+
//#endregion
|
|
42
|
+
export {};
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as ServeOptions, t as BuildOptions } from "../types-C3c_wslr.mjs";
|
|
2
2
|
import { ViteDevServer } from "vite";
|
|
3
|
-
|
|
4
3
|
//#region src/node/index.d.ts
|
|
5
4
|
declare function build(options: BuildOptions): Promise<void>;
|
|
6
5
|
declare function serve(options: ServeOptions): Promise<ViteDevServer>;
|
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as fsp from "node:fs/promises";
|
|
3
|
+
import vuePlugin from "@vitejs/plugin-vue2";
|
|
4
|
+
import vueJsxPlugin from "@vitejs/plugin-vue2-jsx";
|
|
5
|
+
import { consola } from "consola";
|
|
6
|
+
import { colors } from "consola/utils";
|
|
7
|
+
import { basename, dirname, normalize, relative, resolve } from "pathe";
|
|
8
|
+
import { debounce } from "perfect-debounce";
|
|
9
|
+
import externalGlobals from "rollup-plugin-external-globals";
|
|
10
|
+
import { build, createLogger, createServer, mergeConfig } from "vite";
|
|
11
|
+
import fullReloadPlugin from "vite-plugin-full-reload";
|
|
12
|
+
import * as vueCompilerSfc from "vue/compiler-sfc";
|
|
13
|
+
import { loadConfig } from "c12";
|
|
14
|
+
import postcssrc from "postcss-load-config";
|
|
15
|
+
import MagicString from "magic-string";
|
|
16
|
+
import { stripLiteral } from "strip-literal";
|
|
17
|
+
import { detectPackageManager } from "nypm";
|
|
18
|
+
import { isIP } from "node:net";
|
|
19
|
+
import { Buffer } from "node:buffer";
|
|
20
|
+
import { promisify } from "node:util";
|
|
21
|
+
import { gzip } from "node:zlib";
|
|
22
|
+
//#region package.json
|
|
23
|
+
var name = "kirbyup";
|
|
24
|
+
var version = "3.5.0";
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/node/config.ts
|
|
27
|
+
function loadConfig$1(cwd = process.cwd()) {
|
|
28
|
+
return loadConfig({
|
|
29
|
+
cwd,
|
|
30
|
+
name: "kirbyup",
|
|
31
|
+
rcFile: false,
|
|
32
|
+
packageJson: false
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
async function resolvePostCSSConfig(cwd) {
|
|
36
|
+
try {
|
|
37
|
+
return await postcssrc(void 0, void 0, { stopDir: cwd });
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (!error.message.includes("No PostCSS Config found")) throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/node/errors.ts
|
|
44
|
+
var PrettyError = class extends Error {
|
|
45
|
+
constructor(message) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = this.constructor.name;
|
|
48
|
+
Error.captureStackTrace(this, this.constructor);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
function handleError(error) {
|
|
52
|
+
consola.error(error.message);
|
|
53
|
+
process.exitCode = 1;
|
|
54
|
+
}
|
|
55
|
+
//#endregion
|
|
56
|
+
//#region src/node/plugins/build-cleanup.ts
|
|
57
|
+
function kirbyupBuildCleanupPlugin(options) {
|
|
58
|
+
let config;
|
|
59
|
+
let devIndexPath;
|
|
60
|
+
return {
|
|
61
|
+
name: "kirbyup:build-cleanup",
|
|
62
|
+
configResolved(resolvedConfig) {
|
|
63
|
+
config = resolvedConfig;
|
|
64
|
+
devIndexPath = resolve(config.root, options.outDir, "index.dev.mjs");
|
|
65
|
+
},
|
|
66
|
+
writeBundle() {
|
|
67
|
+
if (fs.existsSync(devIndexPath)) fs.unlinkSync(devIndexPath);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
//#endregion
|
|
72
|
+
//#region src/node/plugins/glob-import.ts
|
|
73
|
+
/**
|
|
74
|
+
* Transforms `kirbyup.import(<path>)` to `kirbyup.import(import.meta.glob(<path>, { eager: true }))`.
|
|
75
|
+
*
|
|
76
|
+
* Must run before Vite's own `import.meta.glob` plugin (also `enforce: 'pre'`),
|
|
77
|
+
* otherwise the emitted call is never expanded.
|
|
78
|
+
*/
|
|
79
|
+
function kirbyupGlobImportPlugin() {
|
|
80
|
+
let config;
|
|
81
|
+
return {
|
|
82
|
+
name: "kirbyup:glob-import",
|
|
83
|
+
enforce: "pre",
|
|
84
|
+
configResolved(resolvedConfig) {
|
|
85
|
+
config = resolvedConfig;
|
|
86
|
+
},
|
|
87
|
+
transform(code) {
|
|
88
|
+
if (!code.includes("kirbyup.import")) return;
|
|
89
|
+
const kirbyupImportRE = /\bkirbyup\.import\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*\)/dg;
|
|
90
|
+
const cleanCode = stripLiteral(code);
|
|
91
|
+
let s;
|
|
92
|
+
for (const match of cleanCode.matchAll(kirbyupImportRE)) {
|
|
93
|
+
const { 0: exp, index } = match;
|
|
94
|
+
const [argStart, argEnd] = match.indices[1];
|
|
95
|
+
const rawPath = code.slice(argStart, argEnd);
|
|
96
|
+
if (!s) s = new MagicString(code);
|
|
97
|
+
s.overwrite(index, index + exp.length, `kirbyup.import(import.meta.glob(${rawPath}, { eager: true }))`);
|
|
98
|
+
}
|
|
99
|
+
if (s) return {
|
|
100
|
+
code: s.toString(),
|
|
101
|
+
map: config.build.sourcemap ? s.generateMap({ hires: true }) : void 0
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region src/node/utils/server.ts
|
|
108
|
+
function resolveOriginFromServerOptions(serverOptions, port, fallbackHostname) {
|
|
109
|
+
const protocol = serverOptions?.https && (typeof serverOptions.https === "boolean" || Object.keys(serverOptions.https).length > 0) ? "https" : "http";
|
|
110
|
+
const configuredHost = normalizeHost(serverOptions?.host);
|
|
111
|
+
return `${protocol}://${formatHostname(configuredHost || fallbackHostname || "localhost")}${(configuredHost ? hostIncludesPort(configuredHost) : false) || !needsExplicitPort(protocol, port) ? "" : `:${port}`}`;
|
|
112
|
+
}
|
|
113
|
+
function ensureTrailingSlash(url) {
|
|
114
|
+
return url.endsWith("/") ? url : `${url}/`;
|
|
115
|
+
}
|
|
116
|
+
function normalizeHost(host) {
|
|
117
|
+
if (host === false || host === void 0) return;
|
|
118
|
+
if (host === true) return "0.0.0.0";
|
|
119
|
+
return host;
|
|
120
|
+
}
|
|
121
|
+
function formatHostname(host) {
|
|
122
|
+
if (!host) return "localhost";
|
|
123
|
+
if (host.startsWith("[") && host.endsWith("]")) return host;
|
|
124
|
+
return isIP(host) === 6 ? `[${host}]` : host;
|
|
125
|
+
}
|
|
126
|
+
function hostIncludesPort(host) {
|
|
127
|
+
if (host.startsWith("[")) {
|
|
128
|
+
const closingIndex = host.indexOf("]");
|
|
129
|
+
return closingIndex > -1 && host.slice(closingIndex + 1).startsWith(":");
|
|
130
|
+
}
|
|
131
|
+
if (isIP(host) === 6) return false;
|
|
132
|
+
return host.includes(":");
|
|
133
|
+
}
|
|
134
|
+
function needsExplicitPort(protocol, port) {
|
|
135
|
+
if (protocol === "http") return port !== 80;
|
|
136
|
+
return port !== 443;
|
|
137
|
+
}
|
|
138
|
+
function isHmrRuntimeId(id) {
|
|
139
|
+
return id === "\0plugin-vue2:hmr-runtime" || id === "plugin-vue2-jsx:hmr-runtime";
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* This code is injected into the HMR runtime of plugin-vue2(-jsx).
|
|
143
|
+
*
|
|
144
|
+
* All `.vue` components register themselves once with the HMR runtime, so their exported
|
|
145
|
+
* component definitions can be stored in a map, alongside the rendered component instances
|
|
146
|
+
* that are based off this definition. When a module is updated, the runtime applies all
|
|
147
|
+
* changes from the updated module to the stored definition, then re-renders the instances.
|
|
148
|
+
*
|
|
149
|
+
* ```js
|
|
150
|
+
* {
|
|
151
|
+
* [id]: { options: ComponentDefinition, instances: [...] }
|
|
152
|
+
* }
|
|
153
|
+
* ```
|
|
154
|
+
*
|
|
155
|
+
* However, in some cases (sections and blocks) Kirby does not actually register the
|
|
156
|
+
* object that is exported from a `.vue` file (and stored as definition) as component,
|
|
157
|
+
* instead it creates a new object and merges the definition from the `.vue` file in:
|
|
158
|
+
* https://github.com/getkirby/kirby/blob/main/panel/public/js/plugins.js#L22-L25
|
|
159
|
+
* After changes, the runtime updates the definition and re-renders the instances, but since
|
|
160
|
+
* they are derived from the object created by Kirby, not the stored definition, nothing happens.
|
|
161
|
+
* To fix that, we wrap `rerender()` and `reload()` so that before applying the updates, we first check
|
|
162
|
+
* if the updated definition belongs to a component added by a Kirby plugin. To do so, we can check
|
|
163
|
+
* whether the `__file` (added by plugin-vue2) or `__hmrId` (added by plugin-vue2-jsx) properties of the
|
|
164
|
+
* updated module and the plugin component match. If so, we look up the component definition that is
|
|
165
|
+
* _actually_ used by component instances rendered on the page (`window.panel.app.$options.components`)
|
|
166
|
+
* and if it differs from the one stored in the HMR runtime's map, we updates the map's reference.
|
|
167
|
+
*
|
|
168
|
+
* We also check the component name and add a `$_isSection` flag if it's `k-something-section`, because
|
|
169
|
+
* section components are hard to detect and need special treatment in `$_applyKirbyModifications`.
|
|
170
|
+
*
|
|
171
|
+
* `$_applyKirbyModifications`:
|
|
172
|
+
*
|
|
173
|
+
* Kirby modifies component definitions before registering components.
|
|
174
|
+
* This includes adding the section mixin to section components,
|
|
175
|
+
* giving templates priority over render functions if both exist
|
|
176
|
+
* and resolving component names in `extends` to their definition object:
|
|
177
|
+
* https://github.com/getkirby/kirby/blob/2965c3124e3b141072a2d46c798a327dda710060/panel/src/panel/plugins.js
|
|
178
|
+
* When a module is reloaded, Vue receives a fresh component definition that is
|
|
179
|
+
* missing these modifications. We need to re-apply them, else the runtime will
|
|
180
|
+
* prune them when patching the stored definition to match the newer one.
|
|
181
|
+
*
|
|
182
|
+
* The call to `$_applyKirbyModifications()` is injected into `__VUE_HMR_RUNTIME__.reload()`
|
|
183
|
+
* at the appropriate position using a RegExp in the Vite plugin's transform method.
|
|
184
|
+
*/
|
|
185
|
+
const __INJECTED_HMR_CODE__ = `
|
|
186
|
+
/** - injected by kirbyup - */
|
|
187
|
+
for (const methodName of ['rerender', 'reload']) {
|
|
188
|
+
const original = __VUE_HMR_RUNTIME__[methodName]
|
|
189
|
+
|
|
190
|
+
__VUE_HMR_RUNTIME__[methodName] = function (id, updatedDef) {
|
|
191
|
+
const key = updatedDef?.__file ? '__file' : updatedDef?.__hmrId ? '__hmrId' : null
|
|
192
|
+
|
|
193
|
+
if (key) {
|
|
194
|
+
const pluginComponents = window.panel.plugins.components
|
|
195
|
+
// const usedComponentDefs = window.panel.app.$options.components
|
|
196
|
+
const usedComponentDefs = window.panel.app._vnode.componentInstance.$options.components // #33
|
|
197
|
+
|
|
198
|
+
for (const componentName in pluginComponents) {
|
|
199
|
+
if (updatedDef[key] === pluginComponents[componentName][key]) {
|
|
200
|
+
const usedDefinition = usedComponentDefs[componentName].options
|
|
201
|
+
|
|
202
|
+
if (map[id].options !== usedDefinition)
|
|
203
|
+
map[id].options = usedDefinition
|
|
204
|
+
|
|
205
|
+
if (typeof map[id].options.$_isSection !== 'boolean')
|
|
206
|
+
map[id].options.$_isSection = /^k-.*-section$/.test(componentName)
|
|
207
|
+
|
|
208
|
+
break
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return original.apply(this, arguments)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function $_applyKirbyModifications(activeDef, newDef) {
|
|
218
|
+
const usedComponentDefs = window.panel.app.$options.components
|
|
219
|
+
|
|
220
|
+
if (newDef.template)
|
|
221
|
+
newDef.render = null
|
|
222
|
+
|
|
223
|
+
if (activeDef.$_isSection)
|
|
224
|
+
newDef.$_isSection = true
|
|
225
|
+
if (newDef.$_isSection && !newDef.mixins?.[0]?.methods?.load)
|
|
226
|
+
newDef.mixins = [activeDef.mixins[0], ...(newDef.mixins || [])]
|
|
227
|
+
|
|
228
|
+
if (typeof newDef.extends === 'string') {
|
|
229
|
+
if (newDef.extends === activeDef.extends?.options?.name) {
|
|
230
|
+
newDef.extends = activeDef.extends
|
|
231
|
+
}
|
|
232
|
+
else if (usedComponentDefs[newDef.extends]) {
|
|
233
|
+
newDef.extends = usedComponentDefs[newDef.extends].extend({
|
|
234
|
+
options: newDef,
|
|
235
|
+
components: { ...usedComponentDefs, ...(newDef.components || {}) },
|
|
236
|
+
})
|
|
237
|
+
}
|
|
238
|
+
else { newDef.extends = null }
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** -- */
|
|
242
|
+
`;
|
|
243
|
+
//#endregion
|
|
244
|
+
//#region src/node/plugins/hmr.ts
|
|
245
|
+
function kirbyupHmrPlugin(options) {
|
|
246
|
+
let config;
|
|
247
|
+
let entry;
|
|
248
|
+
let devIndexPath;
|
|
249
|
+
return {
|
|
250
|
+
name: "kirbyup:hmr",
|
|
251
|
+
apply: "serve",
|
|
252
|
+
configResolved(resolvedConfig) {
|
|
253
|
+
config = resolvedConfig;
|
|
254
|
+
entry = resolve(config.root, options.entry);
|
|
255
|
+
devIndexPath = resolve(config.root, options.outDir ?? "", "index.dev.mjs");
|
|
256
|
+
},
|
|
257
|
+
transform(code, id) {
|
|
258
|
+
if (isHmrRuntimeId(id)) return code.replace(/^.*=\s*record\.Ctor\.super\.extend\(options\)/m, "$_applyKirbyModifications(record.Ctor.options, options) // injected by kirbyup\n$&") + __INJECTED_HMR_CODE__;
|
|
259
|
+
},
|
|
260
|
+
configureServer(server) {
|
|
261
|
+
if (!server.httpServer) return;
|
|
262
|
+
server.httpServer.once("listening", async () => {
|
|
263
|
+
const entryPath = entry.replace(`${config.root}/`, "");
|
|
264
|
+
const baseUrl = getDevBaseUrl(server, config);
|
|
265
|
+
const entryUrl = new URL(entryPath, baseUrl).href;
|
|
266
|
+
const pm = await detectPackageManager(config.root);
|
|
267
|
+
await fsp.writeFile(devIndexPath, getViteProxyModule(entryUrl, pm));
|
|
268
|
+
});
|
|
269
|
+
},
|
|
270
|
+
async closeBundle() {
|
|
271
|
+
await fsp.rm(devIndexPath, { force: true });
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Proxy the JS file to "forward" the plugin script loaded by Kirby to the Vite server
|
|
277
|
+
*/
|
|
278
|
+
function getViteProxyModule(entryUrl, packageManager) {
|
|
279
|
+
const pm = packageManager?.name || "npm";
|
|
280
|
+
return `
|
|
281
|
+
try {
|
|
282
|
+
await import("${entryUrl}");
|
|
283
|
+
} catch (error) {
|
|
284
|
+
console.error(
|
|
285
|
+
"[kirbyup] Couldn't connect to the development server at ${entryUrl}. Run \`${pm} run serve\` to start Vite or build the plugin with \`${pm} run build\` so Kirby uses the production version."
|
|
286
|
+
);
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
`.trimStart();
|
|
290
|
+
}
|
|
291
|
+
function getDevBaseUrl(server, config) {
|
|
292
|
+
const { address, port } = server.httpServer.address();
|
|
293
|
+
const normalizedOrigin = ensureTrailingSlash(config.server?.origin ?? server.resolvedUrls?.local?.[0] ?? server.resolvedUrls?.network?.[0] ?? resolveOriginFromServerOptions(config.server, port, address));
|
|
294
|
+
const base = config.base ?? "/";
|
|
295
|
+
return new URL(base, normalizedOrigin).href;
|
|
296
|
+
}
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/node/utils.ts
|
|
299
|
+
const compress = promisify(gzip);
|
|
300
|
+
function toArray(array) {
|
|
301
|
+
array ??= [];
|
|
302
|
+
return Array.isArray(array) ? array : [array];
|
|
303
|
+
}
|
|
304
|
+
async function getCompressedSize(code) {
|
|
305
|
+
return ` / gzip: ${((await compress(typeof code === "string" ? code : Buffer.from(code))).length / 1024).toFixed(2)} KiB`;
|
|
306
|
+
}
|
|
307
|
+
async function printFileInfo({ root, outDir, filePath, content, type, maxLength }) {
|
|
308
|
+
const prettyOutDir = `${normalize(relative(root, resolve(root, outDir)))}/`;
|
|
309
|
+
const kibs = content.length / 1024;
|
|
310
|
+
const compressedSize = await getCompressedSize(content);
|
|
311
|
+
const writeColor = type === "chunk" ? colors.cyan : colors.magenta;
|
|
312
|
+
consola.log(colors.white(colors.dim(prettyOutDir)) + writeColor(filePath.padEnd(maxLength + 2)) + colors.dim(`${kibs.toFixed(2)} kB${compressedSize}`));
|
|
313
|
+
}
|
|
314
|
+
//#endregion
|
|
315
|
+
//#region src/node/index.ts
|
|
316
|
+
let resolvedKirbyupConfig;
|
|
317
|
+
let resolvedPostCssConfig;
|
|
318
|
+
const logLevel = "warn";
|
|
319
|
+
const logger = createLogger(logLevel);
|
|
320
|
+
const loggerWarn = logger.warn;
|
|
321
|
+
logger.warn = (msg, options) => {
|
|
322
|
+
if (msg.includes("(!) build.outDir")) return;
|
|
323
|
+
loggerWarn(msg, options);
|
|
324
|
+
};
|
|
325
|
+
function getViteConfig(command, options) {
|
|
326
|
+
const aliasDir = resolve(options.cwd, dirname(options.entry));
|
|
327
|
+
const { alias = {}, vite, extendViteConfig } = resolvedKirbyupConfig;
|
|
328
|
+
const userConfig = vite ?? extendViteConfig ?? {};
|
|
329
|
+
const sharedConfig = {
|
|
330
|
+
resolve: { alias: {
|
|
331
|
+
"~/": `${aliasDir}/`,
|
|
332
|
+
"@/": `${aliasDir}/`,
|
|
333
|
+
...alias
|
|
334
|
+
} },
|
|
335
|
+
plugins: [
|
|
336
|
+
vuePlugin({ compiler: vueCompilerSfc }),
|
|
337
|
+
vueJsxPlugin(),
|
|
338
|
+
kirbyupGlobImportPlugin(),
|
|
339
|
+
{
|
|
340
|
+
...externalGlobals({ vue: "Vue" }),
|
|
341
|
+
enforce: "post"
|
|
342
|
+
}
|
|
343
|
+
],
|
|
344
|
+
build: { copyPublicDir: false },
|
|
345
|
+
...resolvedPostCssConfig && { css: { postcss: resolvedPostCssConfig } },
|
|
346
|
+
envDir: options.cwd,
|
|
347
|
+
envPrefix: ["VITE_", "KIRBYUP_"],
|
|
348
|
+
customLogger: logger,
|
|
349
|
+
logLevel
|
|
350
|
+
};
|
|
351
|
+
if (command === "serve") {
|
|
352
|
+
const { port, watch } = options;
|
|
353
|
+
const userServerConfig = userConfig.server || {};
|
|
354
|
+
const resolvedPort = userServerConfig.port ?? port;
|
|
355
|
+
const inferredOrigin = userServerConfig.origin ?? resolveOriginFromServerOptions(userServerConfig, resolvedPort, "localhost");
|
|
356
|
+
const serveConfig = mergeConfig(sharedConfig, {
|
|
357
|
+
plugins: [kirbyupHmrPlugin(options), watch && fullReloadPlugin(watch)].filter(Boolean),
|
|
358
|
+
build: { rollupOptions: { input: resolve(options.cwd, options.entry) } },
|
|
359
|
+
server: {
|
|
360
|
+
port: resolvedPort,
|
|
361
|
+
strictPort: true,
|
|
362
|
+
origin: inferredOrigin
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
return mergeConfig(serveConfig, userConfig);
|
|
366
|
+
}
|
|
367
|
+
const mode = options.watch ? "development" : "production";
|
|
368
|
+
const buildConfig = mergeConfig(sharedConfig, {
|
|
369
|
+
mode,
|
|
370
|
+
plugins: [kirbyupBuildCleanupPlugin(options)],
|
|
371
|
+
build: {
|
|
372
|
+
lib: {
|
|
373
|
+
entry: resolve(options.cwd, options.entry),
|
|
374
|
+
formats: ["iife"],
|
|
375
|
+
name: "kirbyupExport",
|
|
376
|
+
fileName: () => "index.js"
|
|
377
|
+
},
|
|
378
|
+
minify: mode === "production",
|
|
379
|
+
outDir: options.outDir,
|
|
380
|
+
emptyOutDir: false,
|
|
381
|
+
rollupOptions: { output: { assetFileNames: "index.[ext]" } }
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
return mergeConfig(buildConfig, userConfig);
|
|
385
|
+
}
|
|
386
|
+
async function generate(options) {
|
|
387
|
+
const config = getViteConfig("build", options);
|
|
388
|
+
let result;
|
|
389
|
+
try {
|
|
390
|
+
result = await build(config);
|
|
391
|
+
} catch (error) {
|
|
392
|
+
consola.error(error);
|
|
393
|
+
if (config.mode === "production") throw error;
|
|
394
|
+
}
|
|
395
|
+
if (result && !options.watch) {
|
|
396
|
+
const { output } = toArray(result)[0];
|
|
397
|
+
let maxLength = 0;
|
|
398
|
+
for (const chunkFile in output) {
|
|
399
|
+
const fileNameLength = output[chunkFile].fileName.length;
|
|
400
|
+
if (fileNameLength > maxLength) maxLength = fileNameLength;
|
|
401
|
+
}
|
|
402
|
+
for (const { fileName, type, code } of output) {
|
|
403
|
+
const content = code || await fsp.readFile(resolve(options.outDir, fileName), "utf8");
|
|
404
|
+
await printFileInfo({
|
|
405
|
+
root: options.cwd,
|
|
406
|
+
outDir: options.outDir,
|
|
407
|
+
filePath: fileName,
|
|
408
|
+
content,
|
|
409
|
+
type,
|
|
410
|
+
maxLength
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
return result;
|
|
415
|
+
}
|
|
416
|
+
async function build$1(options) {
|
|
417
|
+
assertEntryExists(options);
|
|
418
|
+
const { cwd } = options;
|
|
419
|
+
const { config, configFile } = await loadConfig$1(cwd);
|
|
420
|
+
resolvedKirbyupConfig = config ?? {};
|
|
421
|
+
resolvedPostCssConfig = await resolvePostCSSConfig(cwd);
|
|
422
|
+
consola.log(colors.green(`${name} v${version}`));
|
|
423
|
+
consola.start(`Building ${colors.cyan(options.entry)}`);
|
|
424
|
+
const debouncedBuild = debounce(async () => {
|
|
425
|
+
generate(options).catch(handleError);
|
|
426
|
+
}, 100);
|
|
427
|
+
const startWatcher = async () => {
|
|
428
|
+
if (!options.watch) return;
|
|
429
|
+
const { watch } = await import("chokidar");
|
|
430
|
+
const ignored = ["**/{.git,node_modules}/**", "index.{css,js}"];
|
|
431
|
+
const watchPaths = typeof options.watch === "boolean" ? dirname(options.entry) : Array.isArray(options.watch) ? options.watch.filter((path) => typeof path === "string") : options.watch;
|
|
432
|
+
consola.info(`Watching for changes in ${toArray(watchPaths).map((i) => colors.cyan(i)).join(", ")}`);
|
|
433
|
+
const watcher = watch(watchPaths, {
|
|
434
|
+
ignoreInitial: true,
|
|
435
|
+
ignorePermissionErrors: true,
|
|
436
|
+
ignored,
|
|
437
|
+
cwd
|
|
438
|
+
});
|
|
439
|
+
if (configFile) watcher.add(configFile);
|
|
440
|
+
watcher.on("all", async (type, file) => {
|
|
441
|
+
const absolutePath = resolve(cwd, file);
|
|
442
|
+
if (configFile === absolutePath) {
|
|
443
|
+
resolvedKirbyupConfig = (await loadConfig$1(cwd)).config ?? {};
|
|
444
|
+
consola.info(`${colors.cyan(basename(file))} changed, setting new config`);
|
|
445
|
+
} else consola.log(`${colors.green(type)} ${colors.white(colors.dim(file))}`);
|
|
446
|
+
debouncedBuild();
|
|
447
|
+
});
|
|
448
|
+
};
|
|
449
|
+
await generate(options);
|
|
450
|
+
consola.success("Build successful");
|
|
451
|
+
startWatcher();
|
|
452
|
+
}
|
|
453
|
+
async function serve(options) {
|
|
454
|
+
assertEntryExists(options);
|
|
455
|
+
const { cwd } = options;
|
|
456
|
+
const { config } = await loadConfig$1(cwd);
|
|
457
|
+
resolvedKirbyupConfig = config ?? {};
|
|
458
|
+
resolvedPostCssConfig = await resolvePostCSSConfig(cwd);
|
|
459
|
+
consola.log(colors.green(`${name} v${version}`));
|
|
460
|
+
consola.info("Starting development server…");
|
|
461
|
+
const server = await createServer(getViteConfig("serve", options));
|
|
462
|
+
await server.listen();
|
|
463
|
+
consola.success(`Server is listening on :${server.config.server.port}`);
|
|
464
|
+
return server;
|
|
465
|
+
}
|
|
466
|
+
function assertEntryExists(options) {
|
|
467
|
+
if (!fs.existsSync(resolve(options.cwd, options.entry))) throw new PrettyError(`Cannot find "${options.entry}"`);
|
|
468
|
+
}
|
|
469
|
+
//#endregion
|
|
470
|
+
export { version as a, name as i, serve as n, handleError as r, build$1 as t };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { AliasOptions, InlineConfig } from "vite";
|
|
2
|
+
import "postcss";
|
|
3
|
+
//#region src/node/types.d.ts
|
|
4
|
+
interface BaseOptions {
|
|
5
|
+
cwd: string;
|
|
6
|
+
entry: string;
|
|
7
|
+
}
|
|
8
|
+
interface ServeOptions extends BaseOptions {
|
|
9
|
+
watch: false | string | string[];
|
|
10
|
+
port: number;
|
|
11
|
+
outDir?: string;
|
|
12
|
+
}
|
|
13
|
+
interface BuildOptions extends BaseOptions {
|
|
14
|
+
outDir: string;
|
|
15
|
+
watch: boolean | string | string[];
|
|
16
|
+
}
|
|
17
|
+
interface UserConfig {
|
|
18
|
+
/**
|
|
19
|
+
* Object or array of objects defining aliases that replace values in
|
|
20
|
+
* `import` statements. With either format, the order of the entries
|
|
21
|
+
* matters: the first defined rules are applied first.
|
|
22
|
+
*/
|
|
23
|
+
alias?: AliasOptions;
|
|
24
|
+
/**
|
|
25
|
+
* Additional Vite configuration, merged into kirbyup's defaults – for
|
|
26
|
+
* example, to define global constant replacements.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* export default defineConfig({
|
|
30
|
+
* vite: {
|
|
31
|
+
* define: {
|
|
32
|
+
* __TEST__: JSON.stringify(process.env.TEST === 'true'),
|
|
33
|
+
* },
|
|
34
|
+
* })
|
|
35
|
+
*/
|
|
36
|
+
vite?: InlineConfig;
|
|
37
|
+
/**
|
|
38
|
+
* @deprecated Use `vite` instead.
|
|
39
|
+
*/
|
|
40
|
+
extendViteConfig?: InlineConfig;
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
export { ServeOptions as n, UserConfig as r, BuildOptions as t };
|