@plaudit/webpack-extensions 2.16.0 → 2.17.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.
@@ -9,12 +9,16 @@ export type PluginOptions = {
9
9
  };
10
10
  export declare class BrowserSyncPlugin implements WebpackPluginInstance {
11
11
  private static isBrowserSyncRunning;
12
- private readonly browserSyncOptions;
12
+ private static browserSyncPluginOptions;
13
+ private static envFileContents;
13
14
  private readonly pluginOptions;
14
15
  private readonly browserSyncInstance;
15
16
  private isWebpackWatching;
16
17
  private mostRecentChunkHashes;
17
- constructor(browserSyncOptions: browserSync.Options, pluginOptions?: Partial<PluginOptions>);
18
+ private shouldNotify;
19
+ constructor(pluginOptions?: Partial<PluginOptions>);
20
+ private static getBrowserSyncPluginOptions;
21
+ private static loadEnvFile;
18
22
  apply(compiler: Compiler): void;
19
23
  private getCssOnlyEmittedAssetsNames;
20
24
  }
@@ -4,37 +4,125 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BrowserSyncPlugin = void 0;
7
+ const node_child_process_1 = __importDefault(require("node:child_process"));
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_path_1 = __importDefault(require("node:path"));
7
10
  const browser_sync_1 = __importDefault(require("browser-sync"));
11
+ const http_proxy_middleware_1 = require("http-proxy-middleware");
12
+ const open_1 = __importDefault(require("open"));
8
13
  class BrowserSyncPlugin {
9
14
  static isBrowserSyncRunning = false;
10
- browserSyncOptions;
15
+ static browserSyncPluginOptions = undefined;
16
+ static envFileContents = undefined;
11
17
  pluginOptions;
12
18
  browserSyncInstance;
13
19
  isWebpackWatching = false;
14
20
  mostRecentChunkHashes = {};
15
- constructor(browserSyncOptions, pluginOptions) {
16
- this.browserSyncOptions = { ...browserSyncOptions };
21
+ shouldNotify = false;
22
+ constructor(pluginOptions) {
17
23
  this.pluginOptions = { reload: true, name: "plaudit-bs-plugin", injectCss: true, ...pluginOptions };
18
24
  this.browserSyncInstance = browser_sync_1.default.has(this.pluginOptions.name) ? browser_sync_1.default.get(this.pluginOptions.name) : browser_sync_1.default.create(this.pluginOptions.name);
19
25
  }
26
+ static getBrowserSyncPluginOptions() {
27
+ return BrowserSyncPlugin.browserSyncPluginOptions ?? (BrowserSyncPlugin.browserSyncPluginOptions = new Promise(resolve => {
28
+ const envFile = BrowserSyncPlugin.loadEnvFile();
29
+ const prefixes = node_child_process_1.default.spawnSync("theapp", ["info", "--for-browsersync"], {
30
+ encoding: "utf-8",
31
+ stdio: ["ignore", "pipe", "inherit"]
32
+ }).stdout.split(/\r?\n/g).map(url => url.trim()).filter(url => url.length > 0).map(url => url.substring(url.indexOf("://") + 3));
33
+ const targetPort = envFile.match(/WEB_PORT_SSL=(\d+)/i)?.[1] ?? "8443";
34
+ const targetHost = targetPort === "443" ? "localhost" : `localhost:${targetPort}`;
35
+ if (prefixes.length === 0) {
36
+ resolve([{
37
+ host: 'localhost',
38
+ port: 3000,
39
+ https: true,
40
+ proxy: `https://${targetHost}`
41
+ }, {}]);
42
+ }
43
+ else {
44
+ resolve([{
45
+ port: 3000,
46
+ https: true,
47
+ open: false,
48
+ callbacks: {
49
+ ready(err, bsi) {
50
+ // This ensures that the opened URL is actually a valid one
51
+ (0, open_1.default)(`https://${prefixes[0]}:${bsi.getOption("port") ?? 3000}`);
52
+ }
53
+ }
54
+ }, {
55
+ middlewareBuilder: (options) => {
56
+ const proxyPort = options.port?.toString() ?? "3000";
57
+ const router = prefixes.reduce((router, prefix) => {
58
+ router[`${prefix}:${proxyPort}`] = {
59
+ protocol: 'https:',
60
+ slashes: true,
61
+ auth: null,
62
+ host: prefix,
63
+ port: targetPort,
64
+ hostname: targetHost,
65
+ hash: null,
66
+ search: null,
67
+ query: null,
68
+ pathname: '/',
69
+ path: '/',
70
+ href: `https://${targetHost}/`
71
+ };
72
+ return router;
73
+ }, {});
74
+ const portInjectionPattern = new RegExp(`(${prefixes.join('|')})(?!:3000)`, "gi");
75
+ return (0, http_proxy_middleware_1.createProxyMiddleware)({
76
+ changeOrigin: true, router, secure: false, xfwd: true, selfHandleResponse: true,
77
+ on: {
78
+ proxyRes: (0, http_proxy_middleware_1.responseInterceptor)(async (responseBuffer, proxyRes) => {
79
+ const contentType = proxyRes.headers["content-type"];
80
+ if (contentType && (contentType.startsWith("text/") || contentType === "application/x-javascript")) {
81
+ return responseBuffer.toString('utf-8').replaceAll(portInjectionPattern, "$1:3000");
82
+ }
83
+ return responseBuffer;
84
+ })
85
+ }
86
+ });
87
+ }
88
+ }]);
89
+ }
90
+ }));
91
+ }
92
+ static loadEnvFile() {
93
+ if (BrowserSyncPlugin.envFileContents !== undefined) {
94
+ return BrowserSyncPlugin.envFileContents;
95
+ }
96
+ for (let envFileHolderPath = process.cwd(); envFileHolderPath.length > 5; envFileHolderPath = node_path_1.default.dirname(envFileHolderPath)) {
97
+ if (node_fs_1.default.existsSync(node_path_1.default.join(envFileHolderPath, ".env"))) {
98
+ return BrowserSyncPlugin.envFileContents = node_fs_1.default.readFileSync(node_path_1.default.join(envFileHolderPath, ".env"), { encoding: 'utf8' });
99
+ }
100
+ }
101
+ return "";
102
+ }
20
103
  apply(compiler) {
21
104
  compiler.hooks.watchRun.tap(BrowserSyncPlugin.name, () => {
22
105
  this.isWebpackWatching = true;
23
106
  });
24
107
  compiler.hooks.compilation.tap(BrowserSyncPlugin.name, () => {
25
- if (BrowserSyncPlugin.isBrowserSyncRunning && this.browserSyncOptions.notify) {
108
+ if (BrowserSyncPlugin.isBrowserSyncRunning && this.shouldNotify) {
26
109
  this.browserSyncInstance.notify('Rebuilding...');
27
110
  }
28
111
  });
29
- compiler.hooks.done.tap(BrowserSyncPlugin.name, stats => {
112
+ compiler.hooks.done.tapPromise(BrowserSyncPlugin.name, async (stats) => {
30
113
  if (!this.isWebpackWatching) {
31
114
  return;
32
115
  }
33
116
  if (!BrowserSyncPlugin.isBrowserSyncRunning) {
34
- const middleware = this.pluginOptions.middlewareBuilder?.(this.browserSyncOptions);
117
+ const [browserSyncOptions, pluginOptions] = await BrowserSyncPlugin.getBrowserSyncPluginOptions();
118
+ const actualPluginOptions = { ...this.pluginOptions, ...pluginOptions };
119
+ const middleware = actualPluginOptions.middlewareBuilder?.(browserSyncOptions);
35
120
  this.browserSyncInstance.init(middleware
36
- ? { ...this.browserSyncOptions, server: { middleware: Array.isArray(middleware) ? middleware : [middleware] } }
37
- : this.browserSyncOptions, this.pluginOptions.callback);
121
+ ? { ...browserSyncOptions, server: { middleware: Array.isArray(middleware) ? middleware : [middleware] } }
122
+ : browserSyncOptions, this.pluginOptions.callback);
123
+ if (browserSyncOptions.notify) {
124
+ this.shouldNotify = true;
125
+ }
38
126
  BrowserSyncPlugin.isBrowserSyncRunning = true;
39
127
  }
40
128
  if (this.pluginOptions.reload) {
@@ -12,8 +12,6 @@ const BrowserSyncPlugin_1 = require("./wordpress-scripts-wrapper/BrowserSyncPlug
12
12
  const static_configs_1 = require("./wordpress-scripts-wrapper/static-configs");
13
13
  const copy_webpack_plugin_1 = __importDefault(require("copy-webpack-plugin"));
14
14
  const fork_ts_checker_webpack_plugin_1 = __importDefault(require("fork-ts-checker-webpack-plugin"));
15
- const http_proxy_middleware_1 = require("http-proxy-middleware");
16
- const open_1 = __importDefault(require("open"));
17
15
  const webpack_remove_empty_scripts_1 = __importDefault(require("webpack-remove-empty-scripts"));
18
16
  function joinPossiblyAbsolutePaths(...paths) {
19
17
  return paths.reduce((res, p) => !res || node_path_1.default.isAbsolute(p) ? p : node_path_1.default.join(res, p), '') || '.';
@@ -27,18 +25,6 @@ function mapToRealEntrypoints(entrypoint, dir, mapper = (entrypoint) => entrypoi
27
25
  return [joinPossiblyAbsolutePaths(node_path_1.default.basename(parsedEntrypoint.dir), parsedEntrypoint.name), { import: ep }];
28
26
  });
29
27
  }
30
- let envFileContents = undefined;
31
- function loadEnvFile() {
32
- if (envFileContents !== undefined) {
33
- return envFileContents;
34
- }
35
- for (let envFileHolderPath = process.cwd(); envFileHolderPath.length > 5; envFileHolderPath = node_path_1.default.dirname(envFileHolderPath)) {
36
- if (node_fs_1.default.existsSync(node_path_1.default.join(envFileHolderPath, ".env"))) {
37
- return envFileContents = node_fs_1.default.readFileSync(node_path_1.default.join(envFileHolderPath, ".env"), { encoding: 'utf8' });
38
- }
39
- }
40
- return "";
41
- }
42
28
  function isTruthy(value) {
43
29
  return !!value;
44
30
  }
@@ -262,53 +248,7 @@ module.exports = function (config, webpackConfig = require("@wordpress/scripts/c
262
248
  plugins.push(new ExtensionsConfigFileGeneratorPlugin_1.default(srcRoot));
263
249
  }
264
250
  if (process.argv.includes('--browser-sync') || process.env['BROWSER_SYNC'] === 'true') {
265
- const envFile = loadEnvFile();
266
- const prefixes = envFile.match(/WORDPRESS_SITES=([^\r\n]+)/i)?.[1]?.split(/\s*,\s*/gi).map(domain => domain + ".");
267
- const targetPort = envFile.match(/WEB_PORT_SSL=(\d+)/i)?.[1] ?? "8443";
268
- const targetHost = targetPort === "443" ? "localhost" : `localhost:${targetPort}`;
269
- if (prefixes === undefined) {
270
- plugins.push(new BrowserSyncPlugin_1.BrowserSyncPlugin({
271
- host: 'localhost',
272
- port: 3000,
273
- https: true,
274
- proxy: `https://${targetHost}`
275
- }));
276
- }
277
- else {
278
- plugins.push(new BrowserSyncPlugin_1.BrowserSyncPlugin({
279
- port: 3000,
280
- https: true,
281
- open: false,
282
- callbacks: {
283
- ready(err, bsi) {
284
- // This ensures that the opened URL is actually a valid one
285
- (0, open_1.default)(`https://${prefixes[0]}localhost:${bsi.getOption("port") ?? 3000}`);
286
- }
287
- }
288
- }, {
289
- middlewareBuilder: (options) => {
290
- const proxyPort = options.port?.toString() ?? "3000";
291
- const router = prefixes.reduce((router, prefix) => {
292
- router[`${prefix}localhost:${proxyPort}`] = {
293
- protocol: 'https:',
294
- slashes: true,
295
- auth: null,
296
- host: `${prefix}localhost`,
297
- port: targetPort,
298
- hostname: targetHost,
299
- hash: null,
300
- search: null,
301
- query: null,
302
- pathname: '/',
303
- path: '/',
304
- href: `https://${targetHost}/`
305
- };
306
- return router;
307
- }, {});
308
- return (0, http_proxy_middleware_1.createProxyMiddleware)({ changeOrigin: true, router, secure: false, xfwd: true });
309
- }
310
- }));
311
- }
251
+ plugins.push(new BrowserSyncPlugin_1.BrowserSyncPlugin());
312
252
  }
313
253
  let entry;
314
254
  if (srcIsDirectory) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plaudit/webpack-extensions",
3
- "version": "2.16.0",
3
+ "version": "2.17.0",
4
4
  "scripts": {
5
5
  "prepublishOnly": "rm -rf build && mkdir build && tsc",
6
6
  "build": "tsc",