vite-plugin-php 1.0.651 → 2.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/dist/index.cjs CHANGED
@@ -1,32 +1,60 @@
1
1
  'use strict';
2
2
 
3
- const require$$0$2 = require('fs');
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const node_child_process = require('node:child_process');
6
+ const url = require('url');
7
+ const node_path = require('node:path');
8
+ const require$$0 = require('os');
4
9
  const require$$0$1 = require('path');
5
- const vite = require('vite');
6
- const require$$0 = require('tty');
10
+ const require$$0$2 = require('util');
11
+ const require$$0$3 = require('stream');
12
+ const require$$0$5 = require('events');
13
+ const require$$0$4 = require('fs');
14
+ const node_fs = require('node:fs');
7
15
  const http = require('node:http');
8
- const child_process = require('child_process');
9
- const url = require('url');
10
- const require$$0$3 = require('os');
11
- const require$$0$4 = require('util');
12
- const require$$0$5 = require('stream');
13
- const require$$0$6 = require('events');
16
+ const vite = require('vite');
14
17
 
15
18
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
19
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
17
20
 
18
- const require$$0__default$5 = /*#__PURE__*/_interopDefaultCompat(require$$0$2);
19
- const require$$0__default$2 = /*#__PURE__*/_interopDefaultCompat(require$$0$1);
20
21
  const require$$0__default = /*#__PURE__*/_interopDefaultCompat(require$$0);
22
+ const require$$0__default$1 = /*#__PURE__*/_interopDefaultCompat(require$$0$1);
23
+ const require$$0__default$2 = /*#__PURE__*/_interopDefaultCompat(require$$0$2);
24
+ const require$$0__default$3 = /*#__PURE__*/_interopDefaultCompat(require$$0$3);
25
+ const require$$0__default$5 = /*#__PURE__*/_interopDefaultCompat(require$$0$5);
26
+ const require$$0__default$4 = /*#__PURE__*/_interopDefaultCompat(require$$0$4);
21
27
  const http__default = /*#__PURE__*/_interopDefaultCompat(http);
22
- const require$$0__default$1 = /*#__PURE__*/_interopDefaultCompat(require$$0$3);
23
- const require$$0__default$3 = /*#__PURE__*/_interopDefaultCompat(require$$0$4);
24
- const require$$0__default$4 = /*#__PURE__*/_interopDefaultCompat(require$$0$5);
25
- const require$$0__default$6 = /*#__PURE__*/_interopDefaultCompat(require$$0$6);
26
28
 
27
- function makeID() {
28
- return Date.now().toString(36) + Math.random() * 100;
29
- }
29
+ const EPHPError = {
30
+ ERROR: 1,
31
+ WARNING: 2,
32
+ PARSE: 4,
33
+ NOTICE: 8,
34
+ CORE_ERROR: 16,
35
+ CORE_WARNING: 32,
36
+ COMPILE_ERROR: 64,
37
+ COMPILE_WARNING: 128,
38
+ USER_ERROR: 256,
39
+ USER_WARNING: 512,
40
+ USER_NOTICE: 1024,
41
+ STRICT: 2048,
42
+ RECOVERABLE_ERROR: 4096,
43
+ DEPRECATED: 8192,
44
+ USER_DEPRECATED: 16384,
45
+ ALL: 32767
46
+ };
47
+
48
+ const internalParam = "__314159265359__";
49
+ const shared = {
50
+ viteConfig: void 0,
51
+ devConfig: {
52
+ cleanup: true,
53
+ errorLevels: EPHPError.ALL | EPHPError.STRICT
54
+ },
55
+ entries: [],
56
+ tempDir: ".php-tmp"
57
+ };
30
58
 
31
59
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
32
60
 
@@ -34,35 +62,21 @@ function getDefaultExportFromCjs (x) {
34
62
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
35
63
  }
36
64
 
37
- function commonjsRequire(path) {
38
- throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
39
- }
40
-
41
65
  var picocolors = {exports: {}};
42
66
 
43
- let argv = process.argv || [],
44
- env = process.env;
67
+ let p = process || {}, argv = p.argv || [], env = p.env || {};
45
68
  let isColorSupported =
46
- !("NO_COLOR" in env || argv.includes("--no-color")) &&
47
- ("FORCE_COLOR" in env ||
48
- argv.includes("--color") ||
49
- process.platform === "win32" ||
50
- (commonjsRequire != null && require$$0__default.isatty(1) && env.TERM !== "dumb") ||
51
- "CI" in env);
52
-
53
- let formatter =
54
- (open, close, replace = open) =>
69
+ !(!!env.NO_COLOR || argv.includes("--no-color")) &&
70
+ (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
71
+
72
+ let formatter = (open, close, replace = open) =>
55
73
  input => {
56
- let string = "" + input;
57
- let index = string.indexOf(close, open.length);
58
- return ~index
59
- ? open + replaceClose(string, close, replace, index) + close
60
- : open + string + close
74
+ let string = "" + input, index = string.indexOf(close, open.length);
75
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
61
76
  };
62
77
 
63
78
  let replaceClose = (string, close, replace, index) => {
64
- let result = "";
65
- let cursor = 0;
79
+ let result = "", cursor = 0;
66
80
  do {
67
81
  result += string.substring(cursor, index) + replace;
68
82
  cursor = index + close.length;
@@ -72,54 +86,54 @@ let replaceClose = (string, close, replace, index) => {
72
86
  };
73
87
 
74
88
  let createColors = (enabled = isColorSupported) => {
75
- let init = enabled ? formatter : () => String;
89
+ let f = enabled ? formatter : () => String;
76
90
  return {
77
91
  isColorSupported: enabled,
78
- reset: init("\x1b[0m", "\x1b[0m"),
79
- bold: init("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
80
- dim: init("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
81
- italic: init("\x1b[3m", "\x1b[23m"),
82
- underline: init("\x1b[4m", "\x1b[24m"),
83
- inverse: init("\x1b[7m", "\x1b[27m"),
84
- hidden: init("\x1b[8m", "\x1b[28m"),
85
- strikethrough: init("\x1b[9m", "\x1b[29m"),
86
-
87
- black: init("\x1b[30m", "\x1b[39m"),
88
- red: init("\x1b[31m", "\x1b[39m"),
89
- green: init("\x1b[32m", "\x1b[39m"),
90
- yellow: init("\x1b[33m", "\x1b[39m"),
91
- blue: init("\x1b[34m", "\x1b[39m"),
92
- magenta: init("\x1b[35m", "\x1b[39m"),
93
- cyan: init("\x1b[36m", "\x1b[39m"),
94
- white: init("\x1b[37m", "\x1b[39m"),
95
- gray: init("\x1b[90m", "\x1b[39m"),
96
-
97
- bgBlack: init("\x1b[40m", "\x1b[49m"),
98
- bgRed: init("\x1b[41m", "\x1b[49m"),
99
- bgGreen: init("\x1b[42m", "\x1b[49m"),
100
- bgYellow: init("\x1b[43m", "\x1b[49m"),
101
- bgBlue: init("\x1b[44m", "\x1b[49m"),
102
- bgMagenta: init("\x1b[45m", "\x1b[49m"),
103
- bgCyan: init("\x1b[46m", "\x1b[49m"),
104
- bgWhite: init("\x1b[47m", "\x1b[49m"),
105
-
106
- blackBright: init("\x1b[90m", "\x1b[39m"),
107
- redBright: init("\x1b[91m", "\x1b[39m"),
108
- greenBright: init("\x1b[92m", "\x1b[39m"),
109
- yellowBright: init("\x1b[93m", "\x1b[39m"),
110
- blueBright: init("\x1b[94m", "\x1b[39m"),
111
- magentaBright: init("\x1b[95m", "\x1b[39m"),
112
- cyanBright: init("\x1b[96m", "\x1b[39m"),
113
- whiteBright: init("\x1b[97m", "\x1b[39m"),
114
-
115
- bgBlackBright: init("\x1b[100m","\x1b[49m"),
116
- bgRedBright: init("\x1b[101m","\x1b[49m"),
117
- bgGreenBright: init("\x1b[102m","\x1b[49m"),
118
- bgYellowBright: init("\x1b[103m","\x1b[49m"),
119
- bgBlueBright: init("\x1b[104m","\x1b[49m"),
120
- bgMagentaBright: init("\x1b[105m","\x1b[49m"),
121
- bgCyanBright: init("\x1b[106m","\x1b[49m"),
122
- bgWhiteBright: init("\x1b[107m","\x1b[49m"),
92
+ reset: f("\x1b[0m", "\x1b[0m"),
93
+ bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
94
+ dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
95
+ italic: f("\x1b[3m", "\x1b[23m"),
96
+ underline: f("\x1b[4m", "\x1b[24m"),
97
+ inverse: f("\x1b[7m", "\x1b[27m"),
98
+ hidden: f("\x1b[8m", "\x1b[28m"),
99
+ strikethrough: f("\x1b[9m", "\x1b[29m"),
100
+
101
+ black: f("\x1b[30m", "\x1b[39m"),
102
+ red: f("\x1b[31m", "\x1b[39m"),
103
+ green: f("\x1b[32m", "\x1b[39m"),
104
+ yellow: f("\x1b[33m", "\x1b[39m"),
105
+ blue: f("\x1b[34m", "\x1b[39m"),
106
+ magenta: f("\x1b[35m", "\x1b[39m"),
107
+ cyan: f("\x1b[36m", "\x1b[39m"),
108
+ white: f("\x1b[37m", "\x1b[39m"),
109
+ gray: f("\x1b[90m", "\x1b[39m"),
110
+
111
+ bgBlack: f("\x1b[40m", "\x1b[49m"),
112
+ bgRed: f("\x1b[41m", "\x1b[49m"),
113
+ bgGreen: f("\x1b[42m", "\x1b[49m"),
114
+ bgYellow: f("\x1b[43m", "\x1b[49m"),
115
+ bgBlue: f("\x1b[44m", "\x1b[49m"),
116
+ bgMagenta: f("\x1b[45m", "\x1b[49m"),
117
+ bgCyan: f("\x1b[46m", "\x1b[49m"),
118
+ bgWhite: f("\x1b[47m", "\x1b[49m"),
119
+
120
+ blackBright: f("\x1b[90m", "\x1b[39m"),
121
+ redBright: f("\x1b[91m", "\x1b[39m"),
122
+ greenBright: f("\x1b[92m", "\x1b[39m"),
123
+ yellowBright: f("\x1b[93m", "\x1b[39m"),
124
+ blueBright: f("\x1b[94m", "\x1b[39m"),
125
+ magentaBright: f("\x1b[95m", "\x1b[39m"),
126
+ cyanBright: f("\x1b[96m", "\x1b[39m"),
127
+ whiteBright: f("\x1b[97m", "\x1b[39m"),
128
+
129
+ bgBlackBright: f("\x1b[100m", "\x1b[49m"),
130
+ bgRedBright: f("\x1b[101m", "\x1b[49m"),
131
+ bgGreenBright: f("\x1b[102m", "\x1b[49m"),
132
+ bgYellowBright: f("\x1b[103m", "\x1b[49m"),
133
+ bgBlueBright: f("\x1b[104m", "\x1b[49m"),
134
+ bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
135
+ bgCyanBright: f("\x1b[106m", "\x1b[49m"),
136
+ bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
123
137
  }
124
138
  };
125
139
 
@@ -129,136 +143,130 @@ picocolors.exports.createColors = createColors;
129
143
  var picocolorsExports = picocolors.exports;
130
144
  const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
131
145
 
132
- function resolveEnvPrefix({ envPrefix = "VITE_" }) {
133
- envPrefix = Array.isArray(envPrefix) ? envPrefix : [envPrefix];
134
- if (envPrefix.includes("")) {
135
- throw new Error(
136
- `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
137
- );
146
+ function hasViteConfig(input) {
147
+ if (!input) {
148
+ throw new Error("Vite config not initialized!");
138
149
  }
139
- return envPrefix;
140
150
  }
141
- const envPattern = /%(\S+?)%/g;
142
- function initReplaceEnv(config) {
143
- const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
144
- const env = { ...config.env };
145
- for (const key in config.define) {
146
- if (key.startsWith(`import.meta.env.`)) {
147
- const val = config.define[key];
148
- if (typeof val === "string") {
149
- try {
150
- const parsed = JSON.parse(val);
151
- env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
152
- } catch {
153
- env[key.slice(16)] = val;
154
- }
155
- } else {
156
- env[key.slice(16)] = JSON.stringify(val);
157
- }
158
- }
151
+
152
+ function log(message, { type = "info", prefix = true, ...options } = {}) {
153
+ hasViteConfig(shared.viteConfig);
154
+ let output = "";
155
+ if (prefix) {
156
+ output += colors.bgMagenta(colors.white("\u2009php\u2009")) + " ";
159
157
  }
160
- return function replaceEnv(content, filename) {
161
- return content.replace(envPattern, (text, key) => {
162
- if (key in env) {
163
- return env[key];
164
- } else {
165
- if (envPrefix.some((prefix) => key.startsWith(prefix))) {
166
- const relativeHtml = vite.normalizePath(
167
- require$$0$1.relative(config.root, filename)
168
- );
169
- config.logger.warn(
170
- colors.yellow(
171
- colors.bold(
172
- `(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
173
- )
174
- )
175
- );
176
- }
177
- return text;
178
- }
179
- });
180
- };
158
+ output += message;
159
+ shared.viteConfig.logger[type](output, options);
181
160
  }
182
-
183
- function writeFile(file, data) {
184
- require$$0$2.mkdirSync(require$$0$1.dirname(file), { recursive: true });
185
- require$$0$2.writeFileSync(file, data);
186
- }
187
-
188
- const phpTagPattern = /<\?(?:php|).+?(\?>|$)/gis;
189
- function escapePHP({ inputFile, config }) {
190
- const replaceEnv = initReplaceEnv(config);
191
- const input = require$$0$2.readFileSync(inputFile, "utf-8").toString();
192
- const phpCodes = {};
193
- const isJS = inputFile.includes(".js") || inputFile.includes(".ts");
194
- const isML = inputFile.includes(".php") || inputFile.includes(".htm");
195
- const escapedCode = input.replace(phpTagPattern, (match) => {
196
- let token = makeID();
197
- if (isJS) {
198
- token = `/*${token}*/`;
199
- } else if (isML) {
200
- token = `<!--${token}-->`;
201
- }
202
- phpCodes[token] = replaceEnv(match, inputFile);
203
- return token;
204
- });
205
- return {
206
- escapedCode,
207
- phpCodes,
208
- write(outputFile) {
209
- writeFile(outputFile, escapedCode);
210
- writeFile(outputFile + ".json", JSON.stringify(phpCodes));
161
+ log.error = function(json, options = {}) {
162
+ let output = json;
163
+ let type = "info";
164
+ try {
165
+ const data = JSON.parse(json);
166
+ output = "";
167
+ switch (data.code) {
168
+ case EPHPError.PARSE:
169
+ case EPHPError.ERROR:
170
+ case EPHPError.CORE_ERROR:
171
+ case EPHPError.COMPILE_ERROR:
172
+ case EPHPError.USER_ERROR:
173
+ type = "error";
174
+ output += colors.bgRedBright(colors.white("Fatal Error"));
175
+ break;
176
+ case EPHPError.WARNING:
177
+ case EPHPError.USER_WARNING:
178
+ case EPHPError.COMPILE_WARNING:
179
+ case EPHPError.RECOVERABLE_ERROR:
180
+ type = "warn";
181
+ output += colors.yellowBright("Warning");
182
+ break;
183
+ case EPHPError.NOTICE:
184
+ case EPHPError.USER_NOTICE:
185
+ type = "info";
186
+ output += colors.bgWhite(colors.black("Notice"));
187
+ break;
188
+ case EPHPError.STRICT:
189
+ type = "info";
190
+ output += colors.yellow("Strict");
191
+ break;
192
+ case EPHPError.DEPRECATED:
193
+ case EPHPError.USER_DEPRECATED:
194
+ type = "info";
195
+ output += colors.cyan("Deprecated");
196
+ break;
197
+ default:
198
+ break;
211
199
  }
212
- };
213
- }
214
- function unescapePHP({ escapedCode, phpCodes }) {
215
- let out = escapedCode;
216
- Object.entries(phpCodes).forEach(([token, code]) => {
217
- out = out.replace(token, (match) => {
218
- return `${code}`;
219
- });
220
- });
221
- return out;
222
- }
200
+ output += " " + data.message + "\r\n";
201
+ output += " In: " + data.file.replace(
202
+ node_path.resolve(shared.tempDir),
203
+ shared.viteConfig?.root
204
+ ) + "\r\n";
205
+ output += " On line: " + data.line;
206
+ } catch (error) {
207
+ }
208
+ log(output, { ...options, type });
209
+ };
223
210
 
211
+ const PHP_Server = {
212
+ binary: "php",
213
+ port: 65535,
214
+ process: void 0,
215
+ start,
216
+ stop
217
+ };
224
218
  function start(root) {
225
- if (!globalThis.php?.pid) {
219
+ if (!PHP_Server.process?.pid) {
226
220
  const routerFileUrl = new URL("./router.php", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
227
- globalThis.php = child_process.spawn(phpServer.binary, [
221
+ PHP_Server.process = node_child_process.spawn(PHP_Server.binary, [
228
222
  "-S",
229
- "localhost:" + phpServer.port,
223
+ "localhost:" + PHP_Server.port,
230
224
  "-t",
231
225
  root,
232
226
  url.fileURLToPath(routerFileUrl)
233
227
  ]).once("spawn", () => {
234
- console.log(
235
- `PHP development server started (PID: ${globalThis.php?.pid})`
236
- );
228
+ log(`Server started (PID: ${PHP_Server.process?.pid})`);
237
229
  }).on("error", (error) => {
238
- console.error("PHP dev-server error: " + error.message);
239
- }).on("close", (code) => {
240
- console.log(`PHP development server stopped (Code: ${code})`);
230
+ log(`Server error: ${error.message})`, {
231
+ type: "error"
232
+ });
233
+ });
234
+ PHP_Server.process.stdout?.on("data", (data) => {
235
+ log("", { timestamp: true });
236
+ `${data}`.trim().split("\r\n").forEach((line) => {
237
+ if (line.startsWith(internalParam + ":")) {
238
+ log.error(
239
+ line.substring((internalParam + ":").length),
240
+ { prefix: false }
241
+ );
242
+ } else {
243
+ log(line);
244
+ }
245
+ });
241
246
  });
242
247
  }
243
248
  }
244
- function stop() {
245
- if (globalThis.php) {
246
- globalThis.php.stdin?.end();
247
- globalThis.php.stdout?.destroy();
248
- globalThis.php.stderr?.destroy();
249
- if (globalThis.php.kill()) {
250
- console.log("PHP development server killed");
249
+ function stop(callBack) {
250
+ if (PHP_Server.process) {
251
+ PHP_Server.process.on("close", (code) => {
252
+ log("Ended with: " + code);
253
+ PHP_Server.process = void 0;
254
+ callBack();
255
+ });
256
+ PHP_Server.process.stdin?.destroy();
257
+ PHP_Server.process.stdout?.destroy();
258
+ PHP_Server.process.stderr?.destroy();
259
+ if (PHP_Server.process.kill()) {
260
+ log("Shutting down");
251
261
  } else {
252
- console.error("Attention! Failed to kill PHP development server!");
262
+ log("Failed to send SIGTERM", {
263
+ type: "error"
264
+ });
253
265
  }
266
+ } else {
267
+ callBack();
254
268
  }
255
269
  }
256
- const phpServer = {
257
- binary: "php",
258
- port: 65535,
259
- start,
260
- stop
261
- };
262
270
 
263
271
  var tasks = {};
264
272
 
@@ -322,8 +330,8 @@ var path$9 = {};
322
330
 
323
331
  Object.defineProperty(path$9, "__esModule", { value: true });
324
332
  path$9.convertPosixPathToPattern = path$9.convertWindowsPathToPattern = path$9.convertPathToPattern = path$9.escapePosixPath = path$9.escapeWindowsPath = path$9.escape = path$9.removeLeadingDotSegment = path$9.makeAbsolute = path$9.unixify = void 0;
325
- const os = require$$0__default$1;
326
- const path$8 = require$$0__default$2;
333
+ const os = require$$0__default;
334
+ const path$8 = require$$0__default$1;
327
335
  const IS_WINDOWS_PLATFORM = os.platform() === 'win32';
328
336
  const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
329
337
  /**
@@ -563,8 +571,8 @@ var isGlob$1 = function isGlob(str, options) {
563
571
  };
564
572
 
565
573
  var isGlob = isGlob$1;
566
- var pathPosixDirname = require$$0__default$2.posix.dirname;
567
- var isWin32 = require$$0__default$1.platform() === 'win32';
574
+ var pathPosixDirname = require$$0__default$1.posix.dirname;
575
+ var isWin32 = require$$0__default.platform() === 'win32';
568
576
 
569
577
  var slash = '/';
570
578
  var backslash = /\\/g;
@@ -1060,7 +1068,7 @@ var toRegexRange_1 = toRegexRange$1;
1060
1068
  * Licensed under the MIT License.
1061
1069
  */
1062
1070
 
1063
- const util$1 = require$$0__default$3;
1071
+ const util$1 = require$$0__default$2;
1064
1072
  const toRegexRange = toRegexRange_1;
1065
1073
 
1066
1074
  const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
@@ -2025,7 +2033,7 @@ var braces_1 = braces$1;
2025
2033
 
2026
2034
  var utils$f = {};
2027
2035
 
2028
- const path$7 = require$$0__default$2;
2036
+ const path$7 = require$$0__default$1;
2029
2037
  const WIN_SLASH = '\\\\/';
2030
2038
  const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
2031
2039
 
@@ -2205,7 +2213,7 @@ var constants$3 = {
2205
2213
 
2206
2214
  (function (exports) {
2207
2215
 
2208
- const path = require$$0__default$2;
2216
+ const path = require$$0__default$1;
2209
2217
  const win32 = process.platform === 'win32';
2210
2218
  const {
2211
2219
  REGEX_BACKSLASH,
@@ -3749,7 +3757,7 @@ parse$1.fastpaths = (input, options) => {
3749
3757
 
3750
3758
  var parse_1 = parse$1;
3751
3759
 
3752
- const path$6 = require$$0__default$2;
3760
+ const path$6 = require$$0__default$1;
3753
3761
  const scan = scan_1;
3754
3762
  const parse = parse_1;
3755
3763
  const utils$c = utils$f;
@@ -4092,7 +4100,7 @@ var picomatch_1 = picomatch$2;
4092
4100
 
4093
4101
  var picomatch$1 = picomatch_1;
4094
4102
 
4095
- const util = require$$0__default$3;
4103
+ const util = require$$0__default$2;
4096
4104
  const braces = braces_1;
4097
4105
  const picomatch = picomatch$1;
4098
4106
  const utils$b = utils$f;
@@ -4560,7 +4568,7 @@ var micromatch_1 = micromatch$1;
4560
4568
 
4561
4569
  Object.defineProperty(pattern$1, "__esModule", { value: true });
4562
4570
  pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
4563
- const path$5 = require$$0__default$2;
4571
+ const path$5 = require$$0__default$1;
4564
4572
  const globParent = globParent$1;
4565
4573
  const micromatch = micromatch_1;
4566
4574
  const GLOBSTAR = '**';
@@ -4755,7 +4763,7 @@ var stream$4 = {};
4755
4763
  * Copyright (c) 2014-2020 Teambition
4756
4764
  * Licensed under the MIT license.
4757
4765
  */
4758
- const Stream = require$$0__default$4;
4766
+ const Stream = require$$0__default$3;
4759
4767
  const PassThrough = Stream.PassThrough;
4760
4768
  const slice = Array.prototype.slice;
4761
4769
 
@@ -5135,7 +5143,7 @@ var fs$5 = {};
5135
5143
  (function (exports) {
5136
5144
  Object.defineProperty(exports, "__esModule", { value: true });
5137
5145
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
5138
- const fs = require$$0__default$5;
5146
+ const fs = require$$0__default$4;
5139
5147
  exports.FILE_SYSTEM_ADAPTER = {
5140
5148
  lstat: fs.lstat,
5141
5149
  stat: fs.stat,
@@ -5486,7 +5494,7 @@ var fs$1 = {};
5486
5494
  (function (exports) {
5487
5495
  Object.defineProperty(exports, "__esModule", { value: true });
5488
5496
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
5489
- const fs = require$$0__default$5;
5497
+ const fs = require$$0__default$4;
5490
5498
  exports.FILE_SYSTEM_ADAPTER = {
5491
5499
  lstat: fs.lstat,
5492
5500
  stat: fs.stat,
@@ -5505,7 +5513,7 @@ var fs$1 = {};
5505
5513
  } (fs$1));
5506
5514
 
5507
5515
  Object.defineProperty(settings$2, "__esModule", { value: true });
5508
- const path$3 = require$$0__default$2;
5516
+ const path$3 = require$$0__default$1;
5509
5517
  const fsStat$3 = out$1;
5510
5518
  const fs = fs$1;
5511
5519
  let Settings$1 = class Settings {
@@ -5947,7 +5955,7 @@ let Reader$1 = class Reader {
5947
5955
  reader$1.default = Reader$1;
5948
5956
 
5949
5957
  Object.defineProperty(async$4, "__esModule", { value: true });
5950
- const events_1 = require$$0__default$6;
5958
+ const events_1 = require$$0__default$5;
5951
5959
  const fsScandir$2 = out$2;
5952
5960
  const fastq = queueExports;
5953
5961
  const common$1 = common$3;
@@ -6076,7 +6084,7 @@ function callSuccessCallback(callback, entries) {
6076
6084
  var stream$2 = {};
6077
6085
 
6078
6086
  Object.defineProperty(stream$2, "__esModule", { value: true });
6079
- const stream_1$5 = require$$0__default$4;
6087
+ const stream_1$5 = require$$0__default$3;
6080
6088
  const async_1$3 = async$4;
6081
6089
  class StreamProvider {
6082
6090
  constructor(_root, _settings) {
@@ -6189,7 +6197,7 @@ sync$3.default = SyncProvider;
6189
6197
  var settings$1 = {};
6190
6198
 
6191
6199
  Object.defineProperty(settings$1, "__esModule", { value: true });
6192
- const path$2 = require$$0__default$2;
6200
+ const path$2 = require$$0__default$1;
6193
6201
  const fsScandir = out$2;
6194
6202
  class Settings {
6195
6203
  constructor(_options = {}) {
@@ -6251,7 +6259,7 @@ function getSettings(settingsOrOptions = {}) {
6251
6259
  var reader = {};
6252
6260
 
6253
6261
  Object.defineProperty(reader, "__esModule", { value: true });
6254
- const path$1 = require$$0__default$2;
6262
+ const path$1 = require$$0__default$1;
6255
6263
  const fsStat$2 = out$1;
6256
6264
  const utils$6 = utils$k;
6257
6265
  class Reader {
@@ -6286,7 +6294,7 @@ reader.default = Reader;
6286
6294
  var stream$1 = {};
6287
6295
 
6288
6296
  Object.defineProperty(stream$1, "__esModule", { value: true });
6289
- const stream_1$3 = require$$0__default$4;
6297
+ const stream_1$3 = require$$0__default$3;
6290
6298
  const fsStat$1 = out$1;
6291
6299
  const fsWalk$2 = out$3;
6292
6300
  const reader_1$2 = reader;
@@ -6639,7 +6647,7 @@ class EntryTransformer {
6639
6647
  entry.default = EntryTransformer;
6640
6648
 
6641
6649
  Object.defineProperty(provider, "__esModule", { value: true });
6642
- const path = require$$0__default$2;
6650
+ const path = require$$0__default$1;
6643
6651
  const deep_1 = deep;
6644
6652
  const entry_1 = entry$1;
6645
6653
  const error_1 = error;
@@ -6712,7 +6720,7 @@ async$7.default = ProviderAsync;
6712
6720
  var stream = {};
6713
6721
 
6714
6722
  Object.defineProperty(stream, "__esModule", { value: true });
6715
- const stream_1$1 = require$$0__default$4;
6723
+ const stream_1$1 = require$$0__default$3;
6716
6724
  const stream_2 = stream$1;
6717
6725
  const provider_1$1 = provider;
6718
6726
  class ProviderStream extends provider_1$1.default {
@@ -6817,8 +6825,8 @@ var settings = {};
6817
6825
  (function (exports) {
6818
6826
  Object.defineProperty(exports, "__esModule", { value: true });
6819
6827
  exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
6820
- const fs = require$$0__default$5;
6821
- const os = require$$0__default$1;
6828
+ const fs = require$$0__default$4;
6829
+ const os = require$$0__default;
6822
6830
  /**
6823
6831
  * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
6824
6832
  * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
@@ -6977,7 +6985,8 @@ var out = FastGlob;
6977
6985
 
6978
6986
  const fastGlob = /*@__PURE__*/getDefaultExportFromCjs(out);
6979
6987
 
6980
- function consoleHijack(entries) {
6988
+ function consoleHijack() {
6989
+ const entries = shared.entries;
6981
6990
  ["log", "info", "warn", "error"].forEach((command) => {
6982
6991
  const cx = console[command];
6983
6992
  console[command] = function(...args) {
@@ -6993,292 +7002,458 @@ function consoleHijack(entries) {
6993
7002
  });
6994
7003
  }
6995
7004
 
6996
- const internalParam = "__314159265359__";
6997
- function usePHP(cfg = {}) {
6998
- const {
6999
- binary = "php",
7000
- entry = "index.php",
7001
- rewriteUrl = (requestUrl) => requestUrl,
7002
- tempDir = ".php-tmp",
7003
- cleanup = {}
7004
- } = cfg;
7005
- const { dev: devCleanup = true } = cleanup;
7006
- phpServer.binary = binary;
7007
- let config = void 0;
7008
- let viteServer = void 0;
7009
- let entries = Array.isArray(entry) ? entry : [entry];
7010
- function getTempFileName(file) {
7011
- return `${tempDir}/${file}.html`;
7012
- }
7013
- function cleanupTemp() {
7014
- require$$0$2.rmSync(tempDir, { recursive: true, force: true });
7015
- }
7016
- function onExit() {
7017
- if (config?.command === "serve") {
7018
- phpServer.stop();
7019
- devCleanup && cleanupTemp();
7020
- }
7021
- process.exit();
7022
- }
7023
- [
7024
- "exit",
7025
- "SIGINT",
7026
- "SIGUSR1",
7027
- "SIGUSR2",
7028
- "uncaughtException",
7029
- "SIGTERM"
7030
- ].forEach((eventType) => {
7031
- process.on(eventType, onExit.bind(null));
7005
+ function readFile(file) {
7006
+ return node_fs.readFileSync(file, "utf-8").toString();
7007
+ }
7008
+ function writeFile(file, data) {
7009
+ node_fs.mkdirSync(node_path.dirname(file), { recursive: true });
7010
+ node_fs.writeFileSync(file, data);
7011
+ }
7012
+
7013
+ function makeID() {
7014
+ return Date.now().toString(36) + Math.random() * 100;
7015
+ }
7016
+
7017
+ function resolveEnvPrefix({ envPrefix = "VITE_" }) {
7018
+ envPrefix = Array.isArray(envPrefix) ? envPrefix : [envPrefix];
7019
+ if (envPrefix.includes("")) {
7020
+ throw new Error(
7021
+ `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
7022
+ );
7023
+ }
7024
+ return envPrefix;
7025
+ }
7026
+ const envPattern = /%(\S+?)%/g;
7027
+ function initReplaceEnv() {
7028
+ hasViteConfig(shared.viteConfig);
7029
+ const { env, define, root, logger } = shared.viteConfig;
7030
+ const envPrefix = resolveEnvPrefix({
7031
+ envPrefix: shared.viteConfig.envPrefix
7032
+ });
7033
+ for (const key in define) {
7034
+ if (key.startsWith(`import.meta.env.`)) {
7035
+ const val = define[key];
7036
+ if (typeof val === "string") {
7037
+ try {
7038
+ const parsed = JSON.parse(val);
7039
+ env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
7040
+ } catch {
7041
+ env[key.slice(16)] = val;
7042
+ }
7043
+ } else {
7044
+ env[key.slice(16)] = JSON.stringify(val);
7045
+ }
7046
+ }
7047
+ }
7048
+ return function replaceEnv(content, filename) {
7049
+ const relativeHtml = vite.normalizePath(node_path.relative(root, filename));
7050
+ return content.replace(envPattern, (text, key) => {
7051
+ if (key in env) {
7052
+ return env[key];
7053
+ } else {
7054
+ if (envPrefix.some((prefix) => key.startsWith(prefix))) {
7055
+ logger.warn(
7056
+ colors.yellow(
7057
+ colors.bold(
7058
+ `(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
7059
+ )
7060
+ )
7061
+ );
7062
+ }
7063
+ return text;
7064
+ }
7065
+ });
7066
+ };
7067
+ }
7068
+
7069
+ var __defProp = Object.defineProperty;
7070
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7071
+ var __publicField = (obj, key, value) => {
7072
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7073
+ return value;
7074
+ };
7075
+ const phpStartPattern = `<\\?(?:php|)`;
7076
+ const phpEndPattern = `\\?>`;
7077
+ const phpTagRegex = new RegExp(
7078
+ `${phpStartPattern}.+?(${phpEndPattern}|$)`,
7079
+ "gis"
7080
+ );
7081
+ class PHP_Code {
7082
+ constructor(code) {
7083
+ __publicField(this, "file", "!!__VIRTUAL__!!.php");
7084
+ __publicField(this, "code");
7085
+ __publicField(this, "mapping", {});
7086
+ this.code = code;
7087
+ return this;
7088
+ }
7089
+ static fromFile(file) {
7090
+ const inst = new this(readFile(file));
7091
+ inst.file = file;
7092
+ return inst;
7093
+ }
7094
+ applyEnv() {
7095
+ const replaceEnv = initReplaceEnv();
7096
+ this.code = replaceEnv(this.code, this.file || "");
7097
+ return this;
7098
+ }
7099
+ escape() {
7100
+ const isJS = this.file.includes(".js") || this.file.includes(".ts");
7101
+ const isML = this.file.includes(".php") || this.file.includes(".htm");
7102
+ this.code = this.code.replace(phpTagRegex, (match) => {
7103
+ let token = makeID();
7104
+ if (isJS) {
7105
+ token = `/*${token}*/`;
7106
+ } else if (isML) {
7107
+ token = `\u2400\u2400${token}\u2400\u2400`;
7108
+ }
7109
+ this.mapping[token] = match;
7110
+ return token;
7111
+ });
7112
+ return this;
7113
+ }
7114
+ write(file, mapping = false) {
7115
+ writeFile(file, this.code);
7116
+ mapping && writeFile(file + ".json", JSON.stringify(this.mapping));
7117
+ }
7118
+ static unescape(code, mapping) {
7119
+ let out = code;
7120
+ Object.entries(mapping).forEach(([token, code2]) => {
7121
+ out = out.replace(token, code2);
7122
+ });
7123
+ return out;
7124
+ }
7125
+ }
7126
+
7127
+ const serve = {
7128
+ rewriteUrl: (url) => url
7129
+ };
7130
+ function tempName(entry) {
7131
+ return `${shared.tempDir}/${entry}`;
7132
+ }
7133
+ const servePlugin = {
7134
+ name: "serve-php",
7135
+ apply: "serve",
7136
+ enforce: "post",
7137
+ configResolved() {
7138
+ function handleExit(signal) {
7139
+ if (signal === "SIGINT") {
7140
+ console.log();
7141
+ }
7142
+ const tempDir = node_path.resolve(shared.tempDir);
7143
+ if (shared.devConfig.cleanup && node_fs.existsSync(tempDir)) {
7144
+ log("Removing temporary files");
7145
+ node_fs.rmSync(tempDir, {
7146
+ recursive: true,
7147
+ force: true
7148
+ });
7149
+ }
7150
+ if (PHP_Server.process && shared.viteConfig?.command === "serve") {
7151
+ PHP_Server.stop(() => {
7152
+ process.exit();
7153
+ });
7154
+ } else {
7155
+ process.exit();
7156
+ }
7157
+ }
7158
+ [
7159
+ "exit",
7160
+ "SIGINT",
7161
+ "SIGUSR1",
7162
+ "SIGUSR2",
7163
+ "uncaughtException",
7164
+ "SIGTERM"
7165
+ ].forEach((eventType) => {
7166
+ new Promise((resolve2) => process.on(eventType, resolve2)).then(
7167
+ handleExit
7168
+ );
7169
+ });
7170
+ const gitIgnoreFile = node_path.resolve(`${shared.tempDir}/.gitignore`);
7171
+ if (!node_fs.existsSync(gitIgnoreFile)) {
7172
+ writeFile(gitIgnoreFile, "*\r\n**/*");
7173
+ }
7174
+ shared.entries.forEach((entry) => {
7175
+ PHP_Code.fromFile(entry).applyEnv().write(tempName(entry));
7176
+ });
7177
+ },
7178
+ configureServer(server) {
7179
+ if (!PHP_Server.process) {
7180
+ PHP_Server.start(server?.config.root);
7181
+ }
7182
+ server.middlewares.use(async (req, res, next) => {
7183
+ try {
7184
+ if (req.url && !["/@vite", "/@fs", "/@id/__x00__", "/node_modules"].some(
7185
+ (path) => req.url.startsWith(path)
7186
+ )) {
7187
+ req.on("error", (error) => {
7188
+ throw error;
7189
+ });
7190
+ const url = new URL(req.url, "http://localhost");
7191
+ if (shared.viteConfig?.server.port) {
7192
+ url.port = shared.viteConfig.server.port.toString();
7193
+ }
7194
+ const requestUrl = url.pathname;
7195
+ if (url.pathname.endsWith("/")) {
7196
+ url.pathname += "index.php";
7197
+ }
7198
+ const routedUrl = serve.rewriteUrl(url);
7199
+ if (routedUrl) {
7200
+ url.pathname = routedUrl.pathname;
7201
+ url.search = routedUrl.search;
7202
+ url.hash = routedUrl.hash;
7203
+ }
7204
+ const entryPathname = url.pathname.substring(1);
7205
+ const entry = shared.entries.find((file) => {
7206
+ return file === entryPathname || file.substring(0, file.lastIndexOf(".")) === entryPathname;
7207
+ });
7208
+ if (entry) {
7209
+ const tempFile = tempName(entry);
7210
+ if (node_fs.existsSync(node_path.resolve(tempFile))) {
7211
+ url.pathname = tempFile;
7212
+ url.port = PHP_Server.port.toString();
7213
+ url.searchParams.set(
7214
+ internalParam,
7215
+ new URLSearchParams({
7216
+ $REQUEST_URI: requestUrl,
7217
+ $PHP_SELF: "/" + entry,
7218
+ temp_dir: shared.tempDir,
7219
+ error_levels: shared.devConfig.errorLevels.toString()
7220
+ }).toString()
7221
+ );
7222
+ const body = await new Promise(
7223
+ (resolve2, reject) => {
7224
+ let data = [];
7225
+ req.on("data", (chunk) => {
7226
+ data.push(chunk);
7227
+ }).on("end", () => {
7228
+ resolve2(Buffer.concat(data));
7229
+ });
7230
+ }
7231
+ );
7232
+ const phpResult = await new Promise(async (resolve2, reject) => {
7233
+ const chunks = [];
7234
+ let statusCode;
7235
+ let incomingHeaders = {};
7236
+ const request = http__default.request(
7237
+ url.toString(),
7238
+ {
7239
+ method: req.method,
7240
+ headers: {
7241
+ ...req.headers,
7242
+ "content-length": Buffer.byteLength(body)
7243
+ }
7244
+ },
7245
+ (msg) => {
7246
+ statusCode = msg.statusCode;
7247
+ incomingHeaders = msg.headers;
7248
+ msg.on("data", (data) => {
7249
+ chunks.push(data);
7250
+ });
7251
+ }
7252
+ ).on("error", (error) => {
7253
+ reject(error);
7254
+ }).on("close", () => {
7255
+ const content = Buffer.concat(chunks).toString(
7256
+ "utf8"
7257
+ );
7258
+ resolve2({
7259
+ statusCode,
7260
+ headers: incomingHeaders,
7261
+ content
7262
+ });
7263
+ });
7264
+ request.write(body, (error) => {
7265
+ if (error) {
7266
+ reject(error);
7267
+ }
7268
+ });
7269
+ request.end();
7270
+ });
7271
+ let out = phpResult.content;
7272
+ if (phpResult.headers["content-type"]?.includes(
7273
+ "html"
7274
+ )) {
7275
+ out = await server.transformIndexHtml(
7276
+ `/${entry}.html`,
7277
+ out,
7278
+ requestUrl
7279
+ );
7280
+ }
7281
+ res.writeHead(
7282
+ phpResult.statusCode || 200,
7283
+ phpResult.headers
7284
+ ).end(out);
7285
+ return;
7286
+ }
7287
+ }
7288
+ }
7289
+ } catch (error) {
7290
+ console.error("Vite-PHP Error: " + error);
7291
+ }
7292
+ next();
7293
+ });
7294
+ },
7295
+ handleHotUpdate({ server, file }) {
7296
+ const entry = shared.entries.find(
7297
+ (entryFile) => node_path.resolve(entryFile) === node_path.resolve(file)
7298
+ );
7299
+ if (entry) {
7300
+ PHP_Code.fromFile(entry).applyEnv().write(tempName(entry));
7301
+ server.moduleGraph.invalidateAll();
7302
+ }
7303
+ if (entry || !file.startsWith(node_path.resolve(shared.tempDir)) && file.includes(".php")) {
7304
+ server.ws.send({
7305
+ type: "full-reload"
7306
+ });
7307
+ }
7308
+ }
7309
+ };
7310
+
7311
+ const assetsPattern = new RegExp(
7312
+ `^(.+?)(${phpStartPattern}\\s+namespace\\s\\S+?(?:\\s*;|\\s*{).+)$`,
7313
+ "si"
7314
+ );
7315
+ const lastTagPattern = new RegExp(`^(.+(?:</.+?>|<.+?/>))(.+|)$`, "si");
7316
+ const closingPattern = new RegExp(`^(.+)(${phpStartPattern}.+)$`, "si");
7317
+ function fixAssetsInjection(input) {
7318
+ let out = input;
7319
+ let assets = "";
7320
+ out = out.replace(assetsPattern, (match, p1, p2) => {
7321
+ assets = p1.trim();
7322
+ return p2;
7032
7323
  });
7324
+ const injectAssets = (_, part1, part2) => {
7325
+ let a = assets;
7326
+ if (!(part1.endsWith("\n") || part1.endsWith("\r"))) {
7327
+ a = "\r\n" + a;
7328
+ }
7329
+ if (!(part2.startsWith("\n") || part2.startsWith("\r"))) {
7330
+ a += "\r\n";
7331
+ }
7332
+ assets = "";
7333
+ return `${part1}${a}${part2}`;
7334
+ };
7335
+ if (assets) {
7336
+ out = out.replace(lastTagPattern, injectAssets);
7337
+ }
7338
+ if (assets) {
7339
+ out = out.replace(closingPattern, injectAssets);
7340
+ }
7341
+ if (assets) {
7342
+ out += assets;
7343
+ }
7344
+ return out;
7345
+ }
7346
+
7347
+ const buildPlugin = {
7348
+ name: "build-php",
7349
+ apply: "build",
7350
+ enforce: "pre",
7351
+ resolveId(source, importer, options) {
7352
+ if (shared.entries.includes(source)) {
7353
+ return {
7354
+ // Rename ids because Vite transforms only .html files: https://github.com/vitejs/vite/blob/0cde495ebeb48bcfb5961784a30bfaed997790a0/packages/vite/src/node/plugins/html.ts#L330
7355
+ id: `${source}.html`,
7356
+ resolvedBy: "vite-plugin-php",
7357
+ meta: {
7358
+ originalId: source
7359
+ }
7360
+ };
7361
+ }
7362
+ },
7363
+ load(id, options) {
7364
+ const moduleInfo = this.getModuleInfo(id);
7365
+ const entry = moduleInfo?.meta.originalId;
7366
+ if (entry) {
7367
+ const php = PHP_Code.fromFile(entry).applyEnv().escape();
7368
+ return {
7369
+ code: php.code,
7370
+ meta: { phpMapping: php.mapping }
7371
+ };
7372
+ }
7373
+ },
7374
+ generateBundle: {
7375
+ order: "post",
7376
+ handler(options, bundle, isWrite) {
7377
+ Object.entries(bundle).forEach(([key, item]) => {
7378
+ if (item.type === "asset") {
7379
+ const moduleInfo = this.getModuleInfo(item.fileName);
7380
+ if (moduleInfo?.meta.originalId) {
7381
+ const meta = moduleInfo.meta;
7382
+ item.fileName = meta.originalId;
7383
+ if (meta.phpMapping) {
7384
+ item.source = PHP_Code.unescape(
7385
+ item.source.toString(),
7386
+ meta.phpMapping
7387
+ );
7388
+ }
7389
+ item.source = fixAssetsInjection(
7390
+ item.source.toString()
7391
+ );
7392
+ }
7393
+ } else if (item.type === "chunk" && item.facadeModuleId) {
7394
+ const moduleInfo = this.getModuleInfo(item.facadeModuleId);
7395
+ if (moduleInfo) {
7396
+ const meta = moduleInfo.meta;
7397
+ if (meta.phpMapping) {
7398
+ item.code = PHP_Code.unescape(
7399
+ item.code,
7400
+ meta.phpMapping
7401
+ );
7402
+ }
7403
+ item.code = fixAssetsInjection(item.code);
7404
+ }
7405
+ }
7406
+ });
7407
+ }
7408
+ }
7409
+ };
7410
+
7411
+ function usePHP(cfg = {}) {
7412
+ const { entry = "index.php" } = cfg;
7413
+ PHP_Server.binary = cfg.binary ?? PHP_Server.binary;
7414
+ serve.rewriteUrl = cfg.rewriteUrl ?? serve.rewriteUrl;
7415
+ shared.entries = Array.isArray(entry) ? entry : [entry];
7416
+ shared.tempDir = cfg.tempDir ?? shared.tempDir;
7417
+ shared.devConfig = {
7418
+ cleanup: cfg.dev?.cleanup || shared.devConfig.cleanup,
7419
+ errorLevels: cfg.dev?.errorLevels || shared.devConfig.errorLevels
7420
+ };
7033
7421
  return [
7034
7422
  {
7035
- name: "prepare-php",
7423
+ name: "init-php",
7036
7424
  enforce: "post",
7037
- config(config2, env) {
7038
- const gitIgnoreFile = `${tempDir}/.gitignore`;
7039
- if (!require$$0$2.existsSync(gitIgnoreFile)) {
7040
- writeFile(gitIgnoreFile, "*\n**/*.php.html");
7041
- }
7042
- entries = [
7425
+ config(config, env) {
7426
+ shared.entries = [
7043
7427
  ...new Set(
7044
- entries.flatMap(
7428
+ shared.entries.flatMap(
7045
7429
  (entry2) => fastGlob.globSync(entry2, {
7046
7430
  dot: true,
7047
7431
  onlyFiles: true,
7048
7432
  unique: true,
7049
7433
  ignore: [
7050
- tempDir,
7051
- config2.build?.outDir || "dist"
7434
+ shared.tempDir,
7435
+ config.build?.outDir || "dist"
7052
7436
  ]
7053
7437
  })
7054
7438
  )
7055
7439
  )
7056
7440
  ];
7057
- consoleHijack(entries);
7441
+ consoleHijack();
7058
7442
  return {
7059
7443
  build: {
7060
- rollupOptions: { input: entries }
7444
+ rollupOptions: { input: shared.entries }
7061
7445
  },
7062
- optimizeDeps: { entries }
7446
+ optimizeDeps: { entries: shared.entries }
7063
7447
  };
7064
7448
  },
7065
7449
  configResolved(_config) {
7066
- config = _config;
7450
+ shared.viteConfig = _config;
7067
7451
  }
7068
7452
  },
7069
- {
7070
- name: "serve-php",
7071
- apply: "serve",
7072
- enforce: "pre",
7073
- configResolved(_config) {
7074
- config = _config;
7075
- entries.forEach((entry2) => {
7076
- const outputFile = getTempFileName(entry2);
7077
- escapePHP({
7078
- inputFile: entry2,
7079
- config
7080
- }).write(outputFile);
7081
- });
7082
- },
7083
- configureServer(server) {
7084
- viteServer = server;
7085
- phpServer.start(viteServer?.config.root);
7086
- server.middlewares.use(async (req, res, next) => {
7087
- try {
7088
- if (req.url && ![
7089
- "/@vite",
7090
- "/@fs",
7091
- "/@id/__x00__",
7092
- "/node_modules"
7093
- ].some((path) => req.url.startsWith(path))) {
7094
- req.on("error", (error) => {
7095
- throw error;
7096
- });
7097
- res.on("error", (error) => {
7098
- throw error;
7099
- });
7100
- const url = new URL(req.url, "http://localhost");
7101
- if (config?.server.port) {
7102
- url.port = config.server.port.toString();
7103
- }
7104
- const requestUrl = url.pathname;
7105
- if (url.pathname.endsWith("/")) {
7106
- url.pathname += "index.php";
7107
- }
7108
- const routedUrl = rewriteUrl(url);
7109
- if (routedUrl) {
7110
- url.pathname = routedUrl.pathname;
7111
- url.search = routedUrl.search;
7112
- url.hash = routedUrl.hash;
7113
- }
7114
- const entryPathname = url.pathname.substring(1);
7115
- const entry2 = entries.find((file) => {
7116
- return file === entryPathname || file.substring(0, file.lastIndexOf(".")) === entryPathname;
7117
- });
7118
- if (entry2) {
7119
- const tempFile = getTempFileName(entry2);
7120
- if (require$$0$2.existsSync(require$$0$1.resolve(tempFile))) {
7121
- url.pathname = tempFile;
7122
- url.port = phpServer.port.toString();
7123
- url.searchParams.set(
7124
- internalParam,
7125
- new URLSearchParams({
7126
- REQUEST_URI: requestUrl,
7127
- PHP_SELF: "/" + entry2
7128
- }).toString()
7129
- );
7130
- const body = await new Promise(
7131
- (resolve2, reject) => {
7132
- let data = [];
7133
- req.on("data", (chunk) => {
7134
- data.push(chunk);
7135
- }).on("end", () => {
7136
- resolve2(Buffer.concat(data));
7137
- });
7138
- }
7139
- );
7140
- const phpResult = await new Promise(async (resolve2, reject) => {
7141
- const chunks = [];
7142
- let statusCode;
7143
- let incomingHeaders = {};
7144
- const request = http__default.request(
7145
- url.toString(),
7146
- {
7147
- method: req.method,
7148
- headers: {
7149
- ...req.headers,
7150
- "content-length": Buffer.byteLength(
7151
- body
7152
- )
7153
- }
7154
- },
7155
- (msg) => {
7156
- statusCode = msg.statusCode;
7157
- incomingHeaders = msg.headers;
7158
- msg.on("data", (data) => {
7159
- chunks.push(data);
7160
- });
7161
- }
7162
- ).on("error", (error) => {
7163
- reject(error);
7164
- }).on("close", () => {
7165
- const content = Buffer.concat(
7166
- chunks
7167
- ).toString("utf8");
7168
- resolve2({
7169
- statusCode,
7170
- headers: incomingHeaders,
7171
- content
7172
- });
7173
- });
7174
- request.write(body, (error) => {
7175
- if (error) {
7176
- reject(error);
7177
- }
7178
- });
7179
- request.end();
7180
- });
7181
- let out = phpResult.content;
7182
- if (phpResult.headers["content-type"]?.includes("html")) {
7183
- out = await server.transformIndexHtml(
7184
- requestUrl,
7185
- out,
7186
- "/" + entryPathname
7187
- );
7188
- }
7189
- res.writeHead(
7190
- phpResult.statusCode || 200,
7191
- phpResult.headers
7192
- ).end(out);
7193
- return;
7194
- }
7195
- }
7196
- }
7197
- } catch (error) {
7198
- console.error("Vite-PHP Error: " + error);
7199
- }
7200
- next();
7201
- });
7202
- },
7203
- async handleHotUpdate({ server, file }) {
7204
- const entry2 = entries.find(
7205
- (entryFile) => require$$0$1.resolve(entryFile) === file
7206
- );
7207
- if (entry2) {
7208
- const outputFile = getTempFileName(entry2);
7209
- escapePHP({
7210
- inputFile: entry2,
7211
- config
7212
- }).write(outputFile);
7213
- server.moduleGraph.invalidateAll();
7214
- }
7215
- if (entry2 || !file.startsWith(require$$0$1.resolve(tempDir)) && file.includes(".php")) {
7216
- server.ws.send({
7217
- type: "full-reload"
7218
- });
7219
- }
7220
- }
7221
- },
7222
- {
7223
- name: "build-php",
7224
- apply: "build",
7225
- enforce: "pre",
7226
- resolveId(source, importer, options) {
7227
- if (entries.includes(source)) {
7228
- return {
7229
- // Rename ids because Vite transforms only .html files: https://github.com/vitejs/vite/blob/0cde495ebeb48bcfb5961784a30bfaed997790a0/packages/vite/src/node/plugins/html.ts#L330
7230
- id: `${source}.html`,
7231
- resolvedBy: "vite-plugin-php",
7232
- meta: {
7233
- originalId: source
7234
- }
7235
- };
7236
- }
7237
- },
7238
- load(id, options) {
7239
- const entry2 = this.getModuleInfo(id)?.meta.originalId;
7240
- if (entry2) {
7241
- const { escapedCode, phpCodes } = escapePHP({
7242
- inputFile: entry2,
7243
- config
7244
- });
7245
- return {
7246
- code: escapedCode,
7247
- meta: { phpCodes }
7248
- };
7249
- }
7250
- },
7251
- generateBundle: {
7252
- order: "post",
7253
- handler(options, bundle, isWrite) {
7254
- Object.entries(bundle).forEach(([key, item]) => {
7255
- if (item.type === "asset") {
7256
- const meta = this.getModuleInfo(
7257
- item.fileName
7258
- )?.meta;
7259
- if (meta?.originalId && meta?.phpCodes) {
7260
- item.fileName = meta.originalId;
7261
- item.source = unescapePHP({
7262
- escapedCode: item.source.toString(),
7263
- phpCodes: meta.phpCodes
7264
- });
7265
- }
7266
- } else if (item.type === "chunk" && item.facadeModuleId) {
7267
- const meta = this.getModuleInfo(
7268
- item.facadeModuleId
7269
- )?.meta;
7270
- if (meta?.phpCodes) {
7271
- item.code = unescapePHP({
7272
- escapedCode: item.code,
7273
- phpCodes: meta.phpCodes
7274
- });
7275
- }
7276
- }
7277
- });
7278
- }
7279
- }
7280
- }
7453
+ servePlugin,
7454
+ buildPlugin
7281
7455
  ];
7282
7456
  }
7283
7457
 
7284
- module.exports = usePHP;
7458
+ exports.EPHPError = EPHPError;
7459
+ exports.default = usePHP;