@plaudit/webpack-extensions 2.71.0 → 2.72.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.
@@ -6,10 +6,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ExtensionsConfigFileGeneratorPlugin = void 0;
7
7
  const promises_1 = __importDefault(require("node:fs/promises"));
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
+ const php_writer_1 = require("@plaudit/php-writer");
10
+ const expressions_1 = require("@plaudit/php-writer/expressions");
9
11
  const AbstractBiPhasicGroupAndEntryPlugin_1 = require("./AbstractBiPhasicGroupAndEntryPlugin");
10
12
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
11
13
  const shared_1 = require("../shared");
12
- const php_writer_1 = require("../utils/php-writer");
13
14
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
14
15
  const webpack_1 = require("webpack");
15
16
  class ExtensionsConfigFileGeneratorPlugin extends AbstractBiPhasicGroupAndEntryPlugin_1.AbstractBiPhasicGroupAndEntryPlugin {
@@ -98,10 +99,9 @@ class ExtensionsConfigFileGeneratorPlugin extends AbstractBiPhasicGroupAndEntryP
98
99
  return [block[0], Object.fromEntries(Object.entries(block[1]).toSorted(([a], [b]) => a.localeCompare(b)))];
99
100
  })
100
101
  .toSorted(([a], [b]) => a.localeCompare(b)));
101
- new php_writer_1.PHPWriter()
102
- .call("Plaudit\\Common\\Lib\\GutenbergUtils::loadExtensionsV3", [new php_writer_1.EnclosedLiteral((0, shared_1.makeEmittableConfigPHP)(blockExtensionsConfig, false)), php_writer_1.Op.concat(php_writer_1.Constants.__DIR__, '/'),
103
- php_writer_1.Expr.call("plaudit_webpack_extensions__resolve_base_uri", [php_writer_1.Constants.__DIR__])])
104
- .emitAsset(compilation, node_path_1.default.join(this.dest.destination, "extensions-loader.php"));
102
+ (0, shared_1.emitPHPWriterAsAsset)(new php_writer_1.PHPWriter()
103
+ .call("Plaudit\\Common\\Lib\\GutenbergUtils::loadExtensionsV3", [new expressions_1.EnclosedLiteral((0, shared_1.makeEmittableConfigPHP)(blockExtensionsConfig, false)), expressions_1.Op.concat(expressions_1.Constants.__DIR__, '/'),
104
+ expressions_1.Expr.call("plaudit_webpack_extensions__resolve_base_uri", [expressions_1.Constants.__DIR__])]), compilation, node_path_1.default.join(this.dest.destination, "extensions-loader.php"));
105
105
  }
106
106
  attachUniquePhase(compilation) {
107
107
  compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
@@ -5,10 +5,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ExtensionsConfigFileGeneratorPluginV1 = void 0;
7
7
  const node_path_1 = __importDefault(require("node:path"));
8
+ const php_writer_1 = require("@plaudit/php-writer");
9
+ const expressions_1 = require("@plaudit/php-writer/expressions");
8
10
  const AbstractBiPhasicGroupAndEntryPlugin_1 = require("./AbstractBiPhasicGroupAndEntryPlugin");
9
11
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
10
- const php_serializer_1 = require("../utils/php-serializer");
11
- const php_writer_1 = require("../utils/php-writer");
12
12
  const webpack_1 = require("webpack");
13
13
  class ExtensionsConfigFileGeneratorPluginV1 extends AbstractBiPhasicGroupAndEntryPlugin_1.AbstractBiPhasicGroupAndEntryPlugin {
14
14
  extensionsDest;
@@ -28,11 +28,11 @@ class ExtensionsConfigFileGeneratorPluginV1 extends AbstractBiPhasicGroupAndEntr
28
28
  (resourceInfo[key] ?? (resourceInfo[key] = [])).push([`plaudit_block-extension_${match[1]}-${match[2]}`, fileWithAssetData]);
29
29
  }
30
30
  }
31
- compilation.emitAsset(node_path_1.default.join(this.extensionsDest, "mapping.config"), new webpack_1.sources.RawSource((0, php_serializer_1.phpSerialize)(mapping)));
31
+ compilation.emitAsset(node_path_1.default.join(this.extensionsDest, "mapping.config"), new webpack_1.sources.RawSource((0, php_writer_1.phpSerialize)(mapping)));
32
32
  UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, { group: `extensions-config-v1-${this.extensionsDest}`, requiresBaseURI: false, action: writer => {
33
33
  writer
34
34
  .use("Plaudit\\Common\\Lib\\GutenbergUtils")
35
- .call("GutenbergUtils::installExtensionsSupport", [php_writer_1.Op.concat(php_writer_1.Constants.__DIR__, this.extensionsDest)]);
35
+ .call("GutenbergUtils::installExtensionsSupport", [expressions_1.Op.concat(expressions_1.Constants.__DIR__, this.extensionsDest)]);
36
36
  } });
37
37
  }
38
38
  }
@@ -5,8 +5,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.PlainEntrypointsConfigFileGeneratorPlugin = void 0;
7
7
  const node_path_1 = __importDefault(require("node:path"));
8
+ const php_writer_1 = require("@plaudit/php-writer");
9
+ const expressions_1 = require("@plaudit/php-writer/expressions");
8
10
  const shared_1 = require("../shared");
9
- const php_writer_1 = require("../utils/php-writer");
10
11
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
11
12
  const AbstractBiPhasicGroupAndEntryPlugin_1 = require("./AbstractBiPhasicGroupAndEntryPlugin");
12
13
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
@@ -78,12 +79,12 @@ class PlainEntrypointsConfigFileGeneratorPlugin extends AbstractBiPhasicGroupAnd
78
79
  if (!this.useUnifiedLoader) {
79
80
  (0, shared_1.emitResolveBaseUriFunction)(writer);
80
81
  }
81
- const baseUriVar = new php_writer_1.Var("base_uri");
82
+ const baseUriVar = new expressions_1.Var("base_uri");
82
83
  for (const [priority, prioritizedHandleList] of PlainEntrypointsConfigFileGeneratorPlugin.separateHandleListByPriority(handleLists.register)) {
83
84
  writer.action("init", writer => {
84
- writer.call("plaudit_webpack_extensions__resolve_base_uri", [php_writer_1.Constants.__DIR__], { assignTo: baseUriVar });
85
+ writer.call("plaudit_webpack_extensions__resolve_base_uri", [expressions_1.Constants.__DIR__], { assignTo: baseUriVar });
85
86
  for (const { handle, type, data } of prioritizedHandleList) {
86
- writer.call(`wp_register_${type}`, [handle, php_writer_1.Op.concat(baseUriVar, node_path_1.default.relative(emitDir, data.src)), ...data.rest]);
87
+ writer.call(`wp_register_${type}`, [handle, expressions_1.Op.concat(baseUriVar, node_path_1.default.relative(emitDir, data.src)), ...data.rest]);
87
88
  }
88
89
  }, { priority, accountForAlreadyDoing: this.config.includePostInitFallback });
89
90
  }
@@ -100,7 +101,7 @@ class PlainEntrypointsConfigFileGeneratorPlugin extends AbstractBiPhasicGroupAnd
100
101
  }
101
102
  }
102
103
  PlainEntrypointsConfigFileGeneratorPlugin.appendEnqueuingHandleLists(writer, handleLists);
103
- writer.emitAsset(compilation, "plain-entrypoints-loader.php");
104
+ (0, shared_1.emitPHPWriterAsAsset)(writer, compilation, "plain-entrypoints-loader.php");
104
105
  }
105
106
  static addHandlesToHandleLists(type, handles, handleLists) {
106
107
  for (const [handle, data] of handles) {
@@ -10,8 +10,9 @@ const node_fs_1 = __importDefault(require("node:fs"));
10
10
  const node_path_1 = __importDefault(require("node:path"));
11
11
  const AbstractBiPhasicGroupAndEntryPlugin_1 = require("./AbstractBiPhasicGroupAndEntryPlugin");
12
12
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
13
+ const php_writer_1 = require("@plaudit/php-writer");
14
+ const expressions_1 = require("@plaudit/php-writer/expressions");
13
15
  const shared_1 = require("../shared");
14
- const php_writer_1 = require("../utils/php-writer");
15
16
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
16
17
  const webpack_1 = require("webpack");
17
18
  class PlainEntrypointsStyleBlockJSONPlugin extends AbstractBiPhasicGroupAndEntryPlugin_1.AbstractBiPhasicGroupAndEntryPlugin {
@@ -119,12 +120,11 @@ class PlainEntrypointsStyleBlockJSONPlugin extends AbstractBiPhasicGroupAndEntry
119
120
  if (this.config.useUnifiedLoader) {
120
121
  const metadata = blockData['__metadata'];
121
122
  delete blockData['__metadata'];
122
- new php_writer_1.PHPWriter()
123
+ (0, shared_1.emitPHPWriterAsAsset)(new php_writer_1.PHPWriter()
123
124
  .action("init", writer => {
124
- writer.call("\\Plaudit\\Common\\ACF\\BlockManager::autoloadSubfoldersV3", [php_writer_1.Constants.__DIR__, new php_writer_1.EnclosedLiteral((0, shared_1.makeEmittableConfigPHP)(blockData, false, "\t")),
125
- php_writer_1.Constants.__FILE__, new php_writer_1.EnclosedLiteral((0, shared_1.makeEmittableConfigPHP)(metadata, false, "\t")), null]);
126
- }, { accountForAlreadyDoing: this.config.includePostInitFallback })
127
- .emitAsset(compilation, node_path_1.default.join(this.dest.destination, "blockdir-loader.php"));
125
+ writer.call("\\Plaudit\\Common\\ACF\\BlockManager::autoloadSubfoldersV3", [expressions_1.Constants.__DIR__, new expressions_1.EnclosedLiteral((0, shared_1.makeEmittableConfigPHP)(blockData, false, "\t")),
126
+ expressions_1.Constants.__FILE__, new expressions_1.EnclosedLiteral((0, shared_1.makeEmittableConfigPHP)(metadata, false, "\t")), null]);
127
+ }, { accountForAlreadyDoing: this.config.includePostInitFallback }), compilation, node_path_1.default.join(this.dest.destination, "blockdir-loader.php"));
128
128
  }
129
129
  else {
130
130
  compilation.emitAsset(node_path_1.default.join(this.dest.destination, "blockdir.config.php"), new webpack_1.sources.RawSource((0, shared_1.makeEmittableConfigPHP)(blockData, true)));
@@ -5,8 +5,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.SpecialAssetHandlingPlugin = void 0;
7
7
  const node_path_1 = __importDefault(require("node:path"));
8
+ const php_writer_1 = require("@plaudit/php-writer");
9
+ const expressions_1 = require("@plaudit/php-writer/expressions");
8
10
  const shared_1 = require("../shared");
9
- const php_writer_1 = require("../utils/php-writer");
10
11
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
11
12
  const AbstractBiPhasicGroupPlugin_1 = require("./AbstractBiPhasicGroupPlugin");
12
13
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
@@ -68,7 +69,7 @@ class SpecialAssetHandlingPlugin extends AbstractBiPhasicGroupPlugin_1.AbstractB
68
69
  const writer = new php_writer_1.PHPWriter();
69
70
  if (!preloadedAssets.length) {
70
71
  if (!this.config.useUnifiedLoader) {
71
- writer.emitAsset(compilation, outputFile);
72
+ (0, shared_1.emitPHPWriterAsAsset)(writer, compilation, outputFile);
72
73
  }
73
74
  return;
74
75
  }
@@ -76,8 +77,8 @@ class SpecialAssetHandlingPlugin extends AbstractBiPhasicGroupPlugin_1.AbstractB
76
77
  (0, shared_1.emitResolveBaseUriFunction)(writer);
77
78
  }
78
79
  writer.action("wp_head", writer => {
79
- const baseUriVar = new php_writer_1.Var("base_uri");
80
- writer.call("plaudit_webpack_extensions__resolve_base_uri", [php_writer_1.Constants.__DIR__], { assignTo: baseUriVar }).closePHP();
80
+ const baseUriVar = new expressions_1.Var("base_uri");
81
+ writer.call("plaudit_webpack_extensions__resolve_base_uri", [expressions_1.Constants.__DIR__], { assignTo: baseUriVar }).closePHP();
81
82
  for (let [filename, { preload, fetchpriority, crossorigin }] of preloadedAssets) {
82
83
  if (!preload) {
83
84
  continue;
@@ -116,11 +117,11 @@ class SpecialAssetHandlingPlugin extends AbstractBiPhasicGroupPlugin_1.AbstractB
116
117
  attributes.push(["crossorigin", crossorigin]);
117
118
  }
118
119
  const dynamicAttrs = attributes.map(([k, v]) => v ? `${k}="${v}"` : k).join(" ");
119
- writer.append(`<link rel="preload" href="<?= ${php_writer_1.Expr.call("esc_url", [php_writer_1.Op.concat(baseUriVar, filename)])} ?>" ${dynamicAttrs}>`);
120
+ writer.append(`<link rel="preload" href="<?= ${expressions_1.Expr.call("esc_url", [expressions_1.Op.concat(baseUriVar, filename)])} ?>" ${dynamicAttrs}>`);
120
121
  }
121
122
  writer.openPHP();
122
123
  });
123
- writer.emitAsset(compilation, outputFile);
124
+ (0, shared_1.emitPHPWriterAsAsset)(writer, compilation, outputFile);
124
125
  }
125
126
  attachUniquePhase(compilation) {
126
127
  compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
@@ -1,6 +1,6 @@
1
+ import { PHPWriter } from "@plaudit/php-writer";
1
2
  import { AbstractBiPhasicGroupPlugin } from "./AbstractBiPhasicGroupPlugin";
2
3
  import type { VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
3
- import { PHPWriter } from "../utils/php-writer";
4
4
  import { PseudoSemaphore } from "../utils/pseduo-semaphore";
5
5
  import { Compilation } from "webpack";
6
6
  type LoaderInfo = {
@@ -5,10 +5,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.UnifiedLoaderGenerator = void 0;
7
7
  const node_path_1 = __importDefault(require("node:path"));
8
+ const php_writer_1 = require("@plaudit/php-writer");
8
9
  const AbstractBiPhasicGroupPlugin_1 = require("./AbstractBiPhasicGroupPlugin");
9
10
  const shared_1 = require("../shared");
10
- const json_to_php_but_with____injection_1 = __importDefault(require("../utils/json-to-php-but-with-__-injection"));
11
- const php_writer_1 = require("../utils/php-writer");
12
11
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
13
12
  const webpack_1 = require("webpack");
14
13
  class UnifiedLoaderGenerator extends AbstractBiPhasicGroupPlugin_1.AbstractBiPhasicGroupPlugin {
@@ -53,7 +52,7 @@ class UnifiedLoaderGenerator extends AbstractBiPhasicGroupPlugin_1.AbstractBiPha
53
52
  continue;
54
53
  }
55
54
  const parsedPath = node_path_1.default.parse(file);
56
- const contents = `<?php return ${(0, json_to_php_but_with____injection_1.default)(assetData)};\n`;
55
+ const contents = `<?php return ${(0, php_writer_1.json2php)(assetData)};\n`;
57
56
  compilation.emitAsset(node_path_1.default.join(parsedPath.dir, parsedPath.name) + ".asset.php", new webpack_1.sources.RawSource(contents), { size: Buffer.byteLength(contents) });
58
57
  }
59
58
  if (this.config.useUnifiedLoader) {
@@ -65,7 +64,7 @@ class UnifiedLoaderGenerator extends AbstractBiPhasicGroupPlugin_1.AbstractBiPha
65
64
  for (const { action } of groupedLoaderInfo) {
66
65
  action(writer);
67
66
  }
68
- writer.emitAsset(compilation, "unified-loader.php");
67
+ (0, shared_1.emitPHPWriterAsAsset)(writer, compilation, "unified-loader.php");
69
68
  });
70
69
  }
71
70
  });
package/build/shared.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { PHPWriter } from "./utils/php-writer";
1
+ import { PHPWriter } from "@plaudit/php-writer";
2
2
  import type { Options as PostcssFunctionsOptions } from "postcss-functions";
3
- import { Compilation, type Configuration, WebpackError } from "webpack";
3
+ import { AssetInfo, Compilation, type Configuration, WebpackError } from "webpack";
4
4
  export type ParsedAssetsJson = Record<string, {
5
5
  dependencies: string[];
6
6
  version: string;
@@ -146,4 +146,5 @@ export declare function newWebpackErrorForFile(error: string | ConstructorParame
146
146
  */
147
147
  export declare function emitResolveBaseUriFunction(writer: PHPWriter): void;
148
148
  export declare function getAssetsJson(compilation: Compilation): ParsedAssetsJson;
149
+ export declare function emitPHPWriterAsAsset(writer: PHPWriter, compilation: Compilation, file: string, assetInfo?: AssetInfo): void;
149
150
  export {};
package/build/shared.js CHANGED
@@ -24,9 +24,10 @@ exports.parseEnvFile = parseEnvFile;
24
24
  exports.newWebpackErrorForFile = newWebpackErrorForFile;
25
25
  exports.emitResolveBaseUriFunction = emitResolveBaseUriFunction;
26
26
  exports.getAssetsJson = getAssetsJson;
27
+ exports.emitPHPWriterAsAsset = emitPHPWriterAsAsset;
27
28
  const promises_1 = __importDefault(require("node:fs/promises"));
28
- const json_to_php_but_with____injection_1 = __importDefault(require("./utils/json-to-php-but-with-__-injection"));
29
- const php_writer_1 = require("./utils/php-writer");
29
+ const php_writer_1 = require("@plaudit/php-writer");
30
+ const expressions_1 = require("@plaudit/php-writer/expressions");
30
31
  const webpack_1 = require("webpack");
31
32
  function isParsedAssetsJson(thing) {
32
33
  if (!thing || typeof thing !== 'object') {
@@ -73,7 +74,7 @@ function convertUsageLocationsHandleToEmittableHandle(handle, generatedHandle) {
73
74
  return emittableHandle.replaceAll("{basename}", generatedHandle);
74
75
  }
75
76
  function makeEmittableConfigPHP(data, asFullFile, parentIndent = "") {
76
- const prettyPrintedMetadata = json_to_php_but_with____injection_1.default.make({ indent: "\t", linebreak: "\n", shortArraySyntax: true })(data, parentIndent)
77
+ const prettyPrintedMetadata = php_writer_1.json2php.make({ indent: "\t", linebreak: "\n", shortArraySyntax: true })(data, parentIndent)
77
78
  .replaceAll(/(\n\t*)\[\s+],/gs, "$1[],")
78
79
  .replaceAll(/\[\n\t+([^\n]+)\n\t+]/gs, (_, inner) => `[${inner.trim()}]`)
79
80
  .replaceAll(/'rest' => \[\n\t+(\[(?:'[^']+')?]),\n\t+('[^']+')(?:,\n\t+(\[[^\n]+]))?\n\t+]/gs, (_, deps, hash, args) => `'rest' => [${[deps, hash, args].filter(value => !!value).join(", ")}]`);
@@ -143,24 +144,24 @@ function newWebpackErrorForFile(error, file) {
143
144
  * The primary benefit of emitting a function instead of baking its contents into each function that uses it is that it allows us to avoid recomputing the base uri multiple times
144
145
  */
145
146
  function emitResolveBaseUriFunction(writer) {
146
- const dir = new php_writer_1.Var("dir");
147
- const baseUris = new php_writer_1.Var("base_uris");
148
- const assignmentTarget = new php_writer_1.ArrayAccess(baseUris, dir);
149
- const path = new php_writer_1.Var("path");
147
+ const dir = new expressions_1.Var("dir");
148
+ const baseUris = new expressions_1.Var("base_uris");
149
+ const assignmentTarget = new expressions_1.ArrayAccess(baseUris, dir);
150
+ const path = new expressions_1.Var("path");
150
151
  writer.function("plaudit_webpack_extensions__resolve_base_uri", [dir], writer => {
151
152
  writer
152
153
  .static(baseUris, { initializer: [] })
153
- .if(php_writer_1.Expr.isset(assignmentTarget))
154
+ .if(expressions_1.Expr.isset(assignmentTarget))
154
155
  .return(assignmentTarget)
155
- .elseIf(php_writer_1.Expr.call("str_starts_with", [dir, php_writer_1.Constants.ABSPATH]))
156
- .assign(path, php_writer_1.Expr.call("ltrim", [php_writer_1.Expr.call("substr", [dir, php_writer_1.Expr.call("strlen", [php_writer_1.Constants.ABSPATH])]), "/"]))
157
- .elseIf(php_writer_1.Expr.call("str_starts_with", [dir, "/workspace/website"]))
158
- .assign(path, php_writer_1.Expr.call("ltrim", [php_writer_1.Expr.call("substr", [dir, 18]), "/"]))
156
+ .elseIf(expressions_1.Expr.call("str_starts_with", [dir, expressions_1.Constants.ABSPATH]))
157
+ .assign(path, expressions_1.Expr.call("ltrim", [expressions_1.Expr.call("substr", [dir, expressions_1.Expr.call("strlen", [expressions_1.Constants.ABSPATH])]), "/"]))
158
+ .elseIf(expressions_1.Expr.call("str_starts_with", [dir, "/workspace/website"]))
159
+ .assign(path, expressions_1.Expr.call("ltrim", [expressions_1.Expr.call("substr", [dir, 18]), "/"]))
159
160
  .else()
160
161
  .call("error_log", ["UNABLE TO FIGURE OUT WHAT THE RELATIVE PATH TO THE BUILT FILES DIRECTORY SHOULD BE"])
161
162
  .assign(path, "")
162
163
  .endIf()
163
- .call("trailingslashit", [php_writer_1.Expr.call("home_url", [path])], { return: true, assignTo: assignmentTarget });
164
+ .call("trailingslashit", [expressions_1.Expr.call("home_url", [path])], { return: true, assignTo: assignmentTarget });
164
165
  }, { returnType: "string", includeExistenceCheck: true });
165
166
  }
166
167
  function getAssetsJson(compilation) {
@@ -178,3 +179,7 @@ function getAssetsJson(compilation) {
178
179
  compilation.updateAsset("assets.json", s => s, a => ({ ...a, "parsed-assets-json": parsedAssetJson }));
179
180
  return parsedAssetJson;
180
181
  }
182
+ function emitPHPWriterAsAsset(writer, compilation, file, assetInfo) {
183
+ const contents = writer.toString() + "\n";
184
+ compilation[file in compilation.assets ? 'updateAsset' : 'emitAsset'](file, new webpack_1.sources.RawSource(contents), { size: Buffer.byteLength(contents), ...assetInfo });
185
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plaudit/webpack-extensions",
3
- "version": "2.71.0",
3
+ "version": "2.72.0",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "files": [
6
6
  "/build"
@@ -22,7 +22,7 @@
22
22
  "devDependencies": {
23
23
  "@plaudit/gutenberg-api-extensions": "^2.77.2",
24
24
  "@types/browser-sync-webpack-plugin": "^2.2.5",
25
- "@types/node": "^24.7.1",
25
+ "@types/node": "^24.7.2",
26
26
  "@types/postcss-functions": "^4.0.4",
27
27
  "@types/tapable": "^2.3.0",
28
28
  "@types/webpack": "^5.28.5",
@@ -34,6 +34,7 @@
34
34
  "webpack-bundle-analyzer": "^4.10.2"
35
35
  },
36
36
  "dependencies": {
37
+ "@plaudit/php-writer": "^1.0.0",
37
38
  "@plaudit/postcss-color-function": "^5.0.0",
38
39
  "@plaudit/postcss-legacy-shorthand": "^1.0.0",
39
40
  "@plaudit/postcss-silent-extend": "^3.0.0",
@@ -1,11 +0,0 @@
1
- type MakeProps = {
2
- linebreak?: string;
3
- indent?: string;
4
- shortArraySyntax?: boolean;
5
- stripSpaces?: boolean;
6
- };
7
- declare const make: (props?: MakeProps) => (obj: unknown, parentIndent?: string) => string;
8
- declare const json2php: ReturnType<typeof make> & {
9
- make: typeof make;
10
- };
11
- export default json2php;
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const acceptedObjectTypes = ['[object Array]', '[object Object]'];
4
- const make = (props = {}) => {
5
- const linebreak = props.linebreak ?? '';
6
- const indent = props.indent ?? '';
7
- const stripSpaces = props.stripSpaces ?? false;
8
- const shortArraySyntax = props.shortArraySyntax ?? true;
9
- const arrOpen = shortArraySyntax ? '[' : 'array(';
10
- const arrClose = shortArraySyntax ? ']' : ')';
11
- const arrow = stripSpaces ? '=>' : ' => ';
12
- function transformInner(obj, parentIndent, state) {
13
- switch (typeof obj) {
14
- case 'undefined':
15
- return 'null';
16
- case 'bigint':
17
- case 'number':
18
- case 'boolean':
19
- return obj.toString();
20
- case 'string':
21
- const res = obj.replace("\\", '\\\\').replaceAll("'", "\\'");
22
- if (!/\s*/.test(res) && !state.isKey && state.path.length === 4 && state.path[1] === 'attributes' && state.path[3] === 'default' && state.parent?.['translatable']) {
23
- return `__('${res}')`;
24
- }
25
- return `'${res}'`;
26
- case 'object':
27
- if (obj === null)
28
- return 'null';
29
- const objType = Object.prototype.toString.call(obj);
30
- if (objType === '[object Date]')
31
- return obj.toISOString();
32
- if (!acceptedObjectTypes.includes(objType))
33
- return 'null';
34
- const nestIndent = parentIndent + indent;
35
- const items = Array.isArray(obj)
36
- ? obj.map((item, i) => transformInner(item, nestIndent, { path: [...state.path, i], parent: obj }))
37
- : Object.entries(obj).map(([key, value]) => {
38
- return transformInner(key, nestIndent, { path: [...state.path, key], parent: obj, isKey: true })
39
- + arrow + transformInner(value, nestIndent, { path: [...state.path, key], parent: obj });
40
- });
41
- const itemStr = items.join(`,${linebreak === '' && !stripSpaces ? ' ' : linebreak + nestIndent}`);
42
- return `${arrOpen}${linebreak + nestIndent}${itemStr}${linebreak + parentIndent}${arrClose}`;
43
- default:
44
- return 'null';
45
- }
46
- }
47
- return function transform(obj, parentIndent = '') {
48
- return transformInner(obj, parentIndent, { path: [] });
49
- };
50
- };
51
- const json2php = make();
52
- json2php.make = make;
53
- exports.default = json2php;
@@ -1,6 +0,0 @@
1
- type Config = {
2
- objectsAsArrays?: boolean;
3
- excludedKeys?: string[];
4
- };
5
- export declare function phpSerialize(value: any, config?: Config): string;
6
- export {};
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.phpSerialize = phpSerialize;
4
- function phpSerialize(value, config) {
5
- switch (typeof value) {
6
- case "undefined":
7
- return "N;";
8
- case "object":
9
- if (value === null) {
10
- return "N;"; // Yep. Null is an "object" in JavaScript
11
- }
12
- else if (Array.isArray(value)) {
13
- let res = `a:${value.length}:{`;
14
- for (let i = 0; i < value.length; i++) {
15
- res += `i:${i};${phpSerialize(value[i], config)}`;
16
- }
17
- return (res.endsWith('};') ? res.substring(0, res.length - 1) : res) + "}";
18
- }
19
- return entriesInArrayAndObjectFormat(config?.objectsAsArrays ?? true ? 'a' : 'O:8:"stdClass"', Object.entries(value), config);
20
- case "boolean":
21
- return `b:${value ? 1 : 0};`;
22
- case "number":
23
- return Number.isInteger(value) ? serializeInteger(value) : `d:${value};`;
24
- case "string":
25
- return `s:${Buffer.byteLength(value, 'utf8')}:"${value}";`;
26
- case "function":
27
- throw new Error(`We are unable to serialize functions into a form readable by PHP.`);
28
- case "symbol":
29
- value = value.toString();
30
- return `s:${Buffer.byteLength(value, 'utf8')}:"${value}";`;
31
- case "bigint":
32
- return serializeInteger(value);
33
- }
34
- }
35
- function serializeInteger(value) {
36
- const str = value.toString();
37
- if (str.includes("e") || str.includes("E")) {
38
- return `d:${str.replace(/e/i, ".0e")};`;
39
- }
40
- return `i:${str};`;
41
- }
42
- function entriesInArrayAndObjectFormat(prefix, entries, config) {
43
- const excludedKeys = config?.excludedKeys ?? [];
44
- let res = "";
45
- let count = 0;
46
- for (const [k, v] of entries) {
47
- if (!excludedKeys.includes(k)) {
48
- count++;
49
- res += `${phpSerialize(k, config)}${phpSerialize(v, config)}`;
50
- }
51
- }
52
- return `${prefix}:${count}:{` + (res.endsWith('};') ? res.substring(0, res.length - 1) : res) + "}";
53
- }
@@ -1,237 +0,0 @@
1
- import { AssetInfo, Compilation } from "webpack";
2
- export declare abstract class Expr {
3
- static readonly jsonToPHPConverter: (obj: unknown, parentIndent?: string) => string;
4
- static readonly convertJsonToPHP: (obj: unknown) => string;
5
- protected constructor();
6
- abstract toString(): string;
7
- typeName(): string;
8
- static isset(...checks: (Var | ArrayAccess | ObjectAccess)[]): Call;
9
- static call(name: string, args: ConstructorParameters<typeof Call>[1]): Call;
10
- }
11
- export interface EnclosableExpression extends Expr {
12
- toEnclosedForm(): string;
13
- not(): Not;
14
- }
15
- export interface PotentiallyWriteableExpression extends EnclosableExpression {
16
- readonly potentiallyWritable: true;
17
- }
18
- export declare function isEnclosableExpression(a: unknown): a is EnclosableExpression;
19
- export declare function isPotentiallyWriteableExpression(a: unknown): a is PotentiallyWriteableExpression;
20
- export declare abstract class AbstractEnclosableExpression extends Expr implements EnclosableExpression {
21
- static readonly closers: Readonly<{
22
- "(": ")";
23
- "[": "]";
24
- "{": "}";
25
- }>;
26
- abstract toEnclosedForm(): string;
27
- not(): Not;
28
- }
29
- export declare abstract class ParenthesesEnclosableExpression extends AbstractEnclosableExpression {
30
- toEnclosedForm(): string;
31
- }
32
- export declare abstract class EnclosedExpression extends AbstractEnclosableExpression {
33
- toEnclosedForm(): string;
34
- }
35
- export declare class Literal extends Expr {
36
- readonly expression: string;
37
- constructor(expression: string);
38
- toString(): string;
39
- static of(expression: string | PHPWriter, enclosed: true): EnclosedLiteral;
40
- static of(expression: string | PHPWriter, enclosureOpen: keyof typeof AbstractEnclosableExpression.closers, encloserClose?: string): EnclosableLiteral;
41
- static of(expression: string | PHPWriter, enclosureOpen: string, encloserClose: string): EnclosableLiteral;
42
- static of(expression: string | PHPWriter, enclosed?: false | undefined): Literal;
43
- static name(expression: string): EnclosedLiteral;
44
- }
45
- export declare class EnclosedLiteral extends Literal implements EnclosableExpression {
46
- constructor(expression: string);
47
- toEnclosedForm(): string;
48
- not(): Not;
49
- }
50
- export declare class EnclosableLiteral extends Literal implements EnclosableExpression {
51
- private readonly enclosureOpen;
52
- private readonly enclosureClose;
53
- constructor(expression: string, enclosureOpen: string, enclosureClose: string);
54
- toEnclosedForm(): string;
55
- not(): Not;
56
- }
57
- export declare class Var extends EnclosedExpression implements PotentiallyWriteableExpression {
58
- readonly name: string;
59
- readonly potentiallyWritable = true;
60
- constructor(name: string);
61
- toString(): string;
62
- }
63
- export declare class Op extends ParenthesesEnclosableExpression {
64
- readonly operator: string;
65
- readonly args: readonly unknown[];
66
- constructor(operator: string, ...args: unknown[]);
67
- toString(): string;
68
- static binary(left: unknown, operator: string, right: unknown): Op;
69
- static concat(...args: unknown[]): Op;
70
- }
71
- export declare class Not extends ParenthesesEnclosableExpression {
72
- readonly expression: EnclosableExpression;
73
- constructor(expression: EnclosableExpression);
74
- toString(): string;
75
- }
76
- type AtLeastOneArray<T> = [T, ...T[]];
77
- type ReadonlyAtLeastOneArray<T> = readonly [T, ...T[]];
78
- export type Accessor = Expr | string | number;
79
- export type AccessorOrAccessorArray = Accessor | AtLeastOneArray<Accessor>;
80
- export declare abstract class Access extends EnclosedExpression implements PotentiallyWriteableExpression {
81
- readonly target: EnclosableExpression;
82
- readonly potentiallyWritable = true;
83
- readonly accesses: ReadonlyAtLeastOneArray<Accessor>;
84
- constructor(target: EnclosableExpression, accesses: AccessorOrAccessorArray);
85
- abstract endsWithCall(): boolean;
86
- abstract endsWithPotentiallyWritableExpression(): boolean;
87
- }
88
- export declare class ArrayAccess extends Access {
89
- toString(): string;
90
- endsWithCall(): boolean;
91
- endsWithPotentiallyWritableExpression(): boolean;
92
- }
93
- export declare class ObjectAccess extends Access {
94
- static readonly validObjectKey: RegExp;
95
- toString(): string;
96
- endsWithCall(): boolean;
97
- endsWithPotentiallyWritableExpression(): boolean;
98
- }
99
- export declare class Call extends EnclosedExpression implements PotentiallyWriteableExpression {
100
- readonly callee: string | EnclosableExpression;
101
- readonly args: readonly unknown[];
102
- readonly potentiallyWritable = true;
103
- constructor(callee: string | EnclosableExpression, args: readonly unknown[]);
104
- toString(): string;
105
- }
106
- export declare class Parameter extends Expr {
107
- readonly value: unknown;
108
- readonly name?: string | undefined;
109
- constructor(value: unknown, name?: string | undefined);
110
- toString(): string;
111
- }
112
- export declare class FirstClassCallable extends ParenthesesEnclosableExpression {
113
- readonly name: EnclosableExpression;
114
- constructor(name: EnclosableExpression);
115
- static from(literal: string): FirstClassCallable;
116
- toString(): string;
117
- }
118
- export declare const validPHPLabel: RegExp;
119
- type Assignable = EnclosedExpression & PotentiallyWriteableExpression;
120
- export declare class Assignment extends ParenthesesEnclosableExpression {
121
- readonly value: unknown;
122
- readonly push: boolean;
123
- readonly assignees: ReadonlyAtLeastOneArray<Assignable>;
124
- constructor(assignees: Assignable, value: unknown, push: true);
125
- constructor(assignees: Assignable | AtLeastOneArray<Assignable>, value: unknown, push?: false | undefined);
126
- toString(): string;
127
- }
128
- export declare abstract class Constants {
129
- static readonly __FILE__: EnclosedLiteral;
130
- static readonly __DIR__: EnclosedLiteral;
131
- static readonly ABSPATH: EnclosedLiteral;
132
- }
133
- export type AppendExprArgs = {
134
- chain?: boolean;
135
- return?: boolean;
136
- };
137
- export type ActionOrFilterArgs = {
138
- priority?: number | Expr;
139
- functionArgParameters?: string[];
140
- useVars?: Var[];
141
- accountForAlreadyDoing?: boolean | Parameters<PHPWriter['call']>[1];
142
- };
143
- export type FunctionCreationArgs = {
144
- includeExistenceCheck?: boolean;
145
- useVars?: Var[];
146
- returnType?: string;
147
- assignToName?: boolean;
148
- scopeActionDescription?: string;
149
- };
150
- export type RequireOrIncludeArgs = {
151
- dirRelative?: boolean;
152
- once?: boolean;
153
- } & AppendExprArgs;
154
- export declare class PHPWriter {
155
- private readonly inlineFirstLine;
156
- private readonly scopeStack;
157
- private readonly useList;
158
- private readonly allocatedGeneratedFunctionNames;
159
- private readonly isSubwriter;
160
- private printingInPHP;
161
- private buffer;
162
- private indentation;
163
- private fileNamespace;
164
- private myOpenedScopes;
165
- constructor(inlineFirstLine?: boolean, scopeStack?: string[][], useList?: string[], allocatedGeneratedFunctionNames?: Set<string>, isSubwriter?: boolean, printingInPHP?: boolean, initialIndentation?: number);
166
- createSubwriter(): PHPWriter;
167
- indent(): this;
168
- outdent(): this;
169
- setIndentation(level: number): this;
170
- /**
171
- * @param lines These are treated as literal *regardless of their types*
172
- */
173
- append(...lines: (string | Expr)[]): this;
174
- /**
175
- * @param expr This is treated as literal *regardless of its type*
176
- * @param opts flags to add additional markup around the expression
177
- */
178
- appendExpr(expr: string | Expr, opts?: AppendExprArgs): this;
179
- assign(assignee: ConstructorParameters<typeof Assignment>[0] | string, expression: unknown, opts?: AppendExprArgs): this;
180
- return(expression: unknown | Expr): this;
181
- static(variable: Var | string, opts?: {
182
- initializer?: unknown | Literal;
183
- withTest?: boolean | 'chainable';
184
- }): this;
185
- linebreak(): this;
186
- /**
187
- * @param func This is treated as literal *regardless of its type*
188
- * @param args
189
- * @param opts
190
- */
191
- call(func: string | EnclosableExpression, args: unknown[], opts?: {
192
- assignTo?: ConstructorParameters<typeof Assignment>[0];
193
- } & AppendExprArgs): this;
194
- action(name: string | Expr, contents: (writer: PHPWriter) => void, args?: ActionOrFilterArgs): this;
195
- filter(name: string | Expr, contents: (writer: PHPWriter) => void, args?: ActionOrFilterArgs): this;
196
- actionOrFilter(type: 'action' | 'filter', name: string | Expr, contents: (writer: PHPWriter) => void, args: ActionOrFilterArgs): this;
197
- if(condition: Expr): this;
198
- elseIf(condition: Expr): this;
199
- else(): this;
200
- endIf(): this;
201
- function(name: true, parameters: (string | Var)[], body: (writer: PHPWriter) => void, args?: FunctionCreationArgs): Var;
202
- function(name: string | Var | false, parameters: (string | Var)[], body: (writer: PHPWriter) => void, args?: FunctionCreationArgs): this;
203
- generateFunctionName(asVariable: true): Var;
204
- generateFunctionName(asVariable?: false | undefined): string;
205
- generateFunctionName(asVariable?: boolean): string | Var;
206
- closePHP(): this;
207
- openPHP(): this;
208
- namespace(namespace: string): this;
209
- use(...uses: string[]): this;
210
- require(filePath: string | Expr, args?: RequireOrIncludeArgs): this;
211
- include(filePath: string | Expr, args?: RequireOrIncludeArgs): this;
212
- requireOrInclude(type: 'require' | 'include', filePath: string | Expr, args: RequireOrIncludeArgs): this;
213
- /**
214
- * Starts a scope that, when paired with {@link #closeScope()}, allows for automating unset calls.
215
- * All scopes started MUST be paired with either an {@link #closeScope()} or {@link #popScope()} call.
216
- */
217
- openScope(): this;
218
- /**
219
- * Pops the top scope from the stack AND unsets all variables that were assigned within it
220
- */
221
- closeScope(): this;
222
- /**
223
- * Pops the top scope from the stack WITHOUT calling unset for the variables that were assigned within it.
224
- * This is used to allow function bodies to be safely created without disrupting their containing scope.
225
- */
226
- popScope(): this;
227
- withScope(code: (writer: PHPWriter) => void, opts?: {
228
- actionDescription?: string;
229
- usePopScopeInstead?: boolean;
230
- }): this;
231
- toString(args?: {
232
- includeOpenPHP?: boolean;
233
- includeNamespaceAndUse?: boolean;
234
- }): string;
235
- emitAsset(compilation: Compilation, file: string, assetInfo?: AssetInfo): void;
236
- }
237
- export {};
@@ -1,634 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.PHPWriter = exports.Constants = exports.Assignment = exports.validPHPLabel = exports.FirstClassCallable = exports.Parameter = exports.Call = exports.ObjectAccess = exports.ArrayAccess = exports.Access = exports.Not = exports.Op = exports.Var = exports.EnclosableLiteral = exports.EnclosedLiteral = exports.Literal = exports.EnclosedExpression = exports.ParenthesesEnclosableExpression = exports.AbstractEnclosableExpression = exports.Expr = void 0;
7
- exports.isEnclosableExpression = isEnclosableExpression;
8
- exports.isPotentiallyWriteableExpression = isPotentiallyWriteableExpression;
9
- const json_to_php_but_with____injection_1 = __importDefault(require("./json-to-php-but-with-__-injection"));
10
- const webpack_1 = require("webpack");
11
- class Expr {
12
- static jsonToPHPConverter = json_to_php_but_with____injection_1.default.make({ shortArraySyntax: true });
13
- static convertJsonToPHP = (obj) => obj instanceof Expr ? obj.toString() : Expr.jsonToPHPConverter(obj);
14
- constructor() { }
15
- // noinspection JSUnusedGlobalSymbols - this technically-unused method is necessary for TypeScript to differentiate subclasses of Expr from any
16
- typeName() {
17
- return this.constructor.name;
18
- }
19
- static isset(...checks) {
20
- return Expr.call("isset", checks);
21
- }
22
- static call(name, args) {
23
- return new Call(Literal.name(name), args);
24
- }
25
- }
26
- exports.Expr = Expr;
27
- function isEnclosableExpression(a) {
28
- return a instanceof Expr && 'toEnclosedForm' in a && typeof a.toEnclosedForm === 'function';
29
- }
30
- function isPotentiallyWriteableExpression(a) {
31
- return isEnclosableExpression(a) && 'potentiallyWritable' in a && a.potentiallyWritable === true;
32
- }
33
- class AbstractEnclosableExpression extends Expr {
34
- static closers = Object.freeze({ "(": ")", "[": "]", "{": "}" });
35
- not() {
36
- return new Not(this);
37
- }
38
- }
39
- exports.AbstractEnclosableExpression = AbstractEnclosableExpression;
40
- class ParenthesesEnclosableExpression extends AbstractEnclosableExpression {
41
- toEnclosedForm() {
42
- return "(" + this.toString() + ")";
43
- }
44
- }
45
- exports.ParenthesesEnclosableExpression = ParenthesesEnclosableExpression;
46
- class EnclosedExpression extends AbstractEnclosableExpression {
47
- toEnclosedForm() {
48
- return this.toString();
49
- }
50
- }
51
- exports.EnclosedExpression = EnclosedExpression;
52
- class Literal extends Expr {
53
- expression;
54
- constructor(expression) {
55
- super();
56
- this.expression = expression;
57
- }
58
- toString() {
59
- return this.expression;
60
- }
61
- static of(expression, enclosed = false, enclosureClose) {
62
- if (expression instanceof PHPWriter) {
63
- expression = expression.toString({ includeOpenPHP: false, includeNamespaceAndUse: false }).trim();
64
- }
65
- if (typeof enclosed === 'string') {
66
- return new EnclosableLiteral(expression, enclosed, enclosureClose ?? AbstractEnclosableExpression.closers[enclosed] ?? enclosed);
67
- }
68
- if (enclosed) {
69
- return new EnclosedLiteral(expression);
70
- }
71
- return new Literal(expression);
72
- }
73
- static name(expression) {
74
- return new EnclosedLiteral(expression);
75
- }
76
- }
77
- exports.Literal = Literal;
78
- class EnclosedLiteral extends Literal {
79
- constructor(expression) {
80
- super(expression);
81
- }
82
- toEnclosedForm() {
83
- return this.toString();
84
- }
85
- not() {
86
- return new Not(this);
87
- }
88
- }
89
- exports.EnclosedLiteral = EnclosedLiteral;
90
- class EnclosableLiteral extends Literal {
91
- enclosureOpen;
92
- enclosureClose;
93
- constructor(expression, enclosureOpen, enclosureClose) {
94
- super(expression);
95
- this.enclosureOpen = enclosureOpen;
96
- this.enclosureClose = enclosureClose;
97
- }
98
- toEnclosedForm() {
99
- return this.enclosureOpen + this.toString() + this.enclosureClose;
100
- }
101
- not() {
102
- return new Not(this);
103
- }
104
- }
105
- exports.EnclosableLiteral = EnclosableLiteral;
106
- class Var extends EnclosedExpression {
107
- name;
108
- potentiallyWritable = true;
109
- constructor(name) {
110
- super();
111
- this.name = name;
112
- }
113
- toString() {
114
- return "$" + this.name;
115
- }
116
- }
117
- exports.Var = Var;
118
- class Op extends ParenthesesEnclosableExpression {
119
- operator;
120
- args;
121
- constructor(operator, ...args) {
122
- super();
123
- this.operator = operator;
124
- this.args = args;
125
- }
126
- toString() {
127
- return this.args
128
- .map(a => isEnclosableExpression(a) ? a.toEnclosedForm() : Expr.convertJsonToPHP(a))
129
- .join(this.operator);
130
- }
131
- static binary(left, operator, right) {
132
- return new Op(operator, left, right);
133
- }
134
- static concat(...args) {
135
- return new Op(".", ...args);
136
- }
137
- }
138
- exports.Op = Op;
139
- class Not extends ParenthesesEnclosableExpression {
140
- expression;
141
- constructor(expression) {
142
- super();
143
- this.expression = expression;
144
- }
145
- toString() {
146
- return "!" + this.expression.toEnclosedForm();
147
- }
148
- }
149
- exports.Not = Not;
150
- class Access extends EnclosedExpression {
151
- target;
152
- potentiallyWritable = true;
153
- accesses;
154
- constructor(target, accesses) {
155
- super();
156
- this.target = target;
157
- this.accesses = Array.isArray(accesses) ? accesses : [accesses];
158
- }
159
- }
160
- exports.Access = Access;
161
- class ArrayAccess extends Access {
162
- toString() {
163
- return this.target.toEnclosedForm() + this.accesses.map(a => `[${Expr.convertJsonToPHP(a)}]`).join("");
164
- }
165
- endsWithCall() {
166
- return false;
167
- }
168
- endsWithPotentiallyWritableExpression() {
169
- return true;
170
- }
171
- }
172
- exports.ArrayAccess = ArrayAccess;
173
- class ObjectAccess extends Access {
174
- static validObjectKey = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
175
- toString() {
176
- return [this.target.toString(), ...this.accesses.map(a => {
177
- if ((typeof a === 'string' && ObjectAccess.validObjectKey.test(a)) || a instanceof Var || a instanceof Call) {
178
- return a;
179
- }
180
- return "{" + Expr.convertJsonToPHP(a) + "}";
181
- })].join("->");
182
- }
183
- endsWithCall() {
184
- return this.accesses[this.accesses.length - 1] instanceof Call;
185
- }
186
- endsWithPotentiallyWritableExpression() {
187
- return isPotentiallyWriteableExpression(this.accesses[this.accesses.length - 1]);
188
- }
189
- }
190
- exports.ObjectAccess = ObjectAccess;
191
- class Call extends EnclosedExpression {
192
- callee;
193
- args;
194
- potentiallyWritable = true;
195
- constructor(callee, args) {
196
- super();
197
- this.callee = callee;
198
- this.args = args;
199
- }
200
- toString() {
201
- const callee = typeof this.callee === 'string' ? Expr.convertJsonToPHP(this.callee) : this.callee.toEnclosedForm();
202
- return `${callee}(${this.args.map(Expr.convertJsonToPHP).join(", ")})`;
203
- }
204
- }
205
- exports.Call = Call;
206
- class Parameter extends Expr {
207
- value;
208
- name;
209
- constructor(value, name) {
210
- super();
211
- this.value = value;
212
- this.name = name;
213
- }
214
- toString() {
215
- return this.name ? `${this.name}: ${Expr.convertJsonToPHP(this.value)}` : Expr.convertJsonToPHP(this.value);
216
- }
217
- }
218
- exports.Parameter = Parameter;
219
- class FirstClassCallable extends ParenthesesEnclosableExpression {
220
- name;
221
- constructor(name) {
222
- super();
223
- this.name = name;
224
- }
225
- static from(literal) {
226
- return new FirstClassCallable(Literal.name(literal));
227
- }
228
- toString() {
229
- return this.name.toEnclosedForm() + "(...)";
230
- }
231
- }
232
- exports.FirstClassCallable = FirstClassCallable;
233
- exports.validPHPLabel = /^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/; // This is from https://www.php.net/manual/en/functions.user-defined.php
234
- class Assignment extends ParenthesesEnclosableExpression {
235
- value;
236
- push;
237
- assignees;
238
- constructor(assignees, value, push = false) {
239
- super();
240
- this.value = value;
241
- this.push = push;
242
- this.assignees = Array.isArray(assignees) ? assignees : [assignees];
243
- if (this.assignees.some(a => a instanceof Access && !a.endsWithPotentiallyWritableExpression())) {
244
- throw new Error("Cannot assign a value to an access chain that does not end in a writable state");
245
- }
246
- if (!this.push && this.assignees.some(a => a instanceof Call || (a instanceof Access && a.endsWithCall()))) {
247
- throw new Error("Cannot assign a value to an access chain that ends in a function call unless that 'assignment' is a push");
248
- }
249
- }
250
- toString() {
251
- if (this.push) {
252
- return this.assignees[0].toEnclosedForm() + "[] = " + Expr.convertJsonToPHP(this.value);
253
- }
254
- return [...this.assignees.map(t => t.toEnclosedForm()), Expr.convertJsonToPHP(this.value)].join(" = ");
255
- }
256
- }
257
- exports.Assignment = Assignment;
258
- class Constants {
259
- static __FILE__ = Literal.name("__FILE__");
260
- static __DIR__ = Literal.name("__DIR__");
261
- static ABSPATH = Literal.name("ABSPATH");
262
- }
263
- exports.Constants = Constants;
264
- class PHPWriter {
265
- inlineFirstLine;
266
- scopeStack;
267
- useList;
268
- allocatedGeneratedFunctionNames;
269
- isSubwriter;
270
- printingInPHP;
271
- buffer = [];
272
- indentation;
273
- fileNamespace = "";
274
- myOpenedScopes = 0;
275
- constructor(inlineFirstLine = false, scopeStack = [], useList = [], allocatedGeneratedFunctionNames = new Set(), isSubwriter = false, printingInPHP = true, initialIndentation = 0) {
276
- this.inlineFirstLine = inlineFirstLine;
277
- this.scopeStack = scopeStack;
278
- this.useList = useList;
279
- this.allocatedGeneratedFunctionNames = allocatedGeneratedFunctionNames;
280
- this.isSubwriter = isSubwriter;
281
- this.printingInPHP = printingInPHP;
282
- this.indentation = "\t".repeat(initialIndentation);
283
- }
284
- createSubwriter() {
285
- return new PHPWriter(false, this.scopeStack, this.useList, this.allocatedGeneratedFunctionNames, true, this.printingInPHP, this.indentation.length)
286
- .setIndentation(this.indentation.length);
287
- }
288
- indent() {
289
- this.indentation += "\t";
290
- return this;
291
- }
292
- outdent() {
293
- this.indentation = this.indentation.slice(0, -1);
294
- return this;
295
- }
296
- setIndentation(level) {
297
- this.indentation = "\t".repeat(level);
298
- return this;
299
- }
300
- /**
301
- * @param lines These are treated as literal *regardless of their types*
302
- */
303
- append(...lines) {
304
- for (const line of lines) {
305
- this.buffer.push(`${this.indentation}${line}`);
306
- }
307
- return this;
308
- }
309
- /**
310
- * @param expr This is treated as literal *regardless of its type*
311
- * @param opts flags to add additional markup around the expression
312
- */
313
- appendExpr(expr, opts = {}) {
314
- let expression;
315
- if (isEnclosableExpression(expr)) {
316
- expression = opts.chain ? expr.toEnclosedForm() : expr.toString();
317
- }
318
- else if (opts.chain && expr instanceof Expr) {
319
- throw new Error(`Cannot chain non-enclosable expressions`);
320
- }
321
- else {
322
- expression = expr.toString();
323
- }
324
- if (opts.chain && expr instanceof Expr && !isEnclosableExpression(expr)) {
325
- throw new Error(`Cannot chain non-enclosable expressions`);
326
- }
327
- const res = (opts.return ? "return " : "") + expression;
328
- return this.append(!opts.chain ? res + ';' : res);
329
- }
330
- assign(assignee, expression, opts = {}) {
331
- if (typeof assignee === 'string') {
332
- assignee = new Var(assignee);
333
- }
334
- if (Array.isArray(assignee)) {
335
- if (this.scopeStack.length > 0) {
336
- this.scopeStack[this.scopeStack.length - 1].push(...assignee.filter(v => v instanceof Var).map(v => v.name));
337
- }
338
- }
339
- else {
340
- if (this.scopeStack.length > 0 && assignee instanceof Var) {
341
- this.scopeStack[this.scopeStack.length - 1].push(assignee.name);
342
- }
343
- }
344
- return this.appendExpr(new Assignment(assignee, expression), opts);
345
- }
346
- return(expression) {
347
- return this.appendExpr(Expr.convertJsonToPHP(expression), { return: true });
348
- }
349
- static(variable, opts = {}) {
350
- if (typeof variable === 'string') {
351
- variable = new Var(variable);
352
- }
353
- const initializer = opts.initializer ? Expr.convertJsonToPHP(opts.initializer) : "null";
354
- this.append(`static ${variable.toEnclosedForm()} = ${initializer};`);
355
- if (opts.withTest) {
356
- this.if(Op.binary(variable, "!==", new Literal(initializer)))
357
- .append(`return ${Expr.convertJsonToPHP(variable)};`);
358
- if (opts.withTest !== 'chainable') {
359
- this.endIf();
360
- }
361
- }
362
- return this;
363
- }
364
- linebreak() {
365
- this.buffer.push("");
366
- return this;
367
- }
368
- /**
369
- * @param func This is treated as literal *regardless of its type*
370
- * @param args
371
- * @param opts
372
- */
373
- call(func, args, opts = {}) {
374
- const functionCall = new Call(typeof func === 'string' ? Literal.name(func) : func, args);
375
- if (opts.assignTo) {
376
- return this.assign(opts.assignTo, functionCall, opts);
377
- }
378
- return this.appendExpr(functionCall, opts);
379
- }
380
- action(name, contents, args = {}) {
381
- return this.actionOrFilter('action', name, contents, args);
382
- }
383
- filter(name, contents, args = {}) {
384
- return this.actionOrFilter('filter', name, contents, args);
385
- }
386
- actionOrFilter(type, name, contents, args) {
387
- const { priority = 10, functionArgParameters = [], useVars = [], accountForAlreadyDoing } = args;
388
- const functionWriter = this.createSubwriter();
389
- let declarationFunction;
390
- if (accountForAlreadyDoing) {
391
- if (functionArgParameters.length > 0 && accountForAlreadyDoing === true) {
392
- console.trace(`The accountForAlreadyDoing flag must be set to a list of default parameters when applied to ${type}s that take arguments`);
393
- }
394
- this.openPHP().openScope();
395
- const functionName = functionWriter.function(true, functionArgParameters, contents, { useVars, scopeActionDescription: `closing the function call for the ${name} ${type}.`, assignToName: true });
396
- this.append(functionWriter.toString().trim());
397
- declarationFunction = new FirstClassCallable(functionName);
398
- this.if(Expr.call(`doing_${type}`, [name]))
399
- .call(functionName, accountForAlreadyDoing === true ? [] : accountForAlreadyDoing);
400
- }
401
- else {
402
- functionWriter.function(false, functionArgParameters, contents, { useVars, scopeActionDescription: `closing the function call for the ${name} ${type}.` });
403
- declarationFunction = Literal.of(functionWriter);
404
- }
405
- // The trailing comma inside the first item is necessary
406
- const additionArgs = [name, declarationFunction];
407
- const accepted_args = Math.max(functionArgParameters.length, 1); // This avoids us unnecessarily setting the accepted_args value to 0 for actions
408
- if (priority !== 10) {
409
- additionArgs.push(priority);
410
- if (accepted_args !== 1) {
411
- additionArgs.push(accepted_args);
412
- }
413
- }
414
- else if (accepted_args !== 1) {
415
- additionArgs.push(new Parameter(accepted_args, "accepted_args"));
416
- }
417
- const line = Expr.call(`add_${type}`, additionArgs);
418
- if (accountForAlreadyDoing) {
419
- return this
420
- .else()
421
- .appendExpr(line)
422
- .endIf()
423
- .closeScope();
424
- }
425
- return this.openPHP().appendExpr(line);
426
- }
427
- if(condition) {
428
- return this.openPHP().append(`if (${condition}) {`).indent();
429
- }
430
- elseIf(condition) {
431
- return this.openPHP().outdent().append(`} else if (${condition}) {`).indent();
432
- }
433
- else() {
434
- return this.openPHP().outdent().append(`} else {`).indent();
435
- }
436
- endIf() {
437
- return this.openPHP().outdent().append("}");
438
- }
439
- function(name, parameters, body, args = {}) {
440
- if (name === false) {
441
- if (args.includeExistenceCheck) {
442
- console.trace('Anonymous functions cannot have their existence checked for');
443
- }
444
- if (args.assignToName) {
445
- console.trace('Anonymous functions cannot be assigned to a name');
446
- }
447
- }
448
- if (typeof name === 'string') {
449
- if (!exports.validPHPLabel.test(name)) {
450
- throw new Error(`'${name}' is not a valid function name. Please see https://www.php.net/manual/en/functions.user-defined.php for what constitutes one`);
451
- }
452
- }
453
- const returningString = name === true;
454
- if (name === true) {
455
- name = this.generateFunctionName(args.assignToName);
456
- }
457
- if (args.includeExistenceCheck) {
458
- this.if(Expr.call('function_exists', [name]).not());
459
- }
460
- else {
461
- this.openPHP();
462
- }
463
- if (name instanceof Var) {
464
- if (this.scopeStack.length > 0) {
465
- this.scopeStack[this.scopeStack.length - 1].push(name.name);
466
- }
467
- }
468
- const declarationComponents = name === false ? [] : (name instanceof Var ? [name, '='] : ["function"]);
469
- let nameAndParameters = `${!name || name instanceof Var ? 'function' : name}(${parameters.join(", ")})`;
470
- if (args.useVars?.length) {
471
- let useVars = `use (${args.useVars.join(", ")})`;
472
- if (args.returnType) {
473
- useVars += `: ${args.returnType}`;
474
- }
475
- declarationComponents.push(nameAndParameters, useVars);
476
- }
477
- else {
478
- if (args.returnType) {
479
- nameAndParameters += `: ${args.returnType}`;
480
- }
481
- declarationComponents.push(nameAndParameters);
482
- }
483
- declarationComponents.push("{");
484
- this.append(declarationComponents.join(' '));
485
- this.indent();
486
- // We start a new scope here just in case this was called within an existing scope
487
- // We pop the scope instead of closing it because we don't actually want to unset any variables that were created within the function
488
- this.withScope(body, { actionDescription: args.scopeActionDescription ?? `closing the "${name || "anonymous"}" function`, usePopScopeInstead: true });
489
- this.openPHP().outdent().append(name !== false && args.assignToName ? "};" : "}");
490
- if (args.includeExistenceCheck) {
491
- this.endIf();
492
- }
493
- return returningString ? name : this;
494
- }
495
- generateFunctionName(asVariable = false) {
496
- let count = 0;
497
- let name;
498
- do {
499
- name = `plaudit_webpack_extensions__generated_function__${count++}`;
500
- } while (this.allocatedGeneratedFunctionNames.has(name));
501
- this.allocatedGeneratedFunctionNames.add(name);
502
- return asVariable ? new Var(name) : name;
503
- }
504
- closePHP() {
505
- if (!this.printingInPHP) {
506
- return this;
507
- }
508
- this.printingInPHP = false;
509
- return this.append("?>");
510
- }
511
- openPHP() {
512
- if (this.printingInPHP) {
513
- return this;
514
- }
515
- this.printingInPHP = true;
516
- return this.append("<?php");
517
- }
518
- namespace(namespace) {
519
- this.fileNamespace = namespace;
520
- return this;
521
- }
522
- use(...uses) {
523
- for (const use of uses) {
524
- if (!this.useList.find(u => u.toLowerCase() === use.toLowerCase())) {
525
- this.useList.push(use);
526
- }
527
- }
528
- return this;
529
- }
530
- require(filePath, args = {}) {
531
- return this.requireOrInclude('require', filePath, args);
532
- }
533
- include(filePath, args = {}) {
534
- return this.requireOrInclude('include', filePath, args);
535
- }
536
- requireOrInclude(type, filePath, args) {
537
- const command = args.once ? `${type}_once` : type;
538
- if (args.dirRelative && typeof filePath === 'string' && !filePath.startsWith("/")) {
539
- filePath = "/" + filePath;
540
- }
541
- const path = args.dirRelative ? Op.concat(Constants.__DIR__, filePath) : Expr.convertJsonToPHP(filePath);
542
- return this.appendExpr(`${command} ${path}`, args);
543
- }
544
- /**
545
- * Starts a scope that, when paired with {@link #closeScope()}, allows for automating unset calls.
546
- * All scopes started MUST be paired with either an {@link #closeScope()} or {@link #popScope()} call.
547
- */
548
- openScope() {
549
- this.scopeStack.push([]);
550
- this.myOpenedScopes++;
551
- return this;
552
- }
553
- /**
554
- * Pops the top scope from the stack AND unsets all variables that were assigned within it
555
- */
556
- closeScope() {
557
- if (!this.myOpenedScopes) {
558
- return this;
559
- }
560
- this.myOpenedScopes--;
561
- const scope = this.scopeStack.pop();
562
- if (!scope?.length) {
563
- return this;
564
- }
565
- const uniquenessSet = new Set();
566
- const uniqueScopeItems = scope.filter(si => !uniquenessSet.has(si) && uniquenessSet.add(si));
567
- for (const scopeItem of uniqueScopeItems) {
568
- this.allocatedGeneratedFunctionNames.delete(scopeItem);
569
- }
570
- // This is equivalent to calling this.call("unset", scope.map(v => new Var(v))), but creates fewer objects
571
- return this.append(`unset(${uniqueScopeItems.map(usi => "$" + usi).join(", ")});`);
572
- }
573
- /**
574
- * Pops the top scope from the stack WITHOUT calling unset for the variables that were assigned within it.
575
- * This is used to allow function bodies to be safely created without disrupting their containing scope.
576
- */
577
- popScope() {
578
- if (this.myOpenedScopes) {
579
- this.scopeStack.pop();
580
- this.myOpenedScopes--;
581
- }
582
- return this;
583
- }
584
- withScope(code, opts = {}) {
585
- const expectedScopeCount = this.scopeStack.length;
586
- this.openScope();
587
- code(this);
588
- if (opts.usePopScopeInstead) {
589
- this.popScope();
590
- }
591
- else {
592
- this.closeScope();
593
- }
594
- if (expectedScopeCount !== this.scopeStack.length) {
595
- console.trace(`Encountered an unexpected number of scopes (saw: ${this.scopeStack.length}, expected: ${expectedScopeCount})`, `while ${opts.actionDescription ?? "ending an encapsulating scope"}.`);
596
- }
597
- return this;
598
- }
599
- toString(args = this.isSubwriter ? { includeOpenPHP: false, includeNamespaceAndUse: false } : {}) {
600
- if (this.myOpenedScopes) {
601
- console.trace("toString() was called on a PHPWriter that has a dangling scope");
602
- }
603
- const fileContents = [];
604
- let canInline = true;
605
- if (args.includeNamespaceAndUse !== false) {
606
- if (this.fileNamespace) {
607
- canInline = false;
608
- fileContents.push(`namespace ${this.fileNamespace};`);
609
- }
610
- if (this.useList.length) {
611
- canInline = false;
612
- fileContents.push(...this.useList.map(use => `use ${use};`));
613
- }
614
- }
615
- fileContents.push(...this.buffer);
616
- if (args.includeOpenPHP === false) {
617
- return fileContents.join("\n");
618
- }
619
- if (this.inlineFirstLine && canInline) {
620
- return `<?php ${fileContents.join("\n")}`;
621
- }
622
- else if (fileContents.find(line => line.length > 0)) {
623
- return "<?php\n" + fileContents.join("\n");
624
- }
625
- else {
626
- return "<?php";
627
- }
628
- }
629
- emitAsset(compilation, file, assetInfo) {
630
- const contents = this.toString() + "\n";
631
- compilation[file in compilation.assets ? 'updateAsset' : 'emitAsset'](file, new webpack_1.sources.RawSource(contents), { size: Buffer.byteLength(contents), ...assetInfo });
632
- }
633
- }
634
- exports.PHPWriter = PHPWriter;