vite-plugin-php 1.0.31 → 1.0.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,11 +20,13 @@ Check out the [starter repo](https://github.com/nititech/php-vite-starter) for a
20
20
 
21
21
  ## ⚡ Latest changes
22
22
 
23
- | Version | Feature |
24
- | ------- | ------------------------ |
25
- | 1.0.30 | PHP header forwarding |
26
- | 1.0.20 | URL rewrites |
27
- | 1.0.11 | Improved Windows support |
23
+ | Version | Feature |
24
+ | ------- | ------------------------------------------------------------------------------------- |
25
+ | 1.0.50 | Using native Rollup pipeline to generate bundle -> proper error messages during build |
26
+ | 1.0.40 | Vite's "HTML Env Replacement" feature in transpiled PHP files |
27
+ | 1.0.30 | Proper PHP header forwarding during development |
28
+ | 1.0.20 | URL rewrite functionality to mimic mod_rewrite & friends |
29
+ | 1.0.11 | Improved Windows support |
28
30
 
29
31
  ## Write some PHP code in your `index.php`
30
32
 
package/dist/index.cjs CHANGED
@@ -1,65 +1,203 @@
1
1
  'use strict';
2
2
 
3
- const require$$0 = require('fs');
3
+ const require$$0$2 = require('fs');
4
4
  const require$$0$1 = require('path');
5
+ const vite = require('vite');
6
+ const require$$0 = require('tty');
5
7
  const http = require('http');
6
8
  const child_process = require('child_process');
7
9
  const url = require('url');
8
- const require$$0$2 = require('os');
9
- const require$$0$3 = require('util');
10
- const require$$0$4 = require('stream');
11
- const require$$0$5 = require('events');
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');
12
14
 
13
15
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
14
16
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
15
17
 
16
- const require$$0__default$4 = /*#__PURE__*/_interopDefaultCompat(require$$0);
17
- const require$$0__default$1 = /*#__PURE__*/_interopDefaultCompat(require$$0$1);
18
+ const require$$0__default$5 = /*#__PURE__*/_interopDefaultCompat(require$$0$2);
19
+ const require$$0__default$2 = /*#__PURE__*/_interopDefaultCompat(require$$0$1);
20
+ const require$$0__default = /*#__PURE__*/_interopDefaultCompat(require$$0);
18
21
  const http__default = /*#__PURE__*/_interopDefaultCompat(http);
19
- const require$$0__default = /*#__PURE__*/_interopDefaultCompat(require$$0$2);
20
- const require$$0__default$2 = /*#__PURE__*/_interopDefaultCompat(require$$0$3);
22
+ const require$$0__default$1 = /*#__PURE__*/_interopDefaultCompat(require$$0$3);
21
23
  const require$$0__default$3 = /*#__PURE__*/_interopDefaultCompat(require$$0$4);
22
- const require$$0__default$5 = /*#__PURE__*/_interopDefaultCompat(require$$0$5);
24
+ const require$$0__default$4 = /*#__PURE__*/_interopDefaultCompat(require$$0$5);
25
+ const require$$0__default$6 = /*#__PURE__*/_interopDefaultCompat(require$$0$6);
23
26
 
24
27
  function makeID() {
25
28
  return Date.now().toString(36) + Math.random() * 100;
26
29
  }
27
30
 
31
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
32
+
33
+ function getDefaultExportFromCjs (x) {
34
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
35
+ }
36
+
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
+ var picocolors = {exports: {}};
42
+
43
+ let argv = process.argv || [],
44
+ env = process.env;
45
+ 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) =>
55
+ 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
61
+ };
62
+
63
+ let replaceClose = (string, close, replace, index) => {
64
+ let result = "";
65
+ let cursor = 0;
66
+ do {
67
+ result += string.substring(cursor, index) + replace;
68
+ cursor = index + close.length;
69
+ index = string.indexOf(close, cursor);
70
+ } while (~index)
71
+ return result + string.substring(cursor)
72
+ };
73
+
74
+ let createColors = (enabled = isColorSupported) => {
75
+ let init = enabled ? formatter : () => String;
76
+ return {
77
+ 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
+ black: init("\x1b[30m", "\x1b[39m"),
87
+ red: init("\x1b[31m", "\x1b[39m"),
88
+ green: init("\x1b[32m", "\x1b[39m"),
89
+ yellow: init("\x1b[33m", "\x1b[39m"),
90
+ blue: init("\x1b[34m", "\x1b[39m"),
91
+ magenta: init("\x1b[35m", "\x1b[39m"),
92
+ cyan: init("\x1b[36m", "\x1b[39m"),
93
+ white: init("\x1b[37m", "\x1b[39m"),
94
+ gray: init("\x1b[90m", "\x1b[39m"),
95
+ bgBlack: init("\x1b[40m", "\x1b[49m"),
96
+ bgRed: init("\x1b[41m", "\x1b[49m"),
97
+ bgGreen: init("\x1b[42m", "\x1b[49m"),
98
+ bgYellow: init("\x1b[43m", "\x1b[49m"),
99
+ bgBlue: init("\x1b[44m", "\x1b[49m"),
100
+ bgMagenta: init("\x1b[45m", "\x1b[49m"),
101
+ bgCyan: init("\x1b[46m", "\x1b[49m"),
102
+ bgWhite: init("\x1b[47m", "\x1b[49m"),
103
+ }
104
+ };
105
+
106
+ picocolors.exports = createColors();
107
+ picocolors.exports.createColors = createColors;
108
+
109
+ var picocolorsExports = picocolors.exports;
110
+ const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
111
+
112
+ function resolveEnvPrefix({ envPrefix = "VITE_" }) {
113
+ envPrefix = Array.isArray(envPrefix) ? envPrefix : [envPrefix];
114
+ if (envPrefix.includes("")) {
115
+ throw new Error(
116
+ `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
117
+ );
118
+ }
119
+ return envPrefix;
120
+ }
121
+ const envPattern = /%(\S+?)%/g;
122
+ function initReplaceEnv(config) {
123
+ const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
124
+ const env = { ...config.env };
125
+ for (const key in config.define) {
126
+ if (key.startsWith(`import.meta.env.`)) {
127
+ const val = config.define[key];
128
+ if (typeof val === "string") {
129
+ try {
130
+ const parsed = JSON.parse(val);
131
+ env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
132
+ } catch {
133
+ env[key.slice(16)] = val;
134
+ }
135
+ } else {
136
+ env[key.slice(16)] = JSON.stringify(val);
137
+ }
138
+ }
139
+ }
140
+ return function replaceEnv(content, filename) {
141
+ return content.replace(envPattern, (text, key) => {
142
+ if (key in env) {
143
+ return env[key];
144
+ } else {
145
+ if (envPrefix.some((prefix) => key.startsWith(prefix))) {
146
+ const relativeHtml = vite.normalizePath(
147
+ require$$0$1.relative(config.root, filename)
148
+ );
149
+ config.logger.warn(
150
+ colors.yellow(
151
+ colors.bold(
152
+ `(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
153
+ )
154
+ )
155
+ );
156
+ }
157
+ return text;
158
+ }
159
+ });
160
+ };
161
+ }
162
+
28
163
  function writeFile(file, data) {
29
- require$$0.mkdirSync(require$$0$1.dirname(file), { recursive: true });
30
- require$$0.writeFileSync(file, data);
164
+ require$$0$2.mkdirSync(require$$0$1.dirname(file), { recursive: true });
165
+ require$$0$2.writeFileSync(file, data);
31
166
  }
32
167
 
33
- function escapePHP(inputFile, outputFile) {
34
- const input = require$$0.readFileSync(inputFile).toString();
35
- const codeTokens = {};
168
+ const phpTagPattern = /<\?(?:php|).+?(\?>|$)/gis;
169
+ function escapePHP({ inputFile, config }) {
170
+ const replaceEnv = initReplaceEnv(config);
171
+ const input = require$$0$2.readFileSync(inputFile, "utf-8").toString();
172
+ const phpCodes = {};
36
173
  const isJS = inputFile.includes(".js") || inputFile.includes(".ts");
37
174
  const isML = inputFile.includes(".php") || inputFile.includes(".htm");
38
- const out = input.replace(/<\?(?:php|).+?(\?>|$)/gis, (match) => {
175
+ const escapedCode = input.replace(phpTagPattern, (match) => {
39
176
  let token = makeID();
40
177
  if (isJS) {
41
178
  token = `/*${token}*/`;
42
179
  } else if (isML) {
43
180
  token = `<!--${token}-->`;
44
181
  }
45
- codeTokens[token] = match;
182
+ phpCodes[token] = replaceEnv(match, inputFile);
46
183
  return token;
47
184
  });
48
- writeFile(outputFile + ".json", JSON.stringify(codeTokens));
49
- writeFile(outputFile, out);
50
- }
51
- function unescapePHP(file, tokensFile) {
52
- const input = require$$0.readFileSync(file).toString();
53
- let out = input;
54
- const tknsFile = tokensFile || file + ".json";
55
- if (require$$0.existsSync(tknsFile)) {
56
- const codeTokens = JSON.parse(require$$0.readFileSync(tknsFile).toString());
57
- Object.entries(codeTokens).forEach(([token, code]) => {
58
- out = out.replace(token, (match) => {
59
- return `${code}`;
60
- });
185
+ return {
186
+ escapedCode,
187
+ phpCodes,
188
+ write(outputFile) {
189
+ writeFile(outputFile, escapedCode);
190
+ writeFile(outputFile + ".json", JSON.stringify(phpCodes));
191
+ }
192
+ };
193
+ }
194
+ function unescapePHP({ escapedCode, phpCodes }) {
195
+ let out = escapedCode;
196
+ Object.entries(phpCodes).forEach(([token, code]) => {
197
+ out = out.replace(token, (match) => {
198
+ return `${code}`;
61
199
  });
62
- }
200
+ });
63
201
  return out;
64
202
  }
65
203
 
@@ -102,12 +240,6 @@ const phpServer = {
102
240
  stop
103
241
  };
104
242
 
105
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
106
-
107
- function getDefaultExportFromCjs (x) {
108
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
109
- }
110
-
111
243
  var tasks = {};
112
244
 
113
245
  var utils$k = {};
@@ -170,8 +302,8 @@ var path$9 = {};
170
302
 
171
303
  Object.defineProperty(path$9, "__esModule", { value: true });
172
304
  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;
173
- const os = require$$0__default;
174
- const path$8 = require$$0__default$1;
305
+ const os = require$$0__default$1;
306
+ const path$8 = require$$0__default$2;
175
307
  const IS_WINDOWS_PLATFORM = os.platform() === 'win32';
176
308
  const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
177
309
  /**
@@ -411,8 +543,8 @@ var isGlob$1 = function isGlob(str, options) {
411
543
  };
412
544
 
413
545
  var isGlob = isGlob$1;
414
- var pathPosixDirname = require$$0__default$1.posix.dirname;
415
- var isWin32 = require$$0__default.platform() === 'win32';
546
+ var pathPosixDirname = require$$0__default$2.posix.dirname;
547
+ var isWin32 = require$$0__default$1.platform() === 'win32';
416
548
 
417
549
  var slash = '/';
418
550
  var backslash = /\\/g;
@@ -908,7 +1040,7 @@ var toRegexRange_1 = toRegexRange$1;
908
1040
  * Licensed under the MIT License.
909
1041
  */
910
1042
 
911
- const util$1 = require$$0__default$2;
1043
+ const util$1 = require$$0__default$3;
912
1044
  const toRegexRange = toRegexRange_1;
913
1045
 
914
1046
  const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
@@ -1873,7 +2005,7 @@ var braces_1 = braces$1;
1873
2005
 
1874
2006
  var utils$f = {};
1875
2007
 
1876
- const path$7 = require$$0__default$1;
2008
+ const path$7 = require$$0__default$2;
1877
2009
  const WIN_SLASH = '\\\\/';
1878
2010
  const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
1879
2011
 
@@ -2053,7 +2185,7 @@ var constants$3 = {
2053
2185
 
2054
2186
  (function (exports) {
2055
2187
 
2056
- const path = require$$0__default$1;
2188
+ const path = require$$0__default$2;
2057
2189
  const win32 = process.platform === 'win32';
2058
2190
  const {
2059
2191
  REGEX_BACKSLASH,
@@ -3597,7 +3729,7 @@ parse$1.fastpaths = (input, options) => {
3597
3729
 
3598
3730
  var parse_1 = parse$1;
3599
3731
 
3600
- const path$6 = require$$0__default$1;
3732
+ const path$6 = require$$0__default$2;
3601
3733
  const scan = scan_1;
3602
3734
  const parse = parse_1;
3603
3735
  const utils$c = utils$f;
@@ -3940,7 +4072,7 @@ var picomatch_1 = picomatch$2;
3940
4072
 
3941
4073
  var picomatch$1 = picomatch_1;
3942
4074
 
3943
- const util = require$$0__default$2;
4075
+ const util = require$$0__default$3;
3944
4076
  const braces = braces_1;
3945
4077
  const picomatch = picomatch$1;
3946
4078
  const utils$b = utils$f;
@@ -4408,7 +4540,7 @@ var micromatch_1 = micromatch$1;
4408
4540
 
4409
4541
  Object.defineProperty(pattern$1, "__esModule", { value: true });
4410
4542
  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;
4411
- const path$5 = require$$0__default$1;
4543
+ const path$5 = require$$0__default$2;
4412
4544
  const globParent = globParent$1;
4413
4545
  const micromatch = micromatch_1;
4414
4546
  const GLOBSTAR = '**';
@@ -4603,7 +4735,7 @@ var stream$4 = {};
4603
4735
  * Copyright (c) 2014-2020 Teambition
4604
4736
  * Licensed under the MIT license.
4605
4737
  */
4606
- const Stream = require$$0__default$3;
4738
+ const Stream = require$$0__default$4;
4607
4739
  const PassThrough = Stream.PassThrough;
4608
4740
  const slice = Array.prototype.slice;
4609
4741
 
@@ -4983,7 +5115,7 @@ var fs$5 = {};
4983
5115
  (function (exports) {
4984
5116
  Object.defineProperty(exports, "__esModule", { value: true });
4985
5117
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
4986
- const fs = require$$0__default$4;
5118
+ const fs = require$$0__default$5;
4987
5119
  exports.FILE_SYSTEM_ADAPTER = {
4988
5120
  lstat: fs.lstat,
4989
5121
  stat: fs.stat,
@@ -5334,7 +5466,7 @@ var fs$1 = {};
5334
5466
  (function (exports) {
5335
5467
  Object.defineProperty(exports, "__esModule", { value: true });
5336
5468
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
5337
- const fs = require$$0__default$4;
5469
+ const fs = require$$0__default$5;
5338
5470
  exports.FILE_SYSTEM_ADAPTER = {
5339
5471
  lstat: fs.lstat,
5340
5472
  stat: fs.stat,
@@ -5353,7 +5485,7 @@ var fs$1 = {};
5353
5485
  } (fs$1));
5354
5486
 
5355
5487
  Object.defineProperty(settings$2, "__esModule", { value: true });
5356
- const path$3 = require$$0__default$1;
5488
+ const path$3 = require$$0__default$2;
5357
5489
  const fsStat$3 = out$1;
5358
5490
  const fs = fs$1;
5359
5491
  let Settings$1 = class Settings {
@@ -5795,7 +5927,7 @@ let Reader$1 = class Reader {
5795
5927
  reader$1.default = Reader$1;
5796
5928
 
5797
5929
  Object.defineProperty(async$4, "__esModule", { value: true });
5798
- const events_1 = require$$0__default$5;
5930
+ const events_1 = require$$0__default$6;
5799
5931
  const fsScandir$2 = out$2;
5800
5932
  const fastq = queueExports;
5801
5933
  const common$1 = common$3;
@@ -5924,7 +6056,7 @@ function callSuccessCallback(callback, entries) {
5924
6056
  var stream$2 = {};
5925
6057
 
5926
6058
  Object.defineProperty(stream$2, "__esModule", { value: true });
5927
- const stream_1$5 = require$$0__default$3;
6059
+ const stream_1$5 = require$$0__default$4;
5928
6060
  const async_1$3 = async$4;
5929
6061
  class StreamProvider {
5930
6062
  constructor(_root, _settings) {
@@ -6037,7 +6169,7 @@ sync$3.default = SyncProvider;
6037
6169
  var settings$1 = {};
6038
6170
 
6039
6171
  Object.defineProperty(settings$1, "__esModule", { value: true });
6040
- const path$2 = require$$0__default$1;
6172
+ const path$2 = require$$0__default$2;
6041
6173
  const fsScandir = out$2;
6042
6174
  class Settings {
6043
6175
  constructor(_options = {}) {
@@ -6099,7 +6231,7 @@ function getSettings(settingsOrOptions = {}) {
6099
6231
  var reader = {};
6100
6232
 
6101
6233
  Object.defineProperty(reader, "__esModule", { value: true });
6102
- const path$1 = require$$0__default$1;
6234
+ const path$1 = require$$0__default$2;
6103
6235
  const fsStat$2 = out$1;
6104
6236
  const utils$6 = utils$k;
6105
6237
  class Reader {
@@ -6134,7 +6266,7 @@ reader.default = Reader;
6134
6266
  var stream$1 = {};
6135
6267
 
6136
6268
  Object.defineProperty(stream$1, "__esModule", { value: true });
6137
- const stream_1$3 = require$$0__default$3;
6269
+ const stream_1$3 = require$$0__default$4;
6138
6270
  const fsStat$1 = out$1;
6139
6271
  const fsWalk$2 = out$3;
6140
6272
  const reader_1$2 = reader;
@@ -6487,7 +6619,7 @@ class EntryTransformer {
6487
6619
  entry.default = EntryTransformer;
6488
6620
 
6489
6621
  Object.defineProperty(provider, "__esModule", { value: true });
6490
- const path = require$$0__default$1;
6622
+ const path = require$$0__default$2;
6491
6623
  const deep_1 = deep;
6492
6624
  const entry_1 = entry$1;
6493
6625
  const error_1 = error;
@@ -6560,7 +6692,7 @@ async$7.default = ProviderAsync;
6560
6692
  var stream = {};
6561
6693
 
6562
6694
  Object.defineProperty(stream, "__esModule", { value: true });
6563
- const stream_1$1 = require$$0__default$3;
6695
+ const stream_1$1 = require$$0__default$4;
6564
6696
  const stream_2 = stream$1;
6565
6697
  const provider_1$1 = provider;
6566
6698
  class ProviderStream extends provider_1$1.default {
@@ -6665,8 +6797,8 @@ var settings = {};
6665
6797
  (function (exports) {
6666
6798
  Object.defineProperty(exports, "__esModule", { value: true });
6667
6799
  exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
6668
- const fs = require$$0__default$4;
6669
- const os = require$$0__default;
6800
+ const fs = require$$0__default$5;
6801
+ const os = require$$0__default$1;
6670
6802
  /**
6671
6803
  * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
6672
6804
  * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
@@ -6825,6 +6957,22 @@ var out = FastGlob;
6825
6957
 
6826
6958
  const fastGlob = /*@__PURE__*/getDefaultExportFromCjs(out);
6827
6959
 
6960
+ function consoleHijack(entries) {
6961
+ ["log", "info", "warn", "error"].forEach((command) => {
6962
+ const cx = console[command];
6963
+ console[command] = function(...args) {
6964
+ cx.apply(
6965
+ this,
6966
+ args.map(
6967
+ (arg) => typeof arg === "string" ? entries.reduce((acc, entry) => {
6968
+ return acc.replace(entry + ".html", entry);
6969
+ }, arg) : arg
6970
+ )
6971
+ );
6972
+ };
6973
+ });
6974
+ }
6975
+
6828
6976
  const internalParam = "__314159265359__";
6829
6977
  function usePHP(cfg = {}) {
6830
6978
  const {
@@ -6839,14 +6987,11 @@ function usePHP(cfg = {}) {
6839
6987
  let config = void 0;
6840
6988
  let viteServer = void 0;
6841
6989
  let entries = Array.isArray(entry) ? entry : [entry];
6842
- function escapeFile(file) {
6843
- const tempFile = `${tempDir}/${file}.html`;
6844
- escapePHP(file, tempFile);
6845
- return tempFile;
6990
+ function getTempFileName(file) {
6991
+ return `${tempDir}/${file}.html`;
6846
6992
  }
6847
- function cleanupTemp(dir = "") {
6848
- const parentDir = dir ? dir + "/" : dir;
6849
- require$$0.rmSync(parentDir + tempDir, { recursive: true, force: true });
6993
+ function cleanupTemp() {
6994
+ require$$0$2.rmSync(tempDir, { recursive: true, force: true });
6850
6995
  }
6851
6996
  function onExit() {
6852
6997
  if (config?.command === "serve") {
@@ -6871,23 +7016,30 @@ function usePHP(cfg = {}) {
6871
7016
  enforce: "post",
6872
7017
  config(config2, env) {
6873
7018
  const gitIgnoreFile = `${tempDir}/.gitignore`;
6874
- if (!require$$0.existsSync(gitIgnoreFile)) {
7019
+ if (!require$$0$2.existsSync(gitIgnoreFile)) {
6875
7020
  writeFile(gitIgnoreFile, "*\n**/*.php.html");
6876
7021
  }
6877
- entries = entries.flatMap(
6878
- (entry2) => fastGlob.globSync(entry2, {
6879
- dot: true,
6880
- onlyFiles: true,
6881
- unique: true,
6882
- ignore: [tempDir, config2.build?.outDir || "dist"]
6883
- })
6884
- );
6885
- const inputs = entries.map(escapeFile);
7022
+ entries = [
7023
+ ...new Set(
7024
+ entries.flatMap(
7025
+ (entry2) => fastGlob.globSync(entry2, {
7026
+ dot: true,
7027
+ onlyFiles: true,
7028
+ unique: true,
7029
+ ignore: [
7030
+ tempDir,
7031
+ config2.build?.outDir || "dist"
7032
+ ]
7033
+ })
7034
+ )
7035
+ )
7036
+ ];
7037
+ consoleHijack(entries);
6886
7038
  return {
6887
7039
  build: {
6888
- rollupOptions: { input: inputs }
7040
+ rollupOptions: { input: entries }
6889
7041
  },
6890
- optimizeDeps: { entries: inputs }
7042
+ optimizeDeps: { entries }
6891
7043
  };
6892
7044
  },
6893
7045
  configResolved(_config) {
@@ -6898,6 +7050,16 @@ function usePHP(cfg = {}) {
6898
7050
  name: "serve-php",
6899
7051
  apply: "serve",
6900
7052
  enforce: "pre",
7053
+ configResolved(_config) {
7054
+ config = _config;
7055
+ entries.forEach((entry2) => {
7056
+ const outputFile = getTempFileName(entry2);
7057
+ escapePHP({
7058
+ inputFile: entry2,
7059
+ config
7060
+ }).write(outputFile);
7061
+ });
7062
+ },
6901
7063
  configureServer(server) {
6902
7064
  viteServer = server;
6903
7065
  phpServer.start(viteServer?.config.root);
@@ -6925,8 +7087,8 @@ function usePHP(cfg = {}) {
6925
7087
  return file === entryPathname || file.substring(0, file.lastIndexOf(".")) === entryPathname;
6926
7088
  });
6927
7089
  if (entry2) {
6928
- const tempFile = `${tempDir}/${entry2}.html`;
6929
- if (require$$0.existsSync(require$$0$1.resolve(tempFile))) {
7090
+ const tempFile = getTempFileName(entry2);
7091
+ if (require$$0$2.existsSync(require$$0$1.resolve(tempFile))) {
6930
7092
  url.pathname = tempFile;
6931
7093
  url.port = phpServer.port.toString();
6932
7094
  url.searchParams.set(
@@ -6963,7 +7125,7 @@ function usePHP(cfg = {}) {
6963
7125
  ).on("error", reject).end();
6964
7126
  });
6965
7127
  const out = await server.transformIndexHtml(
6966
- entryPathname || "/",
7128
+ "/" + entryPathname,
6967
7129
  phpResult.content,
6968
7130
  req.originalUrl
6969
7131
  );
@@ -6983,10 +7145,14 @@ function usePHP(cfg = {}) {
6983
7145
  },
6984
7146
  handleHotUpdate({ server, file }) {
6985
7147
  const entry2 = entries.find(
6986
- (entryFile) => file.endsWith(entryFile) && require$$0$1.resolve(entryFile) === file
7148
+ (entryFile) => require$$0$1.resolve(entryFile) === file
6987
7149
  );
6988
7150
  if (entry2) {
6989
- escapeFile(entry2);
7151
+ const outputFile = getTempFileName(entry2);
7152
+ escapePHP({
7153
+ inputFile: entry2,
7154
+ config
7155
+ }).write(outputFile);
6990
7156
  server.ws.send({
6991
7157
  type: "full-reload",
6992
7158
  path: "*"
@@ -6997,21 +7163,49 @@ function usePHP(cfg = {}) {
6997
7163
  {
6998
7164
  name: "build-php",
6999
7165
  apply: "build",
7166
+ enforce: "pre",
7000
7167
  resolveId(source, importer, options) {
7001
- if (importer?.endsWith(".html") && importer.includes(`/${tempDir}/`)) {
7002
- return { id: require$$0$1.resolve(source) };
7168
+ if (entries.includes(source)) {
7169
+ return {
7170
+ id: `${source}.html`,
7171
+ resolvedBy: "vite-plugin-php",
7172
+ meta: {
7173
+ originalId: source
7174
+ }
7175
+ };
7003
7176
  }
7004
7177
  },
7005
- closeBundle() {
7006
- const distDir = config?.build.outDir;
7007
- entries.forEach((file) => {
7008
- const code = unescapePHP(
7009
- `${distDir}/${tempDir}/${file}.html`,
7010
- `${tempDir}/${file}.html.json`
7011
- );
7012
- writeFile(`${distDir}/${file}`, code);
7013
- });
7014
- cleanupTemp(distDir);
7178
+ load(id, options) {
7179
+ const entry2 = this.getModuleInfo(id)?.meta.originalId;
7180
+ if (entry2) {
7181
+ const { escapedCode, phpCodes } = escapePHP({
7182
+ inputFile: entry2,
7183
+ config
7184
+ });
7185
+ return {
7186
+ code: escapedCode,
7187
+ meta: { phpCodes }
7188
+ };
7189
+ }
7190
+ },
7191
+ generateBundle: {
7192
+ order: "post",
7193
+ handler(options, bundle, isWrite) {
7194
+ Object.entries(bundle).forEach(([key, item]) => {
7195
+ if (item.type === "asset") {
7196
+ const meta = this.getModuleInfo(
7197
+ item.fileName
7198
+ )?.meta;
7199
+ if (meta?.originalId && meta?.phpCodes) {
7200
+ item.fileName = meta.originalId;
7201
+ item.source = unescapePHP({
7202
+ escapedCode: item.source.toString(),
7203
+ phpCodes: meta.phpCodes
7204
+ });
7205
+ }
7206
+ }
7207
+ });
7208
+ }
7015
7209
  }
7016
7210
  }
7017
7211
  ];
package/dist/index.mjs CHANGED
@@ -1,52 +1,189 @@
1
- import require$$0$4, { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'fs';
2
- import require$$0$1, { dirname, resolve } from 'path';
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';
3
5
  import http from 'http';
4
6
  import { spawn } from 'child_process';
5
7
  import { fileURLToPath } from 'url';
6
- import require$$0 from 'os';
7
- import require$$0$2 from 'util';
8
- import require$$0$3 from 'stream';
9
- import require$$0$5 from 'events';
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';
10
12
 
11
13
  function makeID() {
12
14
  return Date.now().toString(36) + Math.random() * 100;
13
15
  }
14
16
 
17
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
18
+
19
+ function getDefaultExportFromCjs (x) {
20
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
21
+ }
22
+
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
+ var picocolors = {exports: {}};
28
+
29
+ let argv = process.argv || [],
30
+ env = process.env;
31
+ 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) =>
41
+ 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
47
+ };
48
+
49
+ let replaceClose = (string, close, replace, index) => {
50
+ let result = "";
51
+ let cursor = 0;
52
+ do {
53
+ result += string.substring(cursor, index) + replace;
54
+ cursor = index + close.length;
55
+ index = string.indexOf(close, cursor);
56
+ } while (~index)
57
+ return result + string.substring(cursor)
58
+ };
59
+
60
+ let createColors = (enabled = isColorSupported) => {
61
+ let init = enabled ? formatter : () => String;
62
+ return {
63
+ 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
+ black: init("\x1b[30m", "\x1b[39m"),
73
+ red: init("\x1b[31m", "\x1b[39m"),
74
+ green: init("\x1b[32m", "\x1b[39m"),
75
+ yellow: init("\x1b[33m", "\x1b[39m"),
76
+ blue: init("\x1b[34m", "\x1b[39m"),
77
+ magenta: init("\x1b[35m", "\x1b[39m"),
78
+ cyan: init("\x1b[36m", "\x1b[39m"),
79
+ white: init("\x1b[37m", "\x1b[39m"),
80
+ gray: init("\x1b[90m", "\x1b[39m"),
81
+ bgBlack: init("\x1b[40m", "\x1b[49m"),
82
+ bgRed: init("\x1b[41m", "\x1b[49m"),
83
+ bgGreen: init("\x1b[42m", "\x1b[49m"),
84
+ bgYellow: init("\x1b[43m", "\x1b[49m"),
85
+ bgBlue: init("\x1b[44m", "\x1b[49m"),
86
+ bgMagenta: init("\x1b[45m", "\x1b[49m"),
87
+ bgCyan: init("\x1b[46m", "\x1b[49m"),
88
+ bgWhite: init("\x1b[47m", "\x1b[49m"),
89
+ }
90
+ };
91
+
92
+ picocolors.exports = createColors();
93
+ picocolors.exports.createColors = createColors;
94
+
95
+ var picocolorsExports = picocolors.exports;
96
+ const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
97
+
98
+ function resolveEnvPrefix({ envPrefix = "VITE_" }) {
99
+ envPrefix = Array.isArray(envPrefix) ? envPrefix : [envPrefix];
100
+ if (envPrefix.includes("")) {
101
+ throw new Error(
102
+ `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
103
+ );
104
+ }
105
+ return envPrefix;
106
+ }
107
+ const envPattern = /%(\S+?)%/g;
108
+ function initReplaceEnv(config) {
109
+ const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
110
+ const env = { ...config.env };
111
+ for (const key in config.define) {
112
+ if (key.startsWith(`import.meta.env.`)) {
113
+ const val = config.define[key];
114
+ if (typeof val === "string") {
115
+ try {
116
+ const parsed = JSON.parse(val);
117
+ env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
118
+ } catch {
119
+ env[key.slice(16)] = val;
120
+ }
121
+ } else {
122
+ env[key.slice(16)] = JSON.stringify(val);
123
+ }
124
+ }
125
+ }
126
+ return function replaceEnv(content, filename) {
127
+ return content.replace(envPattern, (text, key) => {
128
+ if (key in env) {
129
+ return env[key];
130
+ } else {
131
+ if (envPrefix.some((prefix) => key.startsWith(prefix))) {
132
+ const relativeHtml = normalizePath(
133
+ relative(config.root, filename)
134
+ );
135
+ config.logger.warn(
136
+ colors.yellow(
137
+ colors.bold(
138
+ `(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
139
+ )
140
+ )
141
+ );
142
+ }
143
+ return text;
144
+ }
145
+ });
146
+ };
147
+ }
148
+
15
149
  function writeFile(file, data) {
16
150
  mkdirSync(dirname(file), { recursive: true });
17
151
  writeFileSync(file, data);
18
152
  }
19
153
 
20
- function escapePHP(inputFile, outputFile) {
21
- const input = readFileSync(inputFile).toString();
22
- const codeTokens = {};
154
+ const phpTagPattern = /<\?(?:php|).+?(\?>|$)/gis;
155
+ function escapePHP({ inputFile, config }) {
156
+ const replaceEnv = initReplaceEnv(config);
157
+ const input = readFileSync(inputFile, "utf-8").toString();
158
+ const phpCodes = {};
23
159
  const isJS = inputFile.includes(".js") || inputFile.includes(".ts");
24
160
  const isML = inputFile.includes(".php") || inputFile.includes(".htm");
25
- const out = input.replace(/<\?(?:php|).+?(\?>|$)/gis, (match) => {
161
+ const escapedCode = input.replace(phpTagPattern, (match) => {
26
162
  let token = makeID();
27
163
  if (isJS) {
28
164
  token = `/*${token}*/`;
29
165
  } else if (isML) {
30
166
  token = `<!--${token}-->`;
31
167
  }
32
- codeTokens[token] = match;
168
+ phpCodes[token] = replaceEnv(match, inputFile);
33
169
  return token;
34
170
  });
35
- writeFile(outputFile + ".json", JSON.stringify(codeTokens));
36
- writeFile(outputFile, out);
37
- }
38
- function unescapePHP(file, tokensFile) {
39
- const input = readFileSync(file).toString();
40
- let out = input;
41
- const tknsFile = tokensFile || file + ".json";
42
- if (existsSync(tknsFile)) {
43
- const codeTokens = JSON.parse(readFileSync(tknsFile).toString());
44
- Object.entries(codeTokens).forEach(([token, code]) => {
45
- out = out.replace(token, (match) => {
46
- return `${code}`;
47
- });
171
+ return {
172
+ escapedCode,
173
+ phpCodes,
174
+ write(outputFile) {
175
+ writeFile(outputFile, escapedCode);
176
+ writeFile(outputFile + ".json", JSON.stringify(phpCodes));
177
+ }
178
+ };
179
+ }
180
+ function unescapePHP({ escapedCode, phpCodes }) {
181
+ let out = escapedCode;
182
+ Object.entries(phpCodes).forEach(([token, code]) => {
183
+ out = out.replace(token, (match) => {
184
+ return `${code}`;
48
185
  });
49
- }
186
+ });
50
187
  return out;
51
188
  }
52
189
 
@@ -89,12 +226,6 @@ const phpServer = {
89
226
  stop
90
227
  };
91
228
 
92
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
93
-
94
- function getDefaultExportFromCjs (x) {
95
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
96
- }
97
-
98
229
  var tasks = {};
99
230
 
100
231
  var utils$k = {};
@@ -157,8 +288,8 @@ var path$9 = {};
157
288
 
158
289
  Object.defineProperty(path$9, "__esModule", { value: true });
159
290
  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;
160
- const os = require$$0;
161
- const path$8 = require$$0$1;
291
+ const os = require$$0$1;
292
+ const path$8 = require$$0$2;
162
293
  const IS_WINDOWS_PLATFORM = os.platform() === 'win32';
163
294
  const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
164
295
  /**
@@ -398,8 +529,8 @@ var isGlob$1 = function isGlob(str, options) {
398
529
  };
399
530
 
400
531
  var isGlob = isGlob$1;
401
- var pathPosixDirname = require$$0$1.posix.dirname;
402
- var isWin32 = require$$0.platform() === 'win32';
532
+ var pathPosixDirname = require$$0$2.posix.dirname;
533
+ var isWin32 = require$$0$1.platform() === 'win32';
403
534
 
404
535
  var slash = '/';
405
536
  var backslash = /\\/g;
@@ -895,7 +1026,7 @@ var toRegexRange_1 = toRegexRange$1;
895
1026
  * Licensed under the MIT License.
896
1027
  */
897
1028
 
898
- const util$1 = require$$0$2;
1029
+ const util$1 = require$$0$3;
899
1030
  const toRegexRange = toRegexRange_1;
900
1031
 
901
1032
  const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
@@ -1860,7 +1991,7 @@ var braces_1 = braces$1;
1860
1991
 
1861
1992
  var utils$f = {};
1862
1993
 
1863
- const path$7 = require$$0$1;
1994
+ const path$7 = require$$0$2;
1864
1995
  const WIN_SLASH = '\\\\/';
1865
1996
  const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
1866
1997
 
@@ -2040,7 +2171,7 @@ var constants$3 = {
2040
2171
 
2041
2172
  (function (exports) {
2042
2173
 
2043
- const path = require$$0$1;
2174
+ const path = require$$0$2;
2044
2175
  const win32 = process.platform === 'win32';
2045
2176
  const {
2046
2177
  REGEX_BACKSLASH,
@@ -3584,7 +3715,7 @@ parse$1.fastpaths = (input, options) => {
3584
3715
 
3585
3716
  var parse_1 = parse$1;
3586
3717
 
3587
- const path$6 = require$$0$1;
3718
+ const path$6 = require$$0$2;
3588
3719
  const scan = scan_1;
3589
3720
  const parse = parse_1;
3590
3721
  const utils$c = utils$f;
@@ -3927,7 +4058,7 @@ var picomatch_1 = picomatch$2;
3927
4058
 
3928
4059
  var picomatch$1 = picomatch_1;
3929
4060
 
3930
- const util = require$$0$2;
4061
+ const util = require$$0$3;
3931
4062
  const braces = braces_1;
3932
4063
  const picomatch = picomatch$1;
3933
4064
  const utils$b = utils$f;
@@ -4395,7 +4526,7 @@ var micromatch_1 = micromatch$1;
4395
4526
 
4396
4527
  Object.defineProperty(pattern$1, "__esModule", { value: true });
4397
4528
  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;
4398
- const path$5 = require$$0$1;
4529
+ const path$5 = require$$0$2;
4399
4530
  const globParent = globParent$1;
4400
4531
  const micromatch = micromatch_1;
4401
4532
  const GLOBSTAR = '**';
@@ -4590,7 +4721,7 @@ var stream$4 = {};
4590
4721
  * Copyright (c) 2014-2020 Teambition
4591
4722
  * Licensed under the MIT license.
4592
4723
  */
4593
- const Stream = require$$0$3;
4724
+ const Stream = require$$0$4;
4594
4725
  const PassThrough = Stream.PassThrough;
4595
4726
  const slice = Array.prototype.slice;
4596
4727
 
@@ -4970,7 +5101,7 @@ var fs$5 = {};
4970
5101
  (function (exports) {
4971
5102
  Object.defineProperty(exports, "__esModule", { value: true });
4972
5103
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
4973
- const fs = require$$0$4;
5104
+ const fs = require$$0$5;
4974
5105
  exports.FILE_SYSTEM_ADAPTER = {
4975
5106
  lstat: fs.lstat,
4976
5107
  stat: fs.stat,
@@ -5321,7 +5452,7 @@ var fs$1 = {};
5321
5452
  (function (exports) {
5322
5453
  Object.defineProperty(exports, "__esModule", { value: true });
5323
5454
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
5324
- const fs = require$$0$4;
5455
+ const fs = require$$0$5;
5325
5456
  exports.FILE_SYSTEM_ADAPTER = {
5326
5457
  lstat: fs.lstat,
5327
5458
  stat: fs.stat,
@@ -5340,7 +5471,7 @@ var fs$1 = {};
5340
5471
  } (fs$1));
5341
5472
 
5342
5473
  Object.defineProperty(settings$2, "__esModule", { value: true });
5343
- const path$3 = require$$0$1;
5474
+ const path$3 = require$$0$2;
5344
5475
  const fsStat$3 = out$1;
5345
5476
  const fs = fs$1;
5346
5477
  let Settings$1 = class Settings {
@@ -5782,7 +5913,7 @@ let Reader$1 = class Reader {
5782
5913
  reader$1.default = Reader$1;
5783
5914
 
5784
5915
  Object.defineProperty(async$4, "__esModule", { value: true });
5785
- const events_1 = require$$0$5;
5916
+ const events_1 = require$$0$6;
5786
5917
  const fsScandir$2 = out$2;
5787
5918
  const fastq = queueExports;
5788
5919
  const common$1 = common$3;
@@ -5911,7 +6042,7 @@ function callSuccessCallback(callback, entries) {
5911
6042
  var stream$2 = {};
5912
6043
 
5913
6044
  Object.defineProperty(stream$2, "__esModule", { value: true });
5914
- const stream_1$5 = require$$0$3;
6045
+ const stream_1$5 = require$$0$4;
5915
6046
  const async_1$3 = async$4;
5916
6047
  class StreamProvider {
5917
6048
  constructor(_root, _settings) {
@@ -6024,7 +6155,7 @@ sync$3.default = SyncProvider;
6024
6155
  var settings$1 = {};
6025
6156
 
6026
6157
  Object.defineProperty(settings$1, "__esModule", { value: true });
6027
- const path$2 = require$$0$1;
6158
+ const path$2 = require$$0$2;
6028
6159
  const fsScandir = out$2;
6029
6160
  class Settings {
6030
6161
  constructor(_options = {}) {
@@ -6086,7 +6217,7 @@ function getSettings(settingsOrOptions = {}) {
6086
6217
  var reader = {};
6087
6218
 
6088
6219
  Object.defineProperty(reader, "__esModule", { value: true });
6089
- const path$1 = require$$0$1;
6220
+ const path$1 = require$$0$2;
6090
6221
  const fsStat$2 = out$1;
6091
6222
  const utils$6 = utils$k;
6092
6223
  class Reader {
@@ -6121,7 +6252,7 @@ reader.default = Reader;
6121
6252
  var stream$1 = {};
6122
6253
 
6123
6254
  Object.defineProperty(stream$1, "__esModule", { value: true });
6124
- const stream_1$3 = require$$0$3;
6255
+ const stream_1$3 = require$$0$4;
6125
6256
  const fsStat$1 = out$1;
6126
6257
  const fsWalk$2 = out$3;
6127
6258
  const reader_1$2 = reader;
@@ -6474,7 +6605,7 @@ class EntryTransformer {
6474
6605
  entry.default = EntryTransformer;
6475
6606
 
6476
6607
  Object.defineProperty(provider, "__esModule", { value: true });
6477
- const path = require$$0$1;
6608
+ const path = require$$0$2;
6478
6609
  const deep_1 = deep;
6479
6610
  const entry_1 = entry$1;
6480
6611
  const error_1 = error;
@@ -6547,7 +6678,7 @@ async$7.default = ProviderAsync;
6547
6678
  var stream = {};
6548
6679
 
6549
6680
  Object.defineProperty(stream, "__esModule", { value: true });
6550
- const stream_1$1 = require$$0$3;
6681
+ const stream_1$1 = require$$0$4;
6551
6682
  const stream_2 = stream$1;
6552
6683
  const provider_1$1 = provider;
6553
6684
  class ProviderStream extends provider_1$1.default {
@@ -6652,8 +6783,8 @@ var settings = {};
6652
6783
  (function (exports) {
6653
6784
  Object.defineProperty(exports, "__esModule", { value: true });
6654
6785
  exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
6655
- const fs = require$$0$4;
6656
- const os = require$$0;
6786
+ const fs = require$$0$5;
6787
+ const os = require$$0$1;
6657
6788
  /**
6658
6789
  * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
6659
6790
  * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
@@ -6812,6 +6943,22 @@ var out = FastGlob;
6812
6943
 
6813
6944
  const fastGlob = /*@__PURE__*/getDefaultExportFromCjs(out);
6814
6945
 
6946
+ function consoleHijack(entries) {
6947
+ ["log", "info", "warn", "error"].forEach((command) => {
6948
+ const cx = console[command];
6949
+ console[command] = function(...args) {
6950
+ cx.apply(
6951
+ this,
6952
+ args.map(
6953
+ (arg) => typeof arg === "string" ? entries.reduce((acc, entry) => {
6954
+ return acc.replace(entry + ".html", entry);
6955
+ }, arg) : arg
6956
+ )
6957
+ );
6958
+ };
6959
+ });
6960
+ }
6961
+
6815
6962
  const internalParam = "__314159265359__";
6816
6963
  function usePHP(cfg = {}) {
6817
6964
  const {
@@ -6826,14 +6973,11 @@ function usePHP(cfg = {}) {
6826
6973
  let config = void 0;
6827
6974
  let viteServer = void 0;
6828
6975
  let entries = Array.isArray(entry) ? entry : [entry];
6829
- function escapeFile(file) {
6830
- const tempFile = `${tempDir}/${file}.html`;
6831
- escapePHP(file, tempFile);
6832
- return tempFile;
6976
+ function getTempFileName(file) {
6977
+ return `${tempDir}/${file}.html`;
6833
6978
  }
6834
- function cleanupTemp(dir = "") {
6835
- const parentDir = dir ? dir + "/" : dir;
6836
- rmSync(parentDir + tempDir, { recursive: true, force: true });
6979
+ function cleanupTemp() {
6980
+ rmSync(tempDir, { recursive: true, force: true });
6837
6981
  }
6838
6982
  function onExit() {
6839
6983
  if (config?.command === "serve") {
@@ -6861,20 +7005,27 @@ function usePHP(cfg = {}) {
6861
7005
  if (!existsSync(gitIgnoreFile)) {
6862
7006
  writeFile(gitIgnoreFile, "*\n**/*.php.html");
6863
7007
  }
6864
- entries = entries.flatMap(
6865
- (entry2) => fastGlob.globSync(entry2, {
6866
- dot: true,
6867
- onlyFiles: true,
6868
- unique: true,
6869
- ignore: [tempDir, config2.build?.outDir || "dist"]
6870
- })
6871
- );
6872
- const inputs = entries.map(escapeFile);
7008
+ entries = [
7009
+ ...new Set(
7010
+ entries.flatMap(
7011
+ (entry2) => fastGlob.globSync(entry2, {
7012
+ dot: true,
7013
+ onlyFiles: true,
7014
+ unique: true,
7015
+ ignore: [
7016
+ tempDir,
7017
+ config2.build?.outDir || "dist"
7018
+ ]
7019
+ })
7020
+ )
7021
+ )
7022
+ ];
7023
+ consoleHijack(entries);
6873
7024
  return {
6874
7025
  build: {
6875
- rollupOptions: { input: inputs }
7026
+ rollupOptions: { input: entries }
6876
7027
  },
6877
- optimizeDeps: { entries: inputs }
7028
+ optimizeDeps: { entries }
6878
7029
  };
6879
7030
  },
6880
7031
  configResolved(_config) {
@@ -6885,6 +7036,16 @@ function usePHP(cfg = {}) {
6885
7036
  name: "serve-php",
6886
7037
  apply: "serve",
6887
7038
  enforce: "pre",
7039
+ configResolved(_config) {
7040
+ config = _config;
7041
+ entries.forEach((entry2) => {
7042
+ const outputFile = getTempFileName(entry2);
7043
+ escapePHP({
7044
+ inputFile: entry2,
7045
+ config
7046
+ }).write(outputFile);
7047
+ });
7048
+ },
6888
7049
  configureServer(server) {
6889
7050
  viteServer = server;
6890
7051
  phpServer.start(viteServer?.config.root);
@@ -6912,7 +7073,7 @@ function usePHP(cfg = {}) {
6912
7073
  return file === entryPathname || file.substring(0, file.lastIndexOf(".")) === entryPathname;
6913
7074
  });
6914
7075
  if (entry2) {
6915
- const tempFile = `${tempDir}/${entry2}.html`;
7076
+ const tempFile = getTempFileName(entry2);
6916
7077
  if (existsSync(resolve(tempFile))) {
6917
7078
  url.pathname = tempFile;
6918
7079
  url.port = phpServer.port.toString();
@@ -6950,7 +7111,7 @@ function usePHP(cfg = {}) {
6950
7111
  ).on("error", reject).end();
6951
7112
  });
6952
7113
  const out = await server.transformIndexHtml(
6953
- entryPathname || "/",
7114
+ "/" + entryPathname,
6954
7115
  phpResult.content,
6955
7116
  req.originalUrl
6956
7117
  );
@@ -6970,10 +7131,14 @@ function usePHP(cfg = {}) {
6970
7131
  },
6971
7132
  handleHotUpdate({ server, file }) {
6972
7133
  const entry2 = entries.find(
6973
- (entryFile) => file.endsWith(entryFile) && resolve(entryFile) === file
7134
+ (entryFile) => resolve(entryFile) === file
6974
7135
  );
6975
7136
  if (entry2) {
6976
- escapeFile(entry2);
7137
+ const outputFile = getTempFileName(entry2);
7138
+ escapePHP({
7139
+ inputFile: entry2,
7140
+ config
7141
+ }).write(outputFile);
6977
7142
  server.ws.send({
6978
7143
  type: "full-reload",
6979
7144
  path: "*"
@@ -6984,21 +7149,49 @@ function usePHP(cfg = {}) {
6984
7149
  {
6985
7150
  name: "build-php",
6986
7151
  apply: "build",
7152
+ enforce: "pre",
6987
7153
  resolveId(source, importer, options) {
6988
- if (importer?.endsWith(".html") && importer.includes(`/${tempDir}/`)) {
6989
- return { id: resolve(source) };
7154
+ if (entries.includes(source)) {
7155
+ return {
7156
+ id: `${source}.html`,
7157
+ resolvedBy: "vite-plugin-php",
7158
+ meta: {
7159
+ originalId: source
7160
+ }
7161
+ };
6990
7162
  }
6991
7163
  },
6992
- closeBundle() {
6993
- const distDir = config?.build.outDir;
6994
- entries.forEach((file) => {
6995
- const code = unescapePHP(
6996
- `${distDir}/${tempDir}/${file}.html`,
6997
- `${tempDir}/${file}.html.json`
6998
- );
6999
- writeFile(`${distDir}/${file}`, code);
7000
- });
7001
- cleanupTemp(distDir);
7164
+ load(id, options) {
7165
+ const entry2 = this.getModuleInfo(id)?.meta.originalId;
7166
+ if (entry2) {
7167
+ const { escapedCode, phpCodes } = escapePHP({
7168
+ inputFile: entry2,
7169
+ config
7170
+ });
7171
+ return {
7172
+ code: escapedCode,
7173
+ meta: { phpCodes }
7174
+ };
7175
+ }
7176
+ },
7177
+ generateBundle: {
7178
+ order: "post",
7179
+ handler(options, bundle, isWrite) {
7180
+ Object.entries(bundle).forEach(([key, item]) => {
7181
+ if (item.type === "asset") {
7182
+ const meta = this.getModuleInfo(
7183
+ item.fileName
7184
+ )?.meta;
7185
+ if (meta?.originalId && meta?.phpCodes) {
7186
+ item.fileName = meta.originalId;
7187
+ item.source = unescapePHP({
7188
+ escapedCode: item.source.toString(),
7189
+ phpCodes: meta.phpCodes
7190
+ });
7191
+ }
7192
+ }
7193
+ });
7194
+ }
7002
7195
  }
7003
7196
  }
7004
7197
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-php",
3
- "version": "1.0.31",
3
+ "version": "1.0.50",
4
4
  "description": "Process PHP-files with the speed and tools of Vite",
5
5
  "keywords": [
6
6
  "vite",
@@ -60,6 +60,7 @@
60
60
  "devDependencies": {
61
61
  "@types/node": "^20.14.11",
62
62
  "fast-glob": "^3.3.2",
63
+ "picocolors": "^1.0.1",
63
64
  "typescript": "^5.5.3",
64
65
  "unbuild": "^2.0.0",
65
66
  "vite": "^5.3.4"