cwresdev 0.1.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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -0
  3. package/bin/cwrespro.js +64 -0
  4. package/package.json +47 -0
  5. package/src/client/reload-client.js +40 -0
  6. package/src/config.js +211 -0
  7. package/src/index.js +19 -0
  8. package/src/injector.js +32 -0
  9. package/src/php.js +114 -0
  10. package/src/proxy.js +91 -0
  11. package/src/server.js +334 -0
  12. package/vendor/php/windows/README.md +140 -0
  13. package/vendor/php/windows/brotlicommon.dll +0 -0
  14. package/vendor/php/windows/brotlidec.dll +0 -0
  15. package/vendor/php/windows/deplister.exe +0 -0
  16. package/vendor/php/windows/dev/php8.lib +0 -0
  17. package/vendor/php/windows/ext/php_bz2.dll +0 -0
  18. package/vendor/php/windows/ext/php_com_dotnet.dll +0 -0
  19. package/vendor/php/windows/ext/php_curl.dll +0 -0
  20. package/vendor/php/windows/ext/php_dba.dll +0 -0
  21. package/vendor/php/windows/ext/php_dl_test.dll +0 -0
  22. package/vendor/php/windows/ext/php_enchant.dll +0 -0
  23. package/vendor/php/windows/ext/php_exif.dll +0 -0
  24. package/vendor/php/windows/ext/php_ffi.dll +0 -0
  25. package/vendor/php/windows/ext/php_fileinfo.dll +0 -0
  26. package/vendor/php/windows/ext/php_ftp.dll +0 -0
  27. package/vendor/php/windows/ext/php_gd.dll +0 -0
  28. package/vendor/php/windows/ext/php_gettext.dll +0 -0
  29. package/vendor/php/windows/ext/php_gmp.dll +0 -0
  30. package/vendor/php/windows/ext/php_intl.dll +0 -0
  31. package/vendor/php/windows/ext/php_ldap.dll +0 -0
  32. package/vendor/php/windows/ext/php_mbstring.dll +0 -0
  33. package/vendor/php/windows/ext/php_mysqli.dll +0 -0
  34. package/vendor/php/windows/ext/php_odbc.dll +0 -0
  35. package/vendor/php/windows/ext/php_opcache.dll +0 -0
  36. package/vendor/php/windows/ext/php_openssl.dll +0 -0
  37. package/vendor/php/windows/ext/php_pdo_firebird.dll +0 -0
  38. package/vendor/php/windows/ext/php_pdo_mysql.dll +0 -0
  39. package/vendor/php/windows/ext/php_pdo_odbc.dll +0 -0
  40. package/vendor/php/windows/ext/php_pdo_pgsql.dll +0 -0
  41. package/vendor/php/windows/ext/php_pdo_sqlite.dll +0 -0
  42. package/vendor/php/windows/ext/php_pgsql.dll +0 -0
  43. package/vendor/php/windows/ext/php_shmop.dll +0 -0
  44. package/vendor/php/windows/ext/php_snmp.dll +0 -0
  45. package/vendor/php/windows/ext/php_soap.dll +0 -0
  46. package/vendor/php/windows/ext/php_sockets.dll +0 -0
  47. package/vendor/php/windows/ext/php_sodium.dll +0 -0
  48. package/vendor/php/windows/ext/php_sqlite3.dll +0 -0
  49. package/vendor/php/windows/ext/php_sysvshm.dll +0 -0
  50. package/vendor/php/windows/ext/php_tidy.dll +0 -0
  51. package/vendor/php/windows/ext/php_xsl.dll +0 -0
  52. package/vendor/php/windows/ext/php_zend_test.dll +0 -0
  53. package/vendor/php/windows/ext/php_zip.dll +0 -0
  54. package/vendor/php/windows/extras/ssl/legacy.dll +0 -0
  55. package/vendor/php/windows/extras/ssl/openssl.cnf +390 -0
  56. package/vendor/php/windows/glib-2.dll +0 -0
  57. package/vendor/php/windows/gmodule-2.dll +0 -0
  58. package/vendor/php/windows/icudt77.dll +0 -0
  59. package/vendor/php/windows/icuin77.dll +0 -0
  60. package/vendor/php/windows/icuio77.dll +0 -0
  61. package/vendor/php/windows/icuuc77.dll +0 -0
  62. package/vendor/php/windows/lib/enchant/libenchant2_hunspell.dll +0 -0
  63. package/vendor/php/windows/libcrypto-3-x64.dll +0 -0
  64. package/vendor/php/windows/libenchant2.dll +0 -0
  65. package/vendor/php/windows/libpq.dll +0 -0
  66. package/vendor/php/windows/libsasl.dll +0 -0
  67. package/vendor/php/windows/libsodium.dll +0 -0
  68. package/vendor/php/windows/libsqlite3.dll +0 -0
  69. package/vendor/php/windows/libssh2.dll +0 -0
  70. package/vendor/php/windows/libssl-3-x64.dll +0 -0
  71. package/vendor/php/windows/libzstd.dll +0 -0
  72. package/vendor/php/windows/license.txt +68 -0
  73. package/vendor/php/windows/manifest.json +4 -0
  74. package/vendor/php/windows/news.txt +2204 -0
  75. package/vendor/php/windows/nghttp2.dll +0 -0
  76. package/vendor/php/windows/phar.phar.bat +1 -0
  77. package/vendor/php/windows/pharcommand.phar +0 -0
  78. package/vendor/php/windows/php-cgi.exe +0 -0
  79. package/vendor/php/windows/php-win.exe +0 -0
  80. package/vendor/php/windows/php.exe +0 -0
  81. package/vendor/php/windows/php.ini +1848 -0
  82. package/vendor/php/windows/php.ini-development +1848 -0
  83. package/vendor/php/windows/php.ini-production +1850 -0
  84. package/vendor/php/windows/php8.dll +0 -0
  85. package/vendor/php/windows/php8embed.lib +0 -0
  86. package/vendor/php/windows/php8phpdbg.dll +0 -0
  87. package/vendor/php/windows/phpdbg.exe +0 -0
  88. package/vendor/php/windows/readme-redist-bins.txt +681 -0
  89. package/vendor/php/windows/snapshot.txt +157 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+
2
+ Add a script to the consuming project's `package.json`:
3
+
4
+ Project shape:
5
+
6
+ ```text
7
+ your-project/
8
+ package.json
9
+ virtual_env/
10
+ index.html
11
+ hello.php
12
+ ```
13
+
14
+ Start the server:
15
+
16
+ ```powershell
17
+ npm run dev
18
+ ```
19
+
20
+ ## This Package
21
+
22
+ This repository is the package source. Before publishing, vendor the Windows PHP runtime into the main package:
23
+
24
+ ```powershell
25
+ npm install
26
+ npm run bundle:php
27
+ npm test
28
+ npm run pack:check
29
+ ```
30
+
31
+ Stop any running `cwrespro` server before publishing. On Windows, a live PHP process can leave the bundled runtime partially locked, and `npm run pack:check` is meant to catch that before release.
32
+
33
+ Then publish:
34
+
35
+ ```powershell
36
+ npm login
37
+ npm publish --access public
38
+ ```
39
+
40
+ ```powershell
41
+ npm test
42
+ ```
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { spawn } = require("node:child_process");
4
+ const { formatHelp, loadConfig, parseArgv, resolveLaunchUrl, startDevServer } = require("../src");
5
+
6
+ function openBrowser(url) {
7
+ const child = spawn("cmd", ["/c", "start", "", url], {
8
+ detached: true,
9
+ stdio: "ignore",
10
+ windowsHide: true,
11
+ });
12
+
13
+ child.unref();
14
+ }
15
+
16
+ async function main() {
17
+ if (process.platform !== "win32") {
18
+ throw new Error("cwrespro currently supports Windows only.");
19
+ }
20
+
21
+ const argv = parseArgv(process.argv.slice(2));
22
+
23
+ if (argv.help) {
24
+ process.stdout.write(formatHelp("cwrespro"));
25
+ return;
26
+ }
27
+
28
+ const config = loadConfig({ cwd: process.cwd(), argv });
29
+ const server = await startDevServer(config);
30
+ const launchUrl = resolveLaunchUrl(server.url, config.startPath);
31
+
32
+ process.stdout.write(`[cwrespro] Development Server (${launchUrl}) started\n`);
33
+
34
+ if (config.openBrowser) {
35
+ openBrowser(launchUrl);
36
+ }
37
+
38
+ let closing = false;
39
+
40
+ const shutdown = async (signal) => {
41
+ if (closing) {
42
+ return;
43
+ }
44
+
45
+ closing = true;
46
+ process.stdout.write(`[cwrespro] Shutting down (${signal})...\n`);
47
+ await server.close();
48
+ process.exit(0);
49
+ };
50
+
51
+ ["SIGINT", "SIGTERM"].forEach((signal) => {
52
+ process.on(signal, () => {
53
+ shutdown(signal).catch((error) => {
54
+ process.stderr.write(`[cwrespro] ${error.message}\n`);
55
+ process.exit(1);
56
+ });
57
+ });
58
+ });
59
+ }
60
+
61
+ main().catch((error) => {
62
+ process.stderr.write(`[cwrespro] ${error.message}\n`);
63
+ process.exit(1);
64
+ });
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "cwresdev",
3
+ "version": "0.1.0",
4
+ "description": "",
5
+ "license": "MIT",
6
+ "private": false,
7
+ "type": "commonjs",
8
+ "main": "./src/index.js",
9
+ "bin": {
10
+ "cwrespro": "bin/cwrespro.js"
11
+ },
12
+ "files": [
13
+ "bin",
14
+ "src",
15
+ "vendor/php/windows",
16
+ "README.md",
17
+ "LICENSE",
18
+ "THIRD_PARTY_NOTICES.md"
19
+ ],
20
+ "os": [
21
+ "win32"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20.11"
25
+ },
26
+ "scripts": {
27
+ "start": "node ./bin/cwrespro.js",
28
+ "dev": "node ./bin/cwrespro.js",
29
+ "test": "node --test",
30
+ "bundle:php": "node ./scripts/vendor-php.mjs",
31
+ "pack:check": "node ./scripts/verify-publish.mjs",
32
+ "pack:dry-run": "npm pack --dry-run",
33
+ "prepublishOnly": "npm test && npm run pack:check"
34
+ },
35
+ "keywords": [
36
+ "live-server",
37
+ "php",
38
+ "courseware",
39
+ "proxy",
40
+ "windows"
41
+ ],
42
+ "dependencies": {
43
+ "chokidar": "^4.0.3",
44
+ "express": "^4.21.2",
45
+ "ws": "^8.18.2"
46
+ }
47
+ }
@@ -0,0 +1,40 @@
1
+ (function cwresproReloadClient() {
2
+ const socketPath = "/__cwrespro/ws";
3
+ let reconnectDelay = 500;
4
+ let reconnectTimer = null;
5
+
6
+ function connect() {
7
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
8
+ const socket = new WebSocket(`${protocol}//${window.location.host}${socketPath}`);
9
+
10
+ socket.addEventListener("open", function handleOpen() {
11
+ reconnectDelay = 500;
12
+ });
13
+
14
+ socket.addEventListener("message", function handleMessage(event) {
15
+ if (event.data === "reload") {
16
+ window.location.reload();
17
+ }
18
+ });
19
+
20
+ socket.addEventListener("close", function handleClose() {
21
+ reconnectTimer = window.setTimeout(connect, reconnectDelay);
22
+ reconnectDelay = Math.min(reconnectDelay * 2, 5000);
23
+ });
24
+
25
+ socket.addEventListener("error", function handleError() {
26
+ socket.close();
27
+ });
28
+ }
29
+
30
+ if (!window.__cwresproReloadClientLoaded) {
31
+ window.__cwresproReloadClientLoaded = true;
32
+ connect();
33
+ }
34
+
35
+ window.addEventListener("beforeunload", function cleanup() {
36
+ if (reconnectTimer !== null) {
37
+ window.clearTimeout(reconnectTimer);
38
+ }
39
+ });
40
+ })();
package/src/config.js ADDED
@@ -0,0 +1,211 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+
4
+ const DEFAULT_CONFIG_FILE = "cwrespro.config.json";
5
+ const DEFAULT_PROXY_ORIGIN = "https:" + "//cour" + "sewareob" + "jects.else" + "vier.c" + "om";
6
+ const DEFAULT_START_PATH = "index.html";
7
+
8
+ function parseArgv(argv) {
9
+ const parsed = {
10
+ help: false,
11
+ };
12
+
13
+ for (let index = 0; index < argv.length; index += 1) {
14
+ const token = argv[index];
15
+
16
+ if (token === "--help" || token === "-h") {
17
+ parsed.help = true;
18
+ continue;
19
+ }
20
+
21
+ if (token === "--open" || token === "-o") {
22
+ parsed.openBrowser = true;
23
+ continue;
24
+ }
25
+
26
+ if (token === "--no-open") {
27
+ parsed.openBrowser = false;
28
+ continue;
29
+ }
30
+
31
+ if (token === "--quiet") {
32
+ parsed.quiet = true;
33
+ continue;
34
+ }
35
+
36
+ if (["--port", "-p", "--host", "--doc-root", "--proxy-origin", "--config", "--php-binary", "--start-path"].includes(token)) {
37
+ const value = argv[index + 1];
38
+
39
+ if (typeof value === "undefined") {
40
+ throw new Error(`Missing value for ${token}`);
41
+ }
42
+
43
+ index += 1;
44
+
45
+ if (token === "--port" || token === "-p") {
46
+ parsed.port = Number(value);
47
+ } else if (token === "--host") {
48
+ parsed.host = value;
49
+ } else if (token === "--doc-root") {
50
+ parsed.docRoot = value;
51
+ } else if (token === "--proxy-origin") {
52
+ parsed.proxyOrigin = value;
53
+ } else if (token === "--config") {
54
+ parsed.configPath = value;
55
+ } else if (token === "--php-binary") {
56
+ parsed.phpBinary = value;
57
+ } else if (token === "--start-path") {
58
+ parsed.startPath = value;
59
+ }
60
+
61
+ continue;
62
+ }
63
+
64
+ throw new Error(`Unknown argument: ${token}`);
65
+ }
66
+
67
+ return parsed;
68
+ }
69
+
70
+ function readConfigFile(configPath) {
71
+ if (!fs.existsSync(configPath)) {
72
+ return {};
73
+ }
74
+
75
+ const fileText = fs.readFileSync(configPath, "utf8");
76
+ return JSON.parse(fileText);
77
+ }
78
+
79
+ function readProjectPackageConfig(cwd) {
80
+ const packageJsonPath = path.resolve(cwd, "package.json");
81
+
82
+ if (!fs.existsSync(packageJsonPath)) {
83
+ return {};
84
+ }
85
+
86
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
87
+
88
+ if (!packageJson.cwrespro || typeof packageJson.cwrespro !== "object" || Array.isArray(packageJson.cwrespro)) {
89
+ return {};
90
+ }
91
+
92
+ return packageJson.cwrespro;
93
+ }
94
+
95
+ function normalizeStartPath(startPath) {
96
+ if (typeof startPath !== "string") {
97
+ return DEFAULT_START_PATH;
98
+ }
99
+
100
+ const trimmed = startPath.trim();
101
+
102
+ if (!trimmed) {
103
+ return DEFAULT_START_PATH;
104
+ }
105
+
106
+ return trimmed.replace(/^\.\//, "");
107
+ }
108
+
109
+ function resolveLaunchUrl(baseUrl, startPath) {
110
+ const normalizedPath = normalizeStartPath(startPath);
111
+ return new URL(normalizedPath, baseUrl).toString();
112
+ }
113
+
114
+ function validatePort(port) {
115
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
116
+ throw new Error(`Invalid port: ${port}`);
117
+ }
118
+ }
119
+
120
+ function validateConfig(config) {
121
+ validatePort(config.port);
122
+
123
+ if (!config.host || typeof config.host !== "string") {
124
+ throw new Error("host must be a non-empty string.");
125
+ }
126
+
127
+ if (!config.docRoot || typeof config.docRoot !== "string") {
128
+ throw new Error("docRoot must be a non-empty string.");
129
+ }
130
+
131
+ if (!config.startPath || typeof config.startPath !== "string") {
132
+ throw new Error("startPath must be a non-empty string.");
133
+ }
134
+
135
+ try {
136
+ new URL(config.proxyOrigin);
137
+ } catch (error) {
138
+ throw new Error(`Invalid proxy origin: ${config.proxyOrigin}`);
139
+ }
140
+ }
141
+
142
+ function loadConfig({ cwd, argv }) {
143
+ const configPath = argv.configPath ? path.resolve(cwd, argv.configPath) : null;
144
+ const fileConfig = configPath ? readConfigFile(configPath) : {};
145
+ const packageConfig = readProjectPackageConfig(cwd);
146
+
147
+ const config = {
148
+ cwd,
149
+ host: argv.host || fileConfig.host || packageConfig.host || "127.0.0.1",
150
+ port: typeof argv.port === "number" && !Number.isNaN(argv.port)
151
+ ? argv.port
152
+ : typeof fileConfig.port === "number"
153
+ ? fileConfig.port
154
+ : typeof packageConfig.port === "number"
155
+ ? packageConfig.port
156
+ : 3000,
157
+ docRoot: path.resolve(cwd, argv.docRoot || fileConfig.docRoot || packageConfig.docRoot || "virtual_env"),
158
+ proxyOrigin: argv.proxyOrigin || fileConfig.proxyOrigin || packageConfig.proxyOrigin || DEFAULT_PROXY_ORIGIN,
159
+ openBrowser: typeof argv.openBrowser === "boolean"
160
+ ? argv.openBrowser
161
+ : typeof fileConfig.openBrowser === "boolean"
162
+ ? fileConfig.openBrowser
163
+ : typeof packageConfig.openBrowser === "boolean"
164
+ ? packageConfig.openBrowser
165
+ : true,
166
+ phpBinary: argv.phpBinary || fileConfig.phpBinary || packageConfig.phpBinary || null,
167
+ quiet: Boolean(argv.quiet || fileConfig.quiet || packageConfig.quiet),
168
+ startPath: normalizeStartPath(argv.startPath || fileConfig.startPath || packageConfig.startPath || DEFAULT_START_PATH),
169
+ watchIgnored: Array.isArray(fileConfig.watchIgnored)
170
+ ? fileConfig.watchIgnored
171
+ : Array.isArray(packageConfig.watchIgnored)
172
+ ? packageConfig.watchIgnored
173
+ : [],
174
+ };
175
+
176
+ validateConfig(config);
177
+
178
+ return config;
179
+ }
180
+
181
+ function formatHelp(binName) {
182
+ return [
183
+ `${binName} [options]`,
184
+ "",
185
+ "Options:",
186
+ " -h, --help Show this help message",
187
+ " -p, --port <port> HTTP port to bind. Use 0 for a random port.",
188
+ " --host <host> Host to bind. Default: 127.0.0.1",
189
+ " --doc-root <path> Project doc root. Default: ./virtual_env",
190
+ " --proxy-origin <u> Upstream origin for /objects/* proxying",
191
+ " --start-path <p> Initial page path. Default: index.html",
192
+ " --config <path> Optional explicit config JSON path",
193
+ " --php-binary <p> Override the bundled php.exe path",
194
+ " -o, --open Open the browser after startup",
195
+ " --no-open Do not open the browser",
196
+ " --quiet Reduce console logging",
197
+ "",
198
+ `Built-in defaults are used unless --config points to ${DEFAULT_CONFIG_FILE}.`,
199
+ "",
200
+ ].join("\n");
201
+ }
202
+
203
+ module.exports = {
204
+ DEFAULT_CONFIG_FILE,
205
+ DEFAULT_PROXY_ORIGIN,
206
+ DEFAULT_START_PATH,
207
+ formatHelp,
208
+ loadConfig,
209
+ parseArgv,
210
+ resolveLaunchUrl,
211
+ };
package/src/index.js ADDED
@@ -0,0 +1,19 @@
1
+ const {
2
+ DEFAULT_CONFIG_FILE,
3
+ DEFAULT_START_PATH,
4
+ formatHelp,
5
+ loadConfig,
6
+ parseArgv,
7
+ resolveLaunchUrl,
8
+ } = require("./config");
9
+ const { startDevServer } = require("./server");
10
+
11
+ module.exports = {
12
+ DEFAULT_CONFIG_FILE,
13
+ DEFAULT_START_PATH,
14
+ formatHelp,
15
+ loadConfig,
16
+ parseArgv,
17
+ resolveLaunchUrl,
18
+ startDevServer,
19
+ };
@@ -0,0 +1,32 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+
4
+ const CLIENT_SCRIPT_ROUTE = "/__cwrespro/client.js";
5
+ const CLIENT_SCRIPT_TAG = `<script src="${CLIENT_SCRIPT_ROUTE}" data-cwrespro="true"></script>`;
6
+
7
+ function injectLiveReload(html) {
8
+ if (html.includes(CLIENT_SCRIPT_ROUTE)) {
9
+ return html;
10
+ }
11
+
12
+ if (/<\/body>/i.test(html)) {
13
+ return html.replace(/<\/body>/i, `${CLIENT_SCRIPT_TAG}</body>`);
14
+ }
15
+
16
+ if (/<\/head>/i.test(html)) {
17
+ return html.replace(/<\/head>/i, `${CLIENT_SCRIPT_TAG}</head>`);
18
+ }
19
+
20
+ return `${html}${CLIENT_SCRIPT_TAG}`;
21
+ }
22
+
23
+ function getClientScriptSource() {
24
+ const clientScriptPath = path.resolve(__dirname, "client", "reload-client.js");
25
+ return fs.readFileSync(clientScriptPath, "utf8");
26
+ }
27
+
28
+ module.exports = {
29
+ CLIENT_SCRIPT_ROUTE,
30
+ getClientScriptSource,
31
+ injectLiveReload,
32
+ };
package/src/php.js ADDED
@@ -0,0 +1,114 @@
1
+ const fs = require("node:fs");
2
+ const net = require("node:net");
3
+ const path = require("node:path");
4
+ const { spawn } = require("node:child_process");
5
+
6
+ const BUNDLED_PHP_RELATIVE_PATH = path.join("vendor", "php", "windows", "php.exe");
7
+
8
+ function resolvePhpBinary({ packageRoot, phpBinary }) {
9
+ const binaryPath = phpBinary
10
+ ? path.resolve(phpBinary)
11
+ : path.resolve(packageRoot, BUNDLED_PHP_RELATIVE_PATH);
12
+
13
+ if (!fs.existsSync(binaryPath)) {
14
+ throw new Error(
15
+ [
16
+ `Bundled PHP runtime not found at ${binaryPath}.`,
17
+ "Run `npm run bundle:php` before publishing or override the binary path with --php-binary.",
18
+ ].join(" ")
19
+ );
20
+ }
21
+
22
+ return binaryPath;
23
+ }
24
+
25
+ function findAvailablePort(host) {
26
+ return new Promise((resolve, reject) => {
27
+ const server = net.createServer();
28
+ server.unref();
29
+
30
+ server.on("error", reject);
31
+ server.listen(0, host, () => {
32
+ const address = server.address();
33
+ server.close(() => resolve(address.port));
34
+ });
35
+ });
36
+ }
37
+
38
+ async function waitForPhpServer(baseUrl, timeoutMs) {
39
+ const startedAt = Date.now();
40
+ const probeUrl = `${baseUrl}/__cwrespro_ready_probe__`;
41
+
42
+ while (Date.now() - startedAt < timeoutMs) {
43
+ try {
44
+ await fetch(probeUrl, { method: "GET" });
45
+ return;
46
+ } catch (error) {
47
+ await new Promise((resolve) => setTimeout(resolve, 150));
48
+ }
49
+ }
50
+
51
+ throw new Error(`Timed out waiting for PHP server at ${baseUrl}`);
52
+ }
53
+
54
+ async function startPhpServer({ packageRoot, docRoot, host, logger, phpBinary }) {
55
+ const binaryPath = resolvePhpBinary({ packageRoot, phpBinary });
56
+ const runtimeDir = path.dirname(binaryPath);
57
+ const phpIniPath = path.join(runtimeDir, "php.ini");
58
+ const port = await findAvailablePort(host);
59
+ const baseUrl = `http://${host}:${port}`;
60
+ const args = [];
61
+
62
+ if (fs.existsSync(phpIniPath)) {
63
+ args.push("-c", runtimeDir);
64
+ }
65
+
66
+ const stubsDir = path.join(packageRoot, "stubs");
67
+ const routerFile = path.join(stubsDir, "router.php");
68
+
69
+ args.push("-d", "include_path=" + docRoot + path.delimiter + stubsDir + path.delimiter + ".");
70
+ args.push("-S", `${host}:${port}`, "-t", docRoot);
71
+
72
+ if (fs.existsSync(routerFile)) {
73
+ args.push(routerFile);
74
+ }
75
+
76
+ const child = spawn(binaryPath, args, {
77
+ cwd: docRoot,
78
+ stdio: ["ignore", "pipe", "pipe"],
79
+ windowsHide: true,
80
+ });
81
+
82
+ const exitedEarly = new Promise((_, reject) => {
83
+ child.once("exit", (code, signal) => {
84
+ reject(new Error(`Bundled PHP exited before startup completed (code=${code}, signal=${signal || "none"}).`));
85
+ });
86
+ });
87
+
88
+ await Promise.race([waitForPhpServer(baseUrl, 10000), exitedEarly]);
89
+
90
+ return {
91
+ baseUrl,
92
+ binaryPath,
93
+ child,
94
+ port,
95
+ };
96
+ }
97
+
98
+ async function stopPhpServer(phpServer) {
99
+ if (!phpServer || !phpServer.child || phpServer.child.exitCode !== null) {
100
+ return;
101
+ }
102
+
103
+ await new Promise((resolve) => {
104
+ phpServer.child.once("exit", resolve);
105
+ phpServer.child.kill();
106
+ });
107
+ }
108
+
109
+ module.exports = {
110
+ BUNDLED_PHP_RELATIVE_PATH,
111
+ resolvePhpBinary,
112
+ startPhpServer,
113
+ stopPhpServer,
114
+ };
package/src/proxy.js ADDED
@@ -0,0 +1,91 @@
1
+ const { Readable } = require("node:stream");
2
+ const { injectLiveReload } = require("./injector");
3
+
4
+ function stripHopByHopHeaders(headers) {
5
+ const nextHeaders = { ...headers };
6
+ delete nextHeaders.host;
7
+ delete nextHeaders.connection;
8
+ delete nextHeaders["content-length"];
9
+ delete nextHeaders["transfer-encoding"];
10
+ return nextHeaders;
11
+ }
12
+
13
+ function buildTargetUrl(baseUrl, req) {
14
+ return new URL(req.originalUrl || req.url, baseUrl).toString();
15
+ }
16
+
17
+ function isHtmlResponse(contentType) {
18
+ return typeof contentType === "string" && contentType.toLowerCase().includes("text/html");
19
+ }
20
+
21
+ function applyResponseHeaders(upstreamHeaders, res, omitHeaders) {
22
+ upstreamHeaders.forEach((value, key) => {
23
+ if (omitHeaders.has(key.toLowerCase())) {
24
+ return;
25
+ }
26
+
27
+ res.setHeader(key, value);
28
+ });
29
+ }
30
+
31
+ async function readRequestBody(req) {
32
+ if (req.method === "GET" || req.method === "HEAD") {
33
+ return null;
34
+ }
35
+
36
+ const chunks = [];
37
+
38
+ for await (const chunk of req) {
39
+ chunks.push(chunk);
40
+ }
41
+
42
+ if (chunks.length === 0) {
43
+ return null;
44
+ }
45
+
46
+ return Buffer.concat(chunks);
47
+ }
48
+
49
+ async function proxyRequest({ req, res, target, injectHtml = false }) {
50
+ const body = await readRequestBody(req);
51
+ const upstream = await fetch(target, {
52
+ method: req.method,
53
+ headers: stripHopByHopHeaders(req.headers),
54
+ body,
55
+ redirect: "manual",
56
+ });
57
+
58
+ res.status(upstream.status);
59
+
60
+ const omittedHeaders = new Set([
61
+ "content-encoding",
62
+ "content-length",
63
+ "transfer-encoding",
64
+ ]);
65
+
66
+ applyResponseHeaders(upstream.headers, res, omittedHeaders);
67
+
68
+ if (req.method === "HEAD" || upstream.status === 204 || upstream.status === 304) {
69
+ res.end();
70
+ return;
71
+ }
72
+
73
+ if (injectHtml && isHtmlResponse(upstream.headers.get("content-type"))) {
74
+ const html = await upstream.text();
75
+ res.type("html");
76
+ res.end(injectLiveReload(html));
77
+ return;
78
+ }
79
+
80
+ if (!upstream.body) {
81
+ res.end();
82
+ return;
83
+ }
84
+
85
+ Readable.fromWeb(upstream.body).pipe(res);
86
+ }
87
+
88
+ module.exports = {
89
+ buildTargetUrl,
90
+ proxyRequest,
91
+ };