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.mjs CHANGED
@@ -1,18 +1,45 @@
1
- import require$$0$5, { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'fs';
2
- import require$$0$2, { relative, dirname, resolve } from 'path';
3
- import { normalizePath } from 'vite';
4
- import require$$0 from 'tty';
5
- import http from 'node:http';
6
- import { spawn } from 'child_process';
1
+ import { spawn } from 'node:child_process';
7
2
  import { fileURLToPath } from 'url';
8
- import require$$0$1 from 'os';
9
- import require$$0$3 from 'util';
10
- import require$$0$4 from 'stream';
11
- import require$$0$6 from 'events';
3
+ import { resolve, dirname, relative } from 'node:path';
4
+ import require$$0 from 'os';
5
+ import require$$0$1 from 'path';
6
+ import require$$0$2 from 'util';
7
+ import require$$0$3 from 'stream';
8
+ import require$$0$5 from 'events';
9
+ import require$$0$4 from 'fs';
10
+ import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
11
+ import http from 'node:http';
12
+ import { normalizePath } from 'vite';
12
13
 
13
- function makeID() {
14
- return Date.now().toString(36) + Math.random() * 100;
15
- }
14
+ const EPHPError = {
15
+ ERROR: 1,
16
+ WARNING: 2,
17
+ PARSE: 4,
18
+ NOTICE: 8,
19
+ CORE_ERROR: 16,
20
+ CORE_WARNING: 32,
21
+ COMPILE_ERROR: 64,
22
+ COMPILE_WARNING: 128,
23
+ USER_ERROR: 256,
24
+ USER_WARNING: 512,
25
+ USER_NOTICE: 1024,
26
+ STRICT: 2048,
27
+ RECOVERABLE_ERROR: 4096,
28
+ DEPRECATED: 8192,
29
+ USER_DEPRECATED: 16384,
30
+ ALL: 32767
31
+ };
32
+
33
+ const internalParam = "__314159265359__";
34
+ const shared = {
35
+ viteConfig: void 0,
36
+ devConfig: {
37
+ cleanup: true,
38
+ errorLevels: EPHPError.ALL | EPHPError.STRICT
39
+ },
40
+ entries: [],
41
+ tempDir: ".php-tmp"
42
+ };
16
43
 
17
44
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
18
45
 
@@ -20,35 +47,21 @@ function getDefaultExportFromCjs (x) {
20
47
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
21
48
  }
22
49
 
23
- function commonjsRequire(path) {
24
- 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.');
25
- }
26
-
27
50
  var picocolors = {exports: {}};
28
51
 
29
- let argv = process.argv || [],
30
- env = process.env;
52
+ let p = process || {}, argv = p.argv || [], env = p.env || {};
31
53
  let isColorSupported =
32
- !("NO_COLOR" in env || argv.includes("--no-color")) &&
33
- ("FORCE_COLOR" in env ||
34
- argv.includes("--color") ||
35
- process.platform === "win32" ||
36
- (commonjsRequire != null && require$$0.isatty(1) && env.TERM !== "dumb") ||
37
- "CI" in env);
38
-
39
- let formatter =
40
- (open, close, replace = open) =>
54
+ !(!!env.NO_COLOR || argv.includes("--no-color")) &&
55
+ (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
56
+
57
+ let formatter = (open, close, replace = open) =>
41
58
  input => {
42
- let string = "" + input;
43
- let index = string.indexOf(close, open.length);
44
- return ~index
45
- ? open + replaceClose(string, close, replace, index) + close
46
- : open + string + close
59
+ let string = "" + input, index = string.indexOf(close, open.length);
60
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
47
61
  };
48
62
 
49
63
  let replaceClose = (string, close, replace, index) => {
50
- let result = "";
51
- let cursor = 0;
64
+ let result = "", cursor = 0;
52
65
  do {
53
66
  result += string.substring(cursor, index) + replace;
54
67
  cursor = index + close.length;
@@ -58,54 +71,54 @@ let replaceClose = (string, close, replace, index) => {
58
71
  };
59
72
 
60
73
  let createColors = (enabled = isColorSupported) => {
61
- let init = enabled ? formatter : () => String;
74
+ let f = enabled ? formatter : () => String;
62
75
  return {
63
76
  isColorSupported: enabled,
64
- reset: init("\x1b[0m", "\x1b[0m"),
65
- bold: init("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
66
- dim: init("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
67
- italic: init("\x1b[3m", "\x1b[23m"),
68
- underline: init("\x1b[4m", "\x1b[24m"),
69
- inverse: init("\x1b[7m", "\x1b[27m"),
70
- hidden: init("\x1b[8m", "\x1b[28m"),
71
- strikethrough: init("\x1b[9m", "\x1b[29m"),
72
-
73
- black: init("\x1b[30m", "\x1b[39m"),
74
- red: init("\x1b[31m", "\x1b[39m"),
75
- green: init("\x1b[32m", "\x1b[39m"),
76
- yellow: init("\x1b[33m", "\x1b[39m"),
77
- blue: init("\x1b[34m", "\x1b[39m"),
78
- magenta: init("\x1b[35m", "\x1b[39m"),
79
- cyan: init("\x1b[36m", "\x1b[39m"),
80
- white: init("\x1b[37m", "\x1b[39m"),
81
- gray: init("\x1b[90m", "\x1b[39m"),
82
-
83
- bgBlack: init("\x1b[40m", "\x1b[49m"),
84
- bgRed: init("\x1b[41m", "\x1b[49m"),
85
- bgGreen: init("\x1b[42m", "\x1b[49m"),
86
- bgYellow: init("\x1b[43m", "\x1b[49m"),
87
- bgBlue: init("\x1b[44m", "\x1b[49m"),
88
- bgMagenta: init("\x1b[45m", "\x1b[49m"),
89
- bgCyan: init("\x1b[46m", "\x1b[49m"),
90
- bgWhite: init("\x1b[47m", "\x1b[49m"),
91
-
92
- blackBright: init("\x1b[90m", "\x1b[39m"),
93
- redBright: init("\x1b[91m", "\x1b[39m"),
94
- greenBright: init("\x1b[92m", "\x1b[39m"),
95
- yellowBright: init("\x1b[93m", "\x1b[39m"),
96
- blueBright: init("\x1b[94m", "\x1b[39m"),
97
- magentaBright: init("\x1b[95m", "\x1b[39m"),
98
- cyanBright: init("\x1b[96m", "\x1b[39m"),
99
- whiteBright: init("\x1b[97m", "\x1b[39m"),
100
-
101
- bgBlackBright: init("\x1b[100m","\x1b[49m"),
102
- bgRedBright: init("\x1b[101m","\x1b[49m"),
103
- bgGreenBright: init("\x1b[102m","\x1b[49m"),
104
- bgYellowBright: init("\x1b[103m","\x1b[49m"),
105
- bgBlueBright: init("\x1b[104m","\x1b[49m"),
106
- bgMagentaBright: init("\x1b[105m","\x1b[49m"),
107
- bgCyanBright: init("\x1b[106m","\x1b[49m"),
108
- bgWhiteBright: init("\x1b[107m","\x1b[49m"),
77
+ reset: f("\x1b[0m", "\x1b[0m"),
78
+ bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
79
+ dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
80
+ italic: f("\x1b[3m", "\x1b[23m"),
81
+ underline: f("\x1b[4m", "\x1b[24m"),
82
+ inverse: f("\x1b[7m", "\x1b[27m"),
83
+ hidden: f("\x1b[8m", "\x1b[28m"),
84
+ strikethrough: f("\x1b[9m", "\x1b[29m"),
85
+
86
+ black: f("\x1b[30m", "\x1b[39m"),
87
+ red: f("\x1b[31m", "\x1b[39m"),
88
+ green: f("\x1b[32m", "\x1b[39m"),
89
+ yellow: f("\x1b[33m", "\x1b[39m"),
90
+ blue: f("\x1b[34m", "\x1b[39m"),
91
+ magenta: f("\x1b[35m", "\x1b[39m"),
92
+ cyan: f("\x1b[36m", "\x1b[39m"),
93
+ white: f("\x1b[37m", "\x1b[39m"),
94
+ gray: f("\x1b[90m", "\x1b[39m"),
95
+
96
+ bgBlack: f("\x1b[40m", "\x1b[49m"),
97
+ bgRed: f("\x1b[41m", "\x1b[49m"),
98
+ bgGreen: f("\x1b[42m", "\x1b[49m"),
99
+ bgYellow: f("\x1b[43m", "\x1b[49m"),
100
+ bgBlue: f("\x1b[44m", "\x1b[49m"),
101
+ bgMagenta: f("\x1b[45m", "\x1b[49m"),
102
+ bgCyan: f("\x1b[46m", "\x1b[49m"),
103
+ bgWhite: f("\x1b[47m", "\x1b[49m"),
104
+
105
+ blackBright: f("\x1b[90m", "\x1b[39m"),
106
+ redBright: f("\x1b[91m", "\x1b[39m"),
107
+ greenBright: f("\x1b[92m", "\x1b[39m"),
108
+ yellowBright: f("\x1b[93m", "\x1b[39m"),
109
+ blueBright: f("\x1b[94m", "\x1b[39m"),
110
+ magentaBright: f("\x1b[95m", "\x1b[39m"),
111
+ cyanBright: f("\x1b[96m", "\x1b[39m"),
112
+ whiteBright: f("\x1b[97m", "\x1b[39m"),
113
+
114
+ bgBlackBright: f("\x1b[100m", "\x1b[49m"),
115
+ bgRedBright: f("\x1b[101m", "\x1b[49m"),
116
+ bgGreenBright: f("\x1b[102m", "\x1b[49m"),
117
+ bgYellowBright: f("\x1b[103m", "\x1b[49m"),
118
+ bgBlueBright: f("\x1b[104m", "\x1b[49m"),
119
+ bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
120
+ bgCyanBright: f("\x1b[106m", "\x1b[49m"),
121
+ bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
109
122
  }
110
123
  };
111
124
 
@@ -115,136 +128,130 @@ picocolors.exports.createColors = createColors;
115
128
  var picocolorsExports = picocolors.exports;
116
129
  const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
117
130
 
118
- function resolveEnvPrefix({ envPrefix = "VITE_" }) {
119
- envPrefix = Array.isArray(envPrefix) ? envPrefix : [envPrefix];
120
- if (envPrefix.includes("")) {
121
- throw new Error(
122
- `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
123
- );
131
+ function hasViteConfig(input) {
132
+ if (!input) {
133
+ throw new Error("Vite config not initialized!");
124
134
  }
125
- return envPrefix;
126
- }
127
- const envPattern = /%(\S+?)%/g;
128
- function initReplaceEnv(config) {
129
- const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
130
- const env = { ...config.env };
131
- for (const key in config.define) {
132
- if (key.startsWith(`import.meta.env.`)) {
133
- const val = config.define[key];
134
- if (typeof val === "string") {
135
- try {
136
- const parsed = JSON.parse(val);
137
- env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
138
- } catch {
139
- env[key.slice(16)] = val;
140
- }
141
- } else {
142
- env[key.slice(16)] = JSON.stringify(val);
143
- }
144
- }
145
- }
146
- return function replaceEnv(content, filename) {
147
- return content.replace(envPattern, (text, key) => {
148
- if (key in env) {
149
- return env[key];
150
- } else {
151
- if (envPrefix.some((prefix) => key.startsWith(prefix))) {
152
- const relativeHtml = normalizePath(
153
- relative(config.root, filename)
154
- );
155
- config.logger.warn(
156
- colors.yellow(
157
- colors.bold(
158
- `(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
159
- )
160
- )
161
- );
162
- }
163
- return text;
164
- }
165
- });
166
- };
167
135
  }
168
136
 
169
- function writeFile(file, data) {
170
- mkdirSync(dirname(file), { recursive: true });
171
- writeFileSync(file, data);
137
+ function log(message, { type = "info", prefix = true, ...options } = {}) {
138
+ hasViteConfig(shared.viteConfig);
139
+ let output = "";
140
+ if (prefix) {
141
+ output += colors.bgMagenta(colors.white("\u2009php\u2009")) + " ";
142
+ }
143
+ output += message;
144
+ shared.viteConfig.logger[type](output, options);
172
145
  }
173
-
174
- const phpTagPattern = /<\?(?:php|).+?(\?>|$)/gis;
175
- function escapePHP({ inputFile, config }) {
176
- const replaceEnv = initReplaceEnv(config);
177
- const input = readFileSync(inputFile, "utf-8").toString();
178
- const phpCodes = {};
179
- const isJS = inputFile.includes(".js") || inputFile.includes(".ts");
180
- const isML = inputFile.includes(".php") || inputFile.includes(".htm");
181
- const escapedCode = input.replace(phpTagPattern, (match) => {
182
- let token = makeID();
183
- if (isJS) {
184
- token = `/*${token}*/`;
185
- } else if (isML) {
186
- token = `<!--${token}-->`;
187
- }
188
- phpCodes[token] = replaceEnv(match, inputFile);
189
- return token;
190
- });
191
- return {
192
- escapedCode,
193
- phpCodes,
194
- write(outputFile) {
195
- writeFile(outputFile, escapedCode);
196
- writeFile(outputFile + ".json", JSON.stringify(phpCodes));
146
+ log.error = function(json, options = {}) {
147
+ let output = json;
148
+ let type = "info";
149
+ try {
150
+ const data = JSON.parse(json);
151
+ output = "";
152
+ switch (data.code) {
153
+ case EPHPError.PARSE:
154
+ case EPHPError.ERROR:
155
+ case EPHPError.CORE_ERROR:
156
+ case EPHPError.COMPILE_ERROR:
157
+ case EPHPError.USER_ERROR:
158
+ type = "error";
159
+ output += colors.bgRedBright(colors.white("Fatal Error"));
160
+ break;
161
+ case EPHPError.WARNING:
162
+ case EPHPError.USER_WARNING:
163
+ case EPHPError.COMPILE_WARNING:
164
+ case EPHPError.RECOVERABLE_ERROR:
165
+ type = "warn";
166
+ output += colors.yellowBright("Warning");
167
+ break;
168
+ case EPHPError.NOTICE:
169
+ case EPHPError.USER_NOTICE:
170
+ type = "info";
171
+ output += colors.bgWhite(colors.black("Notice"));
172
+ break;
173
+ case EPHPError.STRICT:
174
+ type = "info";
175
+ output += colors.yellow("Strict");
176
+ break;
177
+ case EPHPError.DEPRECATED:
178
+ case EPHPError.USER_DEPRECATED:
179
+ type = "info";
180
+ output += colors.cyan("Deprecated");
181
+ break;
182
+ default:
183
+ break;
197
184
  }
198
- };
199
- }
200
- function unescapePHP({ escapedCode, phpCodes }) {
201
- let out = escapedCode;
202
- Object.entries(phpCodes).forEach(([token, code]) => {
203
- out = out.replace(token, (match) => {
204
- return `${code}`;
205
- });
206
- });
207
- return out;
208
- }
185
+ output += " " + data.message + "\r\n";
186
+ output += " In: " + data.file.replace(
187
+ resolve(shared.tempDir),
188
+ shared.viteConfig?.root
189
+ ) + "\r\n";
190
+ output += " On line: " + data.line;
191
+ } catch (error) {
192
+ }
193
+ log(output, { ...options, type });
194
+ };
209
195
 
196
+ const PHP_Server = {
197
+ binary: "php",
198
+ port: 65535,
199
+ process: void 0,
200
+ start,
201
+ stop
202
+ };
210
203
  function start(root) {
211
- if (!globalThis.php?.pid) {
204
+ if (!PHP_Server.process?.pid) {
212
205
  const routerFileUrl = new URL("./router.php", import.meta.url);
213
- globalThis.php = spawn(phpServer.binary, [
206
+ PHP_Server.process = spawn(PHP_Server.binary, [
214
207
  "-S",
215
- "localhost:" + phpServer.port,
208
+ "localhost:" + PHP_Server.port,
216
209
  "-t",
217
210
  root,
218
211
  fileURLToPath(routerFileUrl)
219
212
  ]).once("spawn", () => {
220
- console.log(
221
- `PHP development server started (PID: ${globalThis.php?.pid})`
222
- );
213
+ log(`Server started (PID: ${PHP_Server.process?.pid})`);
223
214
  }).on("error", (error) => {
224
- console.error("PHP dev-server error: " + error.message);
225
- }).on("close", (code) => {
226
- console.log(`PHP development server stopped (Code: ${code})`);
215
+ log(`Server error: ${error.message})`, {
216
+ type: "error"
217
+ });
218
+ });
219
+ PHP_Server.process.stdout?.on("data", (data) => {
220
+ log("", { timestamp: true });
221
+ `${data}`.trim().split("\r\n").forEach((line) => {
222
+ if (line.startsWith(internalParam + ":")) {
223
+ log.error(
224
+ line.substring((internalParam + ":").length),
225
+ { prefix: false }
226
+ );
227
+ } else {
228
+ log(line);
229
+ }
230
+ });
227
231
  });
228
232
  }
229
233
  }
230
- function stop() {
231
- if (globalThis.php) {
232
- globalThis.php.stdin?.end();
233
- globalThis.php.stdout?.destroy();
234
- globalThis.php.stderr?.destroy();
235
- if (globalThis.php.kill()) {
236
- console.log("PHP development server killed");
234
+ function stop(callBack) {
235
+ if (PHP_Server.process) {
236
+ PHP_Server.process.on("close", (code) => {
237
+ log("Ended with: " + code);
238
+ PHP_Server.process = void 0;
239
+ callBack();
240
+ });
241
+ PHP_Server.process.stdin?.destroy();
242
+ PHP_Server.process.stdout?.destroy();
243
+ PHP_Server.process.stderr?.destroy();
244
+ if (PHP_Server.process.kill()) {
245
+ log("Shutting down");
237
246
  } else {
238
- console.error("Attention! Failed to kill PHP development server!");
247
+ log("Failed to send SIGTERM", {
248
+ type: "error"
249
+ });
239
250
  }
251
+ } else {
252
+ callBack();
240
253
  }
241
254
  }
242
- const phpServer = {
243
- binary: "php",
244
- port: 65535,
245
- start,
246
- stop
247
- };
248
255
 
249
256
  var tasks = {};
250
257
 
@@ -308,8 +315,8 @@ var path$9 = {};
308
315
 
309
316
  Object.defineProperty(path$9, "__esModule", { value: true });
310
317
  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;
311
- const os = require$$0$1;
312
- const path$8 = require$$0$2;
318
+ const os = require$$0;
319
+ const path$8 = require$$0$1;
313
320
  const IS_WINDOWS_PLATFORM = os.platform() === 'win32';
314
321
  const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
315
322
  /**
@@ -549,8 +556,8 @@ var isGlob$1 = function isGlob(str, options) {
549
556
  };
550
557
 
551
558
  var isGlob = isGlob$1;
552
- var pathPosixDirname = require$$0$2.posix.dirname;
553
- var isWin32 = require$$0$1.platform() === 'win32';
559
+ var pathPosixDirname = require$$0$1.posix.dirname;
560
+ var isWin32 = require$$0.platform() === 'win32';
554
561
 
555
562
  var slash = '/';
556
563
  var backslash = /\\/g;
@@ -1046,7 +1053,7 @@ var toRegexRange_1 = toRegexRange$1;
1046
1053
  * Licensed under the MIT License.
1047
1054
  */
1048
1055
 
1049
- const util$1 = require$$0$3;
1056
+ const util$1 = require$$0$2;
1050
1057
  const toRegexRange = toRegexRange_1;
1051
1058
 
1052
1059
  const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
@@ -2011,7 +2018,7 @@ var braces_1 = braces$1;
2011
2018
 
2012
2019
  var utils$f = {};
2013
2020
 
2014
- const path$7 = require$$0$2;
2021
+ const path$7 = require$$0$1;
2015
2022
  const WIN_SLASH = '\\\\/';
2016
2023
  const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
2017
2024
 
@@ -2191,7 +2198,7 @@ var constants$3 = {
2191
2198
 
2192
2199
  (function (exports) {
2193
2200
 
2194
- const path = require$$0$2;
2201
+ const path = require$$0$1;
2195
2202
  const win32 = process.platform === 'win32';
2196
2203
  const {
2197
2204
  REGEX_BACKSLASH,
@@ -3735,7 +3742,7 @@ parse$1.fastpaths = (input, options) => {
3735
3742
 
3736
3743
  var parse_1 = parse$1;
3737
3744
 
3738
- const path$6 = require$$0$2;
3745
+ const path$6 = require$$0$1;
3739
3746
  const scan = scan_1;
3740
3747
  const parse = parse_1;
3741
3748
  const utils$c = utils$f;
@@ -4078,7 +4085,7 @@ var picomatch_1 = picomatch$2;
4078
4085
 
4079
4086
  var picomatch$1 = picomatch_1;
4080
4087
 
4081
- const util = require$$0$3;
4088
+ const util = require$$0$2;
4082
4089
  const braces = braces_1;
4083
4090
  const picomatch = picomatch$1;
4084
4091
  const utils$b = utils$f;
@@ -4546,7 +4553,7 @@ var micromatch_1 = micromatch$1;
4546
4553
 
4547
4554
  Object.defineProperty(pattern$1, "__esModule", { value: true });
4548
4555
  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;
4549
- const path$5 = require$$0$2;
4556
+ const path$5 = require$$0$1;
4550
4557
  const globParent = globParent$1;
4551
4558
  const micromatch = micromatch_1;
4552
4559
  const GLOBSTAR = '**';
@@ -4741,7 +4748,7 @@ var stream$4 = {};
4741
4748
  * Copyright (c) 2014-2020 Teambition
4742
4749
  * Licensed under the MIT license.
4743
4750
  */
4744
- const Stream = require$$0$4;
4751
+ const Stream = require$$0$3;
4745
4752
  const PassThrough = Stream.PassThrough;
4746
4753
  const slice = Array.prototype.slice;
4747
4754
 
@@ -5121,7 +5128,7 @@ var fs$5 = {};
5121
5128
  (function (exports) {
5122
5129
  Object.defineProperty(exports, "__esModule", { value: true });
5123
5130
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
5124
- const fs = require$$0$5;
5131
+ const fs = require$$0$4;
5125
5132
  exports.FILE_SYSTEM_ADAPTER = {
5126
5133
  lstat: fs.lstat,
5127
5134
  stat: fs.stat,
@@ -5472,7 +5479,7 @@ var fs$1 = {};
5472
5479
  (function (exports) {
5473
5480
  Object.defineProperty(exports, "__esModule", { value: true });
5474
5481
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
5475
- const fs = require$$0$5;
5482
+ const fs = require$$0$4;
5476
5483
  exports.FILE_SYSTEM_ADAPTER = {
5477
5484
  lstat: fs.lstat,
5478
5485
  stat: fs.stat,
@@ -5491,7 +5498,7 @@ var fs$1 = {};
5491
5498
  } (fs$1));
5492
5499
 
5493
5500
  Object.defineProperty(settings$2, "__esModule", { value: true });
5494
- const path$3 = require$$0$2;
5501
+ const path$3 = require$$0$1;
5495
5502
  const fsStat$3 = out$1;
5496
5503
  const fs = fs$1;
5497
5504
  let Settings$1 = class Settings {
@@ -5933,7 +5940,7 @@ let Reader$1 = class Reader {
5933
5940
  reader$1.default = Reader$1;
5934
5941
 
5935
5942
  Object.defineProperty(async$4, "__esModule", { value: true });
5936
- const events_1 = require$$0$6;
5943
+ const events_1 = require$$0$5;
5937
5944
  const fsScandir$2 = out$2;
5938
5945
  const fastq = queueExports;
5939
5946
  const common$1 = common$3;
@@ -6062,7 +6069,7 @@ function callSuccessCallback(callback, entries) {
6062
6069
  var stream$2 = {};
6063
6070
 
6064
6071
  Object.defineProperty(stream$2, "__esModule", { value: true });
6065
- const stream_1$5 = require$$0$4;
6072
+ const stream_1$5 = require$$0$3;
6066
6073
  const async_1$3 = async$4;
6067
6074
  class StreamProvider {
6068
6075
  constructor(_root, _settings) {
@@ -6175,7 +6182,7 @@ sync$3.default = SyncProvider;
6175
6182
  var settings$1 = {};
6176
6183
 
6177
6184
  Object.defineProperty(settings$1, "__esModule", { value: true });
6178
- const path$2 = require$$0$2;
6185
+ const path$2 = require$$0$1;
6179
6186
  const fsScandir = out$2;
6180
6187
  class Settings {
6181
6188
  constructor(_options = {}) {
@@ -6237,7 +6244,7 @@ function getSettings(settingsOrOptions = {}) {
6237
6244
  var reader = {};
6238
6245
 
6239
6246
  Object.defineProperty(reader, "__esModule", { value: true });
6240
- const path$1 = require$$0$2;
6247
+ const path$1 = require$$0$1;
6241
6248
  const fsStat$2 = out$1;
6242
6249
  const utils$6 = utils$k;
6243
6250
  class Reader {
@@ -6272,7 +6279,7 @@ reader.default = Reader;
6272
6279
  var stream$1 = {};
6273
6280
 
6274
6281
  Object.defineProperty(stream$1, "__esModule", { value: true });
6275
- const stream_1$3 = require$$0$4;
6282
+ const stream_1$3 = require$$0$3;
6276
6283
  const fsStat$1 = out$1;
6277
6284
  const fsWalk$2 = out$3;
6278
6285
  const reader_1$2 = reader;
@@ -6625,7 +6632,7 @@ class EntryTransformer {
6625
6632
  entry.default = EntryTransformer;
6626
6633
 
6627
6634
  Object.defineProperty(provider, "__esModule", { value: true });
6628
- const path = require$$0$2;
6635
+ const path = require$$0$1;
6629
6636
  const deep_1 = deep;
6630
6637
  const entry_1 = entry$1;
6631
6638
  const error_1 = error;
@@ -6698,7 +6705,7 @@ async$7.default = ProviderAsync;
6698
6705
  var stream = {};
6699
6706
 
6700
6707
  Object.defineProperty(stream, "__esModule", { value: true });
6701
- const stream_1$1 = require$$0$4;
6708
+ const stream_1$1 = require$$0$3;
6702
6709
  const stream_2 = stream$1;
6703
6710
  const provider_1$1 = provider;
6704
6711
  class ProviderStream extends provider_1$1.default {
@@ -6803,8 +6810,8 @@ var settings = {};
6803
6810
  (function (exports) {
6804
6811
  Object.defineProperty(exports, "__esModule", { value: true });
6805
6812
  exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
6806
- const fs = require$$0$5;
6807
- const os = require$$0$1;
6813
+ const fs = require$$0$4;
6814
+ const os = require$$0;
6808
6815
  /**
6809
6816
  * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
6810
6817
  * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
@@ -6963,7 +6970,8 @@ var out = FastGlob;
6963
6970
 
6964
6971
  const fastGlob = /*@__PURE__*/getDefaultExportFromCjs(out);
6965
6972
 
6966
- function consoleHijack(entries) {
6973
+ function consoleHijack() {
6974
+ const entries = shared.entries;
6967
6975
  ["log", "info", "warn", "error"].forEach((command) => {
6968
6976
  const cx = console[command];
6969
6977
  console[command] = function(...args) {
@@ -6979,292 +6987,457 @@ function consoleHijack(entries) {
6979
6987
  });
6980
6988
  }
6981
6989
 
6982
- const internalParam = "__314159265359__";
6983
- function usePHP(cfg = {}) {
6984
- const {
6985
- binary = "php",
6986
- entry = "index.php",
6987
- rewriteUrl = (requestUrl) => requestUrl,
6988
- tempDir = ".php-tmp",
6989
- cleanup = {}
6990
- } = cfg;
6991
- const { dev: devCleanup = true } = cleanup;
6992
- phpServer.binary = binary;
6993
- let config = void 0;
6994
- let viteServer = void 0;
6995
- let entries = Array.isArray(entry) ? entry : [entry];
6996
- function getTempFileName(file) {
6997
- return `${tempDir}/${file}.html`;
6998
- }
6999
- function cleanupTemp() {
7000
- rmSync(tempDir, { recursive: true, force: true });
7001
- }
7002
- function onExit() {
7003
- if (config?.command === "serve") {
7004
- phpServer.stop();
7005
- devCleanup && cleanupTemp();
7006
- }
7007
- process.exit();
7008
- }
7009
- [
7010
- "exit",
7011
- "SIGINT",
7012
- "SIGUSR1",
7013
- "SIGUSR2",
7014
- "uncaughtException",
7015
- "SIGTERM"
7016
- ].forEach((eventType) => {
7017
- process.on(eventType, onExit.bind(null));
6990
+ function readFile(file) {
6991
+ return readFileSync(file, "utf-8").toString();
6992
+ }
6993
+ function writeFile(file, data) {
6994
+ mkdirSync(dirname(file), { recursive: true });
6995
+ writeFileSync(file, data);
6996
+ }
6997
+
6998
+ function makeID() {
6999
+ return Date.now().toString(36) + Math.random() * 100;
7000
+ }
7001
+
7002
+ function resolveEnvPrefix({ envPrefix = "VITE_" }) {
7003
+ envPrefix = Array.isArray(envPrefix) ? envPrefix : [envPrefix];
7004
+ if (envPrefix.includes("")) {
7005
+ throw new Error(
7006
+ `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
7007
+ );
7008
+ }
7009
+ return envPrefix;
7010
+ }
7011
+ const envPattern = /%(\S+?)%/g;
7012
+ function initReplaceEnv() {
7013
+ hasViteConfig(shared.viteConfig);
7014
+ const { env, define, root, logger } = shared.viteConfig;
7015
+ const envPrefix = resolveEnvPrefix({
7016
+ envPrefix: shared.viteConfig.envPrefix
7018
7017
  });
7018
+ for (const key in define) {
7019
+ if (key.startsWith(`import.meta.env.`)) {
7020
+ const val = define[key];
7021
+ if (typeof val === "string") {
7022
+ try {
7023
+ const parsed = JSON.parse(val);
7024
+ env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
7025
+ } catch {
7026
+ env[key.slice(16)] = val;
7027
+ }
7028
+ } else {
7029
+ env[key.slice(16)] = JSON.stringify(val);
7030
+ }
7031
+ }
7032
+ }
7033
+ return function replaceEnv(content, filename) {
7034
+ const relativeHtml = normalizePath(relative(root, filename));
7035
+ return content.replace(envPattern, (text, key) => {
7036
+ if (key in env) {
7037
+ return env[key];
7038
+ } else {
7039
+ if (envPrefix.some((prefix) => key.startsWith(prefix))) {
7040
+ logger.warn(
7041
+ colors.yellow(
7042
+ colors.bold(
7043
+ `(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
7044
+ )
7045
+ )
7046
+ );
7047
+ }
7048
+ return text;
7049
+ }
7050
+ });
7051
+ };
7052
+ }
7053
+
7054
+ var __defProp = Object.defineProperty;
7055
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7056
+ var __publicField = (obj, key, value) => {
7057
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7058
+ return value;
7059
+ };
7060
+ const phpStartPattern = `<\\?(?:php|)`;
7061
+ const phpEndPattern = `\\?>`;
7062
+ const phpTagRegex = new RegExp(
7063
+ `${phpStartPattern}.+?(${phpEndPattern}|$)`,
7064
+ "gis"
7065
+ );
7066
+ class PHP_Code {
7067
+ constructor(code) {
7068
+ __publicField(this, "file", "!!__VIRTUAL__!!.php");
7069
+ __publicField(this, "code");
7070
+ __publicField(this, "mapping", {});
7071
+ this.code = code;
7072
+ return this;
7073
+ }
7074
+ static fromFile(file) {
7075
+ const inst = new this(readFile(file));
7076
+ inst.file = file;
7077
+ return inst;
7078
+ }
7079
+ applyEnv() {
7080
+ const replaceEnv = initReplaceEnv();
7081
+ this.code = replaceEnv(this.code, this.file || "");
7082
+ return this;
7083
+ }
7084
+ escape() {
7085
+ const isJS = this.file.includes(".js") || this.file.includes(".ts");
7086
+ const isML = this.file.includes(".php") || this.file.includes(".htm");
7087
+ this.code = this.code.replace(phpTagRegex, (match) => {
7088
+ let token = makeID();
7089
+ if (isJS) {
7090
+ token = `/*${token}*/`;
7091
+ } else if (isML) {
7092
+ token = `\u2400\u2400${token}\u2400\u2400`;
7093
+ }
7094
+ this.mapping[token] = match;
7095
+ return token;
7096
+ });
7097
+ return this;
7098
+ }
7099
+ write(file, mapping = false) {
7100
+ writeFile(file, this.code);
7101
+ mapping && writeFile(file + ".json", JSON.stringify(this.mapping));
7102
+ }
7103
+ static unescape(code, mapping) {
7104
+ let out = code;
7105
+ Object.entries(mapping).forEach(([token, code2]) => {
7106
+ out = out.replace(token, code2);
7107
+ });
7108
+ return out;
7109
+ }
7110
+ }
7111
+
7112
+ const serve = {
7113
+ rewriteUrl: (url) => url
7114
+ };
7115
+ function tempName(entry) {
7116
+ return `${shared.tempDir}/${entry}`;
7117
+ }
7118
+ const servePlugin = {
7119
+ name: "serve-php",
7120
+ apply: "serve",
7121
+ enforce: "post",
7122
+ configResolved() {
7123
+ function handleExit(signal) {
7124
+ if (signal === "SIGINT") {
7125
+ console.log();
7126
+ }
7127
+ const tempDir = resolve(shared.tempDir);
7128
+ if (shared.devConfig.cleanup && existsSync(tempDir)) {
7129
+ log("Removing temporary files");
7130
+ rmSync(tempDir, {
7131
+ recursive: true,
7132
+ force: true
7133
+ });
7134
+ }
7135
+ if (PHP_Server.process && shared.viteConfig?.command === "serve") {
7136
+ PHP_Server.stop(() => {
7137
+ process.exit();
7138
+ });
7139
+ } else {
7140
+ process.exit();
7141
+ }
7142
+ }
7143
+ [
7144
+ "exit",
7145
+ "SIGINT",
7146
+ "SIGUSR1",
7147
+ "SIGUSR2",
7148
+ "uncaughtException",
7149
+ "SIGTERM"
7150
+ ].forEach((eventType) => {
7151
+ new Promise((resolve2) => process.on(eventType, resolve2)).then(
7152
+ handleExit
7153
+ );
7154
+ });
7155
+ const gitIgnoreFile = resolve(`${shared.tempDir}/.gitignore`);
7156
+ if (!existsSync(gitIgnoreFile)) {
7157
+ writeFile(gitIgnoreFile, "*\r\n**/*");
7158
+ }
7159
+ shared.entries.forEach((entry) => {
7160
+ PHP_Code.fromFile(entry).applyEnv().write(tempName(entry));
7161
+ });
7162
+ },
7163
+ configureServer(server) {
7164
+ if (!PHP_Server.process) {
7165
+ PHP_Server.start(server?.config.root);
7166
+ }
7167
+ server.middlewares.use(async (req, res, next) => {
7168
+ try {
7169
+ if (req.url && !["/@vite", "/@fs", "/@id/__x00__", "/node_modules"].some(
7170
+ (path) => req.url.startsWith(path)
7171
+ )) {
7172
+ req.on("error", (error) => {
7173
+ throw error;
7174
+ });
7175
+ const url = new URL(req.url, "http://localhost");
7176
+ if (shared.viteConfig?.server.port) {
7177
+ url.port = shared.viteConfig.server.port.toString();
7178
+ }
7179
+ const requestUrl = url.pathname;
7180
+ if (url.pathname.endsWith("/")) {
7181
+ url.pathname += "index.php";
7182
+ }
7183
+ const routedUrl = serve.rewriteUrl(url);
7184
+ if (routedUrl) {
7185
+ url.pathname = routedUrl.pathname;
7186
+ url.search = routedUrl.search;
7187
+ url.hash = routedUrl.hash;
7188
+ }
7189
+ const entryPathname = url.pathname.substring(1);
7190
+ const entry = shared.entries.find((file) => {
7191
+ return file === entryPathname || file.substring(0, file.lastIndexOf(".")) === entryPathname;
7192
+ });
7193
+ if (entry) {
7194
+ const tempFile = tempName(entry);
7195
+ if (existsSync(resolve(tempFile))) {
7196
+ url.pathname = tempFile;
7197
+ url.port = PHP_Server.port.toString();
7198
+ url.searchParams.set(
7199
+ internalParam,
7200
+ new URLSearchParams({
7201
+ $REQUEST_URI: requestUrl,
7202
+ $PHP_SELF: "/" + entry,
7203
+ temp_dir: shared.tempDir,
7204
+ error_levels: shared.devConfig.errorLevels.toString()
7205
+ }).toString()
7206
+ );
7207
+ const body = await new Promise(
7208
+ (resolve2, reject) => {
7209
+ let data = [];
7210
+ req.on("data", (chunk) => {
7211
+ data.push(chunk);
7212
+ }).on("end", () => {
7213
+ resolve2(Buffer.concat(data));
7214
+ });
7215
+ }
7216
+ );
7217
+ const phpResult = await new Promise(async (resolve2, reject) => {
7218
+ const chunks = [];
7219
+ let statusCode;
7220
+ let incomingHeaders = {};
7221
+ const request = http.request(
7222
+ url.toString(),
7223
+ {
7224
+ method: req.method,
7225
+ headers: {
7226
+ ...req.headers,
7227
+ "content-length": Buffer.byteLength(body)
7228
+ }
7229
+ },
7230
+ (msg) => {
7231
+ statusCode = msg.statusCode;
7232
+ incomingHeaders = msg.headers;
7233
+ msg.on("data", (data) => {
7234
+ chunks.push(data);
7235
+ });
7236
+ }
7237
+ ).on("error", (error) => {
7238
+ reject(error);
7239
+ }).on("close", () => {
7240
+ const content = Buffer.concat(chunks).toString(
7241
+ "utf8"
7242
+ );
7243
+ resolve2({
7244
+ statusCode,
7245
+ headers: incomingHeaders,
7246
+ content
7247
+ });
7248
+ });
7249
+ request.write(body, (error) => {
7250
+ if (error) {
7251
+ reject(error);
7252
+ }
7253
+ });
7254
+ request.end();
7255
+ });
7256
+ let out = phpResult.content;
7257
+ if (phpResult.headers["content-type"]?.includes(
7258
+ "html"
7259
+ )) {
7260
+ out = await server.transformIndexHtml(
7261
+ `/${entry}.html`,
7262
+ out,
7263
+ requestUrl
7264
+ );
7265
+ }
7266
+ res.writeHead(
7267
+ phpResult.statusCode || 200,
7268
+ phpResult.headers
7269
+ ).end(out);
7270
+ return;
7271
+ }
7272
+ }
7273
+ }
7274
+ } catch (error) {
7275
+ console.error("Vite-PHP Error: " + error);
7276
+ }
7277
+ next();
7278
+ });
7279
+ },
7280
+ handleHotUpdate({ server, file }) {
7281
+ const entry = shared.entries.find(
7282
+ (entryFile) => resolve(entryFile) === resolve(file)
7283
+ );
7284
+ if (entry) {
7285
+ PHP_Code.fromFile(entry).applyEnv().write(tempName(entry));
7286
+ server.moduleGraph.invalidateAll();
7287
+ }
7288
+ if (entry || !file.startsWith(resolve(shared.tempDir)) && file.includes(".php")) {
7289
+ server.ws.send({
7290
+ type: "full-reload"
7291
+ });
7292
+ }
7293
+ }
7294
+ };
7295
+
7296
+ const assetsPattern = new RegExp(
7297
+ `^(.+?)(${phpStartPattern}\\s+namespace\\s\\S+?(?:\\s*;|\\s*{).+)$`,
7298
+ "si"
7299
+ );
7300
+ const lastTagPattern = new RegExp(`^(.+(?:</.+?>|<.+?/>))(.+|)$`, "si");
7301
+ const closingPattern = new RegExp(`^(.+)(${phpStartPattern}.+)$`, "si");
7302
+ function fixAssetsInjection(input) {
7303
+ let out = input;
7304
+ let assets = "";
7305
+ out = out.replace(assetsPattern, (match, p1, p2) => {
7306
+ assets = p1.trim();
7307
+ return p2;
7308
+ });
7309
+ const injectAssets = (_, part1, part2) => {
7310
+ let a = assets;
7311
+ if (!(part1.endsWith("\n") || part1.endsWith("\r"))) {
7312
+ a = "\r\n" + a;
7313
+ }
7314
+ if (!(part2.startsWith("\n") || part2.startsWith("\r"))) {
7315
+ a += "\r\n";
7316
+ }
7317
+ assets = "";
7318
+ return `${part1}${a}${part2}`;
7319
+ };
7320
+ if (assets) {
7321
+ out = out.replace(lastTagPattern, injectAssets);
7322
+ }
7323
+ if (assets) {
7324
+ out = out.replace(closingPattern, injectAssets);
7325
+ }
7326
+ if (assets) {
7327
+ out += assets;
7328
+ }
7329
+ return out;
7330
+ }
7331
+
7332
+ const buildPlugin = {
7333
+ name: "build-php",
7334
+ apply: "build",
7335
+ enforce: "pre",
7336
+ resolveId(source, importer, options) {
7337
+ if (shared.entries.includes(source)) {
7338
+ return {
7339
+ // Rename ids because Vite transforms only .html files: https://github.com/vitejs/vite/blob/0cde495ebeb48bcfb5961784a30bfaed997790a0/packages/vite/src/node/plugins/html.ts#L330
7340
+ id: `${source}.html`,
7341
+ resolvedBy: "vite-plugin-php",
7342
+ meta: {
7343
+ originalId: source
7344
+ }
7345
+ };
7346
+ }
7347
+ },
7348
+ load(id, options) {
7349
+ const moduleInfo = this.getModuleInfo(id);
7350
+ const entry = moduleInfo?.meta.originalId;
7351
+ if (entry) {
7352
+ const php = PHP_Code.fromFile(entry).applyEnv().escape();
7353
+ return {
7354
+ code: php.code,
7355
+ meta: { phpMapping: php.mapping }
7356
+ };
7357
+ }
7358
+ },
7359
+ generateBundle: {
7360
+ order: "post",
7361
+ handler(options, bundle, isWrite) {
7362
+ Object.entries(bundle).forEach(([key, item]) => {
7363
+ if (item.type === "asset") {
7364
+ const moduleInfo = this.getModuleInfo(item.fileName);
7365
+ if (moduleInfo?.meta.originalId) {
7366
+ const meta = moduleInfo.meta;
7367
+ item.fileName = meta.originalId;
7368
+ if (meta.phpMapping) {
7369
+ item.source = PHP_Code.unescape(
7370
+ item.source.toString(),
7371
+ meta.phpMapping
7372
+ );
7373
+ }
7374
+ item.source = fixAssetsInjection(
7375
+ item.source.toString()
7376
+ );
7377
+ }
7378
+ } else if (item.type === "chunk" && item.facadeModuleId) {
7379
+ const moduleInfo = this.getModuleInfo(item.facadeModuleId);
7380
+ if (moduleInfo) {
7381
+ const meta = moduleInfo.meta;
7382
+ if (meta.phpMapping) {
7383
+ item.code = PHP_Code.unescape(
7384
+ item.code,
7385
+ meta.phpMapping
7386
+ );
7387
+ }
7388
+ item.code = fixAssetsInjection(item.code);
7389
+ }
7390
+ }
7391
+ });
7392
+ }
7393
+ }
7394
+ };
7395
+
7396
+ function usePHP(cfg = {}) {
7397
+ const { entry = "index.php" } = cfg;
7398
+ PHP_Server.binary = cfg.binary ?? PHP_Server.binary;
7399
+ serve.rewriteUrl = cfg.rewriteUrl ?? serve.rewriteUrl;
7400
+ shared.entries = Array.isArray(entry) ? entry : [entry];
7401
+ shared.tempDir = cfg.tempDir ?? shared.tempDir;
7402
+ shared.devConfig = {
7403
+ cleanup: cfg.dev?.cleanup || shared.devConfig.cleanup,
7404
+ errorLevels: cfg.dev?.errorLevels || shared.devConfig.errorLevels
7405
+ };
7019
7406
  return [
7020
7407
  {
7021
- name: "prepare-php",
7408
+ name: "init-php",
7022
7409
  enforce: "post",
7023
- config(config2, env) {
7024
- const gitIgnoreFile = `${tempDir}/.gitignore`;
7025
- if (!existsSync(gitIgnoreFile)) {
7026
- writeFile(gitIgnoreFile, "*\n**/*.php.html");
7027
- }
7028
- entries = [
7410
+ config(config, env) {
7411
+ shared.entries = [
7029
7412
  ...new Set(
7030
- entries.flatMap(
7413
+ shared.entries.flatMap(
7031
7414
  (entry2) => fastGlob.globSync(entry2, {
7032
7415
  dot: true,
7033
7416
  onlyFiles: true,
7034
7417
  unique: true,
7035
7418
  ignore: [
7036
- tempDir,
7037
- config2.build?.outDir || "dist"
7419
+ shared.tempDir,
7420
+ config.build?.outDir || "dist"
7038
7421
  ]
7039
7422
  })
7040
7423
  )
7041
7424
  )
7042
7425
  ];
7043
- consoleHijack(entries);
7426
+ consoleHijack();
7044
7427
  return {
7045
7428
  build: {
7046
- rollupOptions: { input: entries }
7429
+ rollupOptions: { input: shared.entries }
7047
7430
  },
7048
- optimizeDeps: { entries }
7431
+ optimizeDeps: { entries: shared.entries }
7049
7432
  };
7050
7433
  },
7051
7434
  configResolved(_config) {
7052
- config = _config;
7053
- }
7054
- },
7055
- {
7056
- name: "serve-php",
7057
- apply: "serve",
7058
- enforce: "pre",
7059
- configResolved(_config) {
7060
- config = _config;
7061
- entries.forEach((entry2) => {
7062
- const outputFile = getTempFileName(entry2);
7063
- escapePHP({
7064
- inputFile: entry2,
7065
- config
7066
- }).write(outputFile);
7067
- });
7068
- },
7069
- configureServer(server) {
7070
- viteServer = server;
7071
- phpServer.start(viteServer?.config.root);
7072
- server.middlewares.use(async (req, res, next) => {
7073
- try {
7074
- if (req.url && ![
7075
- "/@vite",
7076
- "/@fs",
7077
- "/@id/__x00__",
7078
- "/node_modules"
7079
- ].some((path) => req.url.startsWith(path))) {
7080
- req.on("error", (error) => {
7081
- throw error;
7082
- });
7083
- res.on("error", (error) => {
7084
- throw error;
7085
- });
7086
- const url = new URL(req.url, "http://localhost");
7087
- if (config?.server.port) {
7088
- url.port = config.server.port.toString();
7089
- }
7090
- const requestUrl = url.pathname;
7091
- if (url.pathname.endsWith("/")) {
7092
- url.pathname += "index.php";
7093
- }
7094
- const routedUrl = rewriteUrl(url);
7095
- if (routedUrl) {
7096
- url.pathname = routedUrl.pathname;
7097
- url.search = routedUrl.search;
7098
- url.hash = routedUrl.hash;
7099
- }
7100
- const entryPathname = url.pathname.substring(1);
7101
- const entry2 = entries.find((file) => {
7102
- return file === entryPathname || file.substring(0, file.lastIndexOf(".")) === entryPathname;
7103
- });
7104
- if (entry2) {
7105
- const tempFile = getTempFileName(entry2);
7106
- if (existsSync(resolve(tempFile))) {
7107
- url.pathname = tempFile;
7108
- url.port = phpServer.port.toString();
7109
- url.searchParams.set(
7110
- internalParam,
7111
- new URLSearchParams({
7112
- REQUEST_URI: requestUrl,
7113
- PHP_SELF: "/" + entry2
7114
- }).toString()
7115
- );
7116
- const body = await new Promise(
7117
- (resolve2, reject) => {
7118
- let data = [];
7119
- req.on("data", (chunk) => {
7120
- data.push(chunk);
7121
- }).on("end", () => {
7122
- resolve2(Buffer.concat(data));
7123
- });
7124
- }
7125
- );
7126
- const phpResult = await new Promise(async (resolve2, reject) => {
7127
- const chunks = [];
7128
- let statusCode;
7129
- let incomingHeaders = {};
7130
- const request = http.request(
7131
- url.toString(),
7132
- {
7133
- method: req.method,
7134
- headers: {
7135
- ...req.headers,
7136
- "content-length": Buffer.byteLength(
7137
- body
7138
- )
7139
- }
7140
- },
7141
- (msg) => {
7142
- statusCode = msg.statusCode;
7143
- incomingHeaders = msg.headers;
7144
- msg.on("data", (data) => {
7145
- chunks.push(data);
7146
- });
7147
- }
7148
- ).on("error", (error) => {
7149
- reject(error);
7150
- }).on("close", () => {
7151
- const content = Buffer.concat(
7152
- chunks
7153
- ).toString("utf8");
7154
- resolve2({
7155
- statusCode,
7156
- headers: incomingHeaders,
7157
- content
7158
- });
7159
- });
7160
- request.write(body, (error) => {
7161
- if (error) {
7162
- reject(error);
7163
- }
7164
- });
7165
- request.end();
7166
- });
7167
- let out = phpResult.content;
7168
- if (phpResult.headers["content-type"]?.includes("html")) {
7169
- out = await server.transformIndexHtml(
7170
- requestUrl,
7171
- out,
7172
- "/" + entryPathname
7173
- );
7174
- }
7175
- res.writeHead(
7176
- phpResult.statusCode || 200,
7177
- phpResult.headers
7178
- ).end(out);
7179
- return;
7180
- }
7181
- }
7182
- }
7183
- } catch (error) {
7184
- console.error("Vite-PHP Error: " + error);
7185
- }
7186
- next();
7187
- });
7188
- },
7189
- async handleHotUpdate({ server, file }) {
7190
- const entry2 = entries.find(
7191
- (entryFile) => resolve(entryFile) === file
7192
- );
7193
- if (entry2) {
7194
- const outputFile = getTempFileName(entry2);
7195
- escapePHP({
7196
- inputFile: entry2,
7197
- config
7198
- }).write(outputFile);
7199
- server.moduleGraph.invalidateAll();
7200
- }
7201
- if (entry2 || !file.startsWith(resolve(tempDir)) && file.includes(".php")) {
7202
- server.ws.send({
7203
- type: "full-reload"
7204
- });
7205
- }
7435
+ shared.viteConfig = _config;
7206
7436
  }
7207
7437
  },
7208
- {
7209
- name: "build-php",
7210
- apply: "build",
7211
- enforce: "pre",
7212
- resolveId(source, importer, options) {
7213
- if (entries.includes(source)) {
7214
- return {
7215
- // Rename ids because Vite transforms only .html files: https://github.com/vitejs/vite/blob/0cde495ebeb48bcfb5961784a30bfaed997790a0/packages/vite/src/node/plugins/html.ts#L330
7216
- id: `${source}.html`,
7217
- resolvedBy: "vite-plugin-php",
7218
- meta: {
7219
- originalId: source
7220
- }
7221
- };
7222
- }
7223
- },
7224
- load(id, options) {
7225
- const entry2 = this.getModuleInfo(id)?.meta.originalId;
7226
- if (entry2) {
7227
- const { escapedCode, phpCodes } = escapePHP({
7228
- inputFile: entry2,
7229
- config
7230
- });
7231
- return {
7232
- code: escapedCode,
7233
- meta: { phpCodes }
7234
- };
7235
- }
7236
- },
7237
- generateBundle: {
7238
- order: "post",
7239
- handler(options, bundle, isWrite) {
7240
- Object.entries(bundle).forEach(([key, item]) => {
7241
- if (item.type === "asset") {
7242
- const meta = this.getModuleInfo(
7243
- item.fileName
7244
- )?.meta;
7245
- if (meta?.originalId && meta?.phpCodes) {
7246
- item.fileName = meta.originalId;
7247
- item.source = unescapePHP({
7248
- escapedCode: item.source.toString(),
7249
- phpCodes: meta.phpCodes
7250
- });
7251
- }
7252
- } else if (item.type === "chunk" && item.facadeModuleId) {
7253
- const meta = this.getModuleInfo(
7254
- item.facadeModuleId
7255
- )?.meta;
7256
- if (meta?.phpCodes) {
7257
- item.code = unescapePHP({
7258
- escapedCode: item.code,
7259
- phpCodes: meta.phpCodes
7260
- });
7261
- }
7262
- }
7263
- });
7264
- }
7265
- }
7266
- }
7438
+ servePlugin,
7439
+ buildPlugin
7267
7440
  ];
7268
7441
  }
7269
7442
 
7270
- export { usePHP as default };
7443
+ export { EPHPError, usePHP as default };