@plaudit/webpack-extensions 2.63.2 → 2.65.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 (34) hide show
  1. package/build/plugins/AbstractBiPhasicGroupAndEntryPlugin.d.ts +22 -0
  2. package/build/plugins/{AbstractMultiPhaseLibraryAndEntryPlugin.js → AbstractBiPhasicGroupAndEntryPlugin.js} +31 -8
  3. package/build/plugins/AbstractBiPhasicGroupPlugin.d.ts +33 -0
  4. package/build/plugins/AbstractBiPhasicGroupPlugin.js +93 -0
  5. package/build/plugins/AdditionalDependencyInjectorPlugin.d.ts +3 -1
  6. package/build/plugins/AdditionalDependencyInjectorPlugin.js +5 -3
  7. package/build/plugins/EnhancedDynamicEntryPlugin.d.ts +8 -0
  8. package/build/plugins/EnhancedDynamicEntryPlugin.js +12 -0
  9. package/build/plugins/ExtensionsConfigFileGeneratorPlugin.d.ts +9 -8
  10. package/build/plugins/ExtensionsConfigFileGeneratorPlugin.js +108 -142
  11. package/build/plugins/ExtensionsConfigFileGeneratorPluginV1.d.ts +8 -6
  12. package/build/plugins/ExtensionsConfigFileGeneratorPluginV1.js +22 -32
  13. package/build/plugins/PlainEntrypointsConfigFileGeneratorPlugin.d.ts +8 -8
  14. package/build/plugins/PlainEntrypointsConfigFileGeneratorPlugin.js +51 -82
  15. package/build/plugins/PlainEntrypointsStyleBlockJSONPlugin.d.ts +6 -7
  16. package/build/plugins/PlainEntrypointsStyleBlockJSONPlugin.js +78 -107
  17. package/build/plugins/SpecialAssetHandlingPlugin.d.ts +5 -6
  18. package/build/plugins/SpecialAssetHandlingPlugin.js +45 -51
  19. package/build/plugins/UnifiedLoaderGenerator.d.ts +8 -8
  20. package/build/plugins/UnifiedLoaderGenerator.js +59 -46
  21. package/build/plugins/WPMLConfigBuilder.d.ts +3 -1
  22. package/build/plugins/WPMLConfigBuilder.js +7 -4
  23. package/build/shared.d.ts +7 -5
  24. package/build/shared.js +19 -3
  25. package/build/utils/common-config-helpers.d.ts +5 -3
  26. package/build/utils/common-config-helpers.js +10 -31
  27. package/build/utils/json-to-php-but-with-__-injection.js +1 -1
  28. package/build/utils/pseduo-semaphore.d.ts +2 -3
  29. package/build/utils/pseduo-semaphore.js +9 -5
  30. package/build/wordpress-scripts-wrapper.js +116 -106
  31. package/package.json +1 -2
  32. package/build/plugins/AbstractMultiPhaseLibraryAndEntryPlugin.d.ts +0 -19
  33. package/build/plugins/AbstractMultiPhaseLibraryPlugin.d.ts +0 -14
  34. package/build/plugins/AbstractMultiPhaseLibraryPlugin.js +0 -37
@@ -5,45 +5,35 @@ 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 AbstractMultiPhaseLibraryPlugin_1 = require("./AbstractMultiPhaseLibraryPlugin");
8
+ const AbstractBiPhasicGroupAndEntryPlugin_1 = require("./AbstractBiPhasicGroupAndEntryPlugin");
9
9
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
10
10
  const php_serializer_1 = require("../utils/php-serializer");
11
11
  const php_writer_1 = require("../utils/php-writer");
12
12
  const webpack_1 = require("webpack");
13
- class ExtensionsConfigFileGeneratorPluginV1 extends AbstractMultiPhaseLibraryPlugin_1.AbstractMultiPhaseLibraryPlugin {
13
+ class ExtensionsConfigFileGeneratorPluginV1 extends AbstractBiPhasicGroupAndEntryPlugin_1.AbstractBiPhasicGroupAndEntryPlugin {
14
14
  extensionsDest;
15
- constructor(extensionsDest) {
16
- super(`extensions-v1-${extensionsDest}`, [UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore]);
15
+ constructor(config, extensionsDest, context, entry) {
16
+ super(config, `extensions-v1-${extensionsDest}`, [UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore], context, entry);
17
17
  this.extensionsDest = extensionsDest;
18
18
  }
19
- apply(compiler) {
20
- super.apply(compiler);
21
- compiler.hooks.compilation.tap(this.constructor.name, compilation => {
22
- compilation.hooks.processAssets.tap({ name: `${this.constructor.name}_UnifiedLoaderGeneratorIntegration`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_DERIVED }, () => {
23
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, { group: `extensions-config-v1-${this.extensionsDest}`, requiresBaseURI: false, action: writer => {
24
- writer
25
- .use("Plaudit\\Common\\Lib\\GutenbergUtils")
26
- .call("GutenbergUtils::installExtensionsSupport", [php_writer_1.Op.join(php_writer_1.Constants.__DIR__, this.extensionsDest)]);
27
- } });
28
- });
29
- compilation.hooks.afterProcessAssets.tap(`${this.constructor.name}_AfterProcessAssets`, compilationAssets => {
30
- const regex = /^(.+?)-((?:editor-|view-|)(?:style|script|script-module))\.(?:css|m?js)$/i;
31
- const mapping = {};
32
- for (const asset of Object.keys(compilationAssets)) {
33
- let match;
34
- if ((match = /^(.+?)-setup.php$/i.exec(asset)) && match[1]) {
35
- (mapping[match[1]] ?? (mapping[match[1]] = [{}]))[1] = `${asset}`;
36
- }
37
- else if ((match = regex.exec(asset)) && match[1] && match[2]) {
38
- const resourceInfo = (mapping[match[1]] ?? (mapping[match[1]] = [{}]))[0];
39
- const key = match[2].replace(/-[sm]/gi, chars => chars.substring(1).toUpperCase());
40
- (resourceInfo[key] ?? (resourceInfo[key] = [])).push([`plaudit_block-extension_${match[1]}-${match[2]}`, asset]);
41
- }
42
- }
43
- compilation.emitAsset(node_path_1.default.join(this.extensionsDest, "mapping.config"), new webpack_1.sources.RawSource((0, php_serializer_1.phpSerialize)(mapping)));
44
- });
45
- });
19
+ attachUniquePhase() { }
20
+ processAssets(compilation, assetsJson) {
21
+ const regex = /^(.+?)-((?:editor-|view-|)(?:style|script|script-module))\.(?:css|m?js)$/i;
22
+ const mapping = {};
23
+ for (const fileWithAssetData of Object.keys(this.extractRelevantAssetData(compilation, assetsJson))) {
24
+ let match;
25
+ if ((match = regex.exec(fileWithAssetData)) && match[1] && match[2]) {
26
+ const resourceInfo = (mapping[match[1]] ?? (mapping[match[1]] = [{}]))[0];
27
+ const key = match[2].replace(/-[sm]/gi, chars => chars.substring(1).toUpperCase());
28
+ (resourceInfo[key] ?? (resourceInfo[key] = [])).push([`plaudit_block-extension_${match[1]}-${match[2]}`, fileWithAssetData]);
29
+ }
30
+ }
31
+ compilation.emitAsset(node_path_1.default.join(this.extensionsDest, "mapping.config"), new webpack_1.sources.RawSource((0, php_serializer_1.phpSerialize)(mapping)));
32
+ UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, { group: `extensions-config-v1-${this.extensionsDest}`, requiresBaseURI: false, action: writer => {
33
+ writer
34
+ .use("Plaudit\\Common\\Lib\\GutenbergUtils")
35
+ .call("GutenbergUtils::installExtensionsSupport", [php_writer_1.Op.join(php_writer_1.Constants.__DIR__, this.extensionsDest)]);
36
+ } });
46
37
  }
47
- attachSecondPhase(compilation) { }
48
38
  }
49
39
  exports.ExtensionsConfigFileGeneratorPluginV1 = ExtensionsConfigFileGeneratorPluginV1;
@@ -1,18 +1,18 @@
1
- import { UnpackedBlockEntrypointInfo, UsageLocations } from "../shared";
2
- import { AbstractMultiPhaseLibraryAndEntryPlugin, EntryProvider } from "./AbstractMultiPhaseLibraryAndEntryPlugin";
3
- import { Compilation, type Compiler } from "webpack";
4
- export declare class PlainEntrypointsConfigFileGeneratorPlugin extends AbstractMultiPhaseLibraryAndEntryPlugin<UnpackedBlockEntrypointInfo | string> {
1
+ import { ParsedAssetsJson, UnpackedBlockEntrypointInfo, UsageLocations } from "../shared";
2
+ import type { VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
3
+ import { AbstractBiPhasicGroupAndEntryPlugin, EntryProvider } from "./AbstractBiPhasicGroupAndEntryPlugin";
4
+ import { Compilation } from "webpack";
5
+ export declare class PlainEntrypointsConfigFileGeneratorPlugin extends AbstractBiPhasicGroupAndEntryPlugin<UnpackedBlockEntrypointInfo | string> {
5
6
  private readonly buildRoot;
6
7
  private readonly outputDir;
7
8
  private readonly usageLocations;
8
- private readonly handlePrefix;
9
9
  private readonly useUnifiedLoader;
10
10
  private static readonly semaphore;
11
- constructor(buildRoot: string, outputDir: string, usageLocations: UsageLocations, handlePrefix: string, useUnifiedLoader: boolean, context: string, entry: EntryProvider<UnpackedBlockEntrypointInfo | string>);
12
- apply(compiler: Compiler): void;
11
+ constructor(config: VerifiedPlauditWordpressWebpackConfig, buildRoot: string, outputDir: string, usageLocations: UsageLocations, useUnifiedLoader: boolean, context: string, entry: EntryProvider<UnpackedBlockEntrypointInfo | string>);
13
12
  private generatePlainEntrypointsLoader;
14
13
  private static addHandlesToHandleLists;
15
14
  private static appendEnqueuingHandleLists;
16
15
  private static separateHandleListByPriority;
17
- protected attachSecondPhase(compilation: Compilation): void;
16
+ protected attachUniquePhase(compilation: Compilation): void;
17
+ protected processAssets(compilation: Compilation, assetsJson: ParsedAssetsJson): void;
18
18
  }
@@ -8,97 +8,22 @@ const node_path_1 = __importDefault(require("node:path"));
8
8
  const shared_1 = require("../shared");
9
9
  const php_writer_1 = require("../utils/php-writer");
10
10
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
11
- const AbstractMultiPhaseLibraryAndEntryPlugin_1 = require("./AbstractMultiPhaseLibraryAndEntryPlugin");
11
+ const AbstractBiPhasicGroupAndEntryPlugin_1 = require("./AbstractBiPhasicGroupAndEntryPlugin");
12
12
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
13
13
  const webpack_1 = require("webpack");
14
- class PlainEntrypointsConfigFileGeneratorPlugin extends AbstractMultiPhaseLibraryAndEntryPlugin_1.AbstractMultiPhaseLibraryAndEntryPlugin {
14
+ class PlainEntrypointsConfigFileGeneratorPlugin extends AbstractBiPhasicGroupAndEntryPlugin_1.AbstractBiPhasicGroupAndEntryPlugin {
15
15
  buildRoot;
16
16
  outputDir;
17
17
  usageLocations;
18
- handlePrefix;
19
18
  useUnifiedLoader;
20
- static semaphore = new pseduo_semaphore_1.PseudoSemaphore([], "Plain");
21
- constructor(buildRoot, outputDir, usageLocations, handlePrefix, useUnifiedLoader, context, entry) {
22
- super("plain-entrypoints-v2", [PlainEntrypointsConfigFileGeneratorPlugin.semaphore, UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore], context, entry);
19
+ static semaphore = new pseduo_semaphore_1.PseudoSemaphore("Plain");
20
+ constructor(config, buildRoot, outputDir, usageLocations, useUnifiedLoader, context, entry) {
21
+ super(config, "plain-entrypoints-v2", [PlainEntrypointsConfigFileGeneratorPlugin.semaphore, UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore], context, entry);
23
22
  this.buildRoot = buildRoot;
24
23
  this.outputDir = outputDir;
25
24
  this.usageLocations = usageLocations;
26
- this.handlePrefix = handlePrefix;
27
25
  this.useUnifiedLoader = useUnifiedLoader;
28
26
  }
29
- apply(compiler) {
30
- super.apply(compiler);
31
- compiler.hooks.compilation.tap(this.constructor.name, compilation => {
32
- compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE, additionalAssets: true }, async (assets) => {
33
- if (!("assets.json" in assets)) {
34
- return;
35
- }
36
- try {
37
- const rawAssetDataSource = assets["assets.json"]?.source();
38
- if (typeof rawAssetDataSource !== 'string') {
39
- PlainEntrypointsConfigFileGeneratorPlugin.semaphore.reject(this.id);
40
- compilation.errors.push(new Error("assets.json is unexpectedly missing or not a string"));
41
- return;
42
- }
43
- const assetDataSource = JSON.parse(rawAssetDataSource);
44
- if (!(0, shared_1.isRawAssetData)(assetDataSource)) {
45
- PlainEntrypointsConfigFileGeneratorPlugin.semaphore.reject(this.id);
46
- compilation.errors.push(new Error("assets.json is does not match the RawAssetData format"));
47
- return;
48
- }
49
- const isScriptRegex = /\.m?[jt]sx?(\?|$)/i;
50
- const myAssetHandles = [];
51
- for (const { entrypoint, srcPath } of this.getRelevantEntrypoints(compilation)) {
52
- const entrypointChunk = entrypoint.getEntrypointChunk();
53
- const assetData = entrypointChunk.files.values()
54
- .map(file => assetDataSource[file]).find(v => v !== undefined);
55
- if (!assetData) {
56
- continue;
57
- }
58
- const handles = [];
59
- const entrypointChunkIsScript = isScriptRegex.test(srcPath);
60
- const chunkFiles = entrypoint.chunks.flatMap(chunk => {
61
- return [...chunk.files].filter(file => entrypointChunkIsScript || !isScriptRegex.test(file))
62
- .map(file => [file, chunk === entrypointChunk]);
63
- });
64
- if (chunkFiles.length === 1) {
65
- chunkFiles[0][1] = true;
66
- }
67
- for (const [file, useHandleName] of chunkFiles) {
68
- const extension = node_path_1.default.extname(file).toLowerCase();
69
- const type = extension === ".js" ? 'script' : (extension === ".mjs" ? 'script_module' : 'style');
70
- const isScript = type !== 'style';
71
- const dependencies = isScript === entrypointChunkIsScript ? assetData.dependencies : [];
72
- const rest = isScript && this.usageLocations.registerScriptArgs !== undefined
73
- ? [dependencies, assetData.version, this.usageLocations.registerScriptArgs] : [dependencies, assetData.version];
74
- const destPath = node_path_1.default.join(compilation.outputOptions.path, file);
75
- handles.push({
76
- src: destPath, rest, type,
77
- locations: this.usageLocations,
78
- handleName: useHandleName ? this.usageLocations.handle : undefined,
79
- });
80
- }
81
- myAssetHandles.push({
82
- handles,
83
- handlePrefix: this.handlePrefix
84
- });
85
- }
86
- PlainEntrypointsConfigFileGeneratorPlugin.semaphore.resolve(this.id, myAssetHandles);
87
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, myAssetHandles.length
88
- ? { group: this.libraryType, requiresBaseURI: true, action: writer => writer.append("require_once __DIR__.'/plain-entrypoints-loader.php';") }
89
- : undefined);
90
- }
91
- catch (e) {
92
- PlainEntrypointsConfigFileGeneratorPlugin.semaphore.reject(this.id);
93
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.reject(this.id);
94
- throw e;
95
- }
96
- });
97
- compilation.hooks.afterProcessAssets.tap(this.constructor.name, () => {
98
- compilation.deleteAsset("assets.json");
99
- });
100
- });
101
- }
102
27
  generatePlainEntrypointsLoader(compilation, assets) {
103
28
  const emitDir = node_path_1.default.join(this.buildRoot, this.outputDir);
104
29
  const handleLists = {
@@ -233,10 +158,54 @@ class PlainEntrypointsConfigFileGeneratorPlugin extends AbstractMultiPhaseLibrar
233
158
  }
234
159
  return lists.entries().toArray().sort((a, b) => a[0] - b[0]);
235
160
  }
236
- attachSecondPhase(compilation) {
237
- compilation.hooks.processAssets.tapPromise({ name: `${this.constructor.name}_CompileLoader`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
161
+ attachUniquePhase(compilation) {
162
+ compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
238
163
  this.generatePlainEntrypointsLoader(compilation, (await PlainEntrypointsConfigFileGeneratorPlugin.semaphore.wait()).flat());
239
164
  });
240
165
  }
166
+ processAssets(compilation, assetsJson) {
167
+ const isScriptRegex = /\.m?[jt]sx?(\?|$)/i;
168
+ const myAssetHandles = [];
169
+ const relevantEntrypoints = this.getRelevantEntrypoints(compilation);
170
+ for (const { entrypoint, srcPath } of relevantEntrypoints) {
171
+ const entrypointChunk = entrypoint.getEntrypointChunk();
172
+ const assetData = entrypointChunk.files.values()
173
+ .map(file => assetsJson[file]).find(v => v !== undefined);
174
+ if (!assetData) {
175
+ continue;
176
+ }
177
+ const handles = [];
178
+ const entrypointChunkIsScript = isScriptRegex.test(srcPath);
179
+ const chunkFiles = entrypoint.chunks.flatMap(chunk => {
180
+ return [...chunk.files].filter(file => entrypointChunkIsScript || !isScriptRegex.test(file))
181
+ .map(file => [file, chunk === entrypointChunk]);
182
+ });
183
+ if (chunkFiles.length === 1) {
184
+ chunkFiles[0][1] = true;
185
+ }
186
+ for (const [file, useHandleName] of chunkFiles) {
187
+ const extension = node_path_1.default.extname(file).toLowerCase();
188
+ const type = extension === ".js" ? 'script' : (extension === ".mjs" ? 'script_module' : 'style');
189
+ const isScript = type !== 'style';
190
+ const dependencies = isScript === entrypointChunkIsScript ? assetData.dependencies : [];
191
+ const rest = isScript && this.usageLocations.registerScriptArgs !== undefined
192
+ ? [dependencies, assetData.version, this.usageLocations.registerScriptArgs] : [dependencies, assetData.version];
193
+ const destPath = node_path_1.default.join(compilation.outputOptions.path, file);
194
+ handles.push({
195
+ src: destPath, rest, type,
196
+ locations: this.usageLocations,
197
+ handleName: useHandleName ? this.usageLocations.handle : undefined,
198
+ });
199
+ }
200
+ myAssetHandles.push({ handles, handlePrefix: this.config.plainEntrypointsHandlePrefix });
201
+ }
202
+ PlainEntrypointsConfigFileGeneratorPlugin.semaphore.resolve(this.id, myAssetHandles);
203
+ UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, myAssetHandles.length
204
+ ? {
205
+ group: this.group, requiresBaseURI: true, action: writer => writer.append("require_once __DIR__.'/plain-entrypoints-loader.php';"),
206
+ staticallyLoadedEntrypoints: Object.keys(relevantEntrypoints)
207
+ }
208
+ : undefined);
209
+ }
241
210
  }
242
211
  exports.PlainEntrypointsConfigFileGeneratorPlugin = PlainEntrypointsConfigFileGeneratorPlugin;
@@ -1,15 +1,14 @@
1
- import { AbstractMultiPhaseLibraryAndEntryPlugin, EntryProvider } from "./AbstractMultiPhaseLibraryAndEntryPlugin";
2
- import { UnpackedBlockEntrypointInfo } from "../shared";
1
+ import { AbstractBiPhasicGroupAndEntryPlugin, EntryProvider } from "./AbstractBiPhasicGroupAndEntryPlugin";
2
+ import { ParsedAssetsJson, UnpackedBlockEntrypointInfo } from "../shared";
3
3
  import type { VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
4
- import { Compilation, type Compiler } from "webpack";
4
+ import { Compilation } from "webpack";
5
5
  import type WebpackRemoveEmptyScriptsPlugin from "webpack-remove-empty-scripts";
6
- export declare class PlainEntrypointsStyleBlockJSONPlugin extends AbstractMultiPhaseLibraryAndEntryPlugin<UnpackedBlockEntrypointInfo | string> {
7
- private readonly config;
6
+ export declare class PlainEntrypointsStyleBlockJSONPlugin extends AbstractBiPhasicGroupAndEntryPlugin<UnpackedBlockEntrypointInfo | string> {
8
7
  private readonly blocksDest;
9
8
  private readonly webpackRemoveEmptyScriptsPlugin;
10
9
  private static readonly semaphore;
11
10
  constructor(config: VerifiedPlauditWordpressWebpackConfig, blocksDest: string, webpackRemoveEmptyScriptsPlugin: WebpackRemoveEmptyScriptsPlugin, context: string, entry: EntryProvider<UnpackedBlockEntrypointInfo | string>);
12
- apply(compiler: Compiler): void;
11
+ protected processAssets(compilation: Compilation, rawAssetData: ParsedAssetsJson): Promise<void>;
13
12
  private emitBlockLoaderFile;
14
13
  private transformBlocks;
15
14
  private static extractAssetSource;
@@ -22,5 +21,5 @@ export declare class PlainEntrypointsStyleBlockJSONPlugin extends AbstractMultiP
22
21
  static findRelativeRouteBetween(path1: string, path2: string): string;
23
22
  private static remapReferencedPHPFilesOnKey;
24
23
  private static normalizeRenderTemplate;
25
- protected attachSecondPhase(compilation: Compilation): void;
24
+ protected attachUniquePhase(compilation: Compilation): void;
26
25
  }
@@ -7,129 +7,100 @@ exports.PlainEntrypointsStyleBlockJSONPlugin = void 0;
7
7
  const node_crypto_1 = __importDefault(require("node:crypto"));
8
8
  const node_fs_1 = __importDefault(require("node:fs"));
9
9
  const node_path_1 = __importDefault(require("node:path"));
10
- const AbstractMultiPhaseLibraryAndEntryPlugin_1 = require("./AbstractMultiPhaseLibraryAndEntryPlugin");
10
+ const AbstractBiPhasicGroupAndEntryPlugin_1 = require("./AbstractBiPhasicGroupAndEntryPlugin");
11
11
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
12
12
  const shared_1 = require("../shared");
13
13
  const php_writer_1 = require("../utils/php-writer");
14
14
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
15
15
  const webpack_1 = require("webpack");
16
16
  const promises_1 = __importDefault(require("node:fs/promises"));
17
- class PlainEntrypointsStyleBlockJSONPlugin extends AbstractMultiPhaseLibraryAndEntryPlugin_1.AbstractMultiPhaseLibraryAndEntryPlugin {
18
- config;
17
+ class PlainEntrypointsStyleBlockJSONPlugin extends AbstractBiPhasicGroupAndEntryPlugin_1.AbstractBiPhasicGroupAndEntryPlugin {
19
18
  blocksDest;
20
19
  webpackRemoveEmptyScriptsPlugin;
21
- static semaphore = new pseduo_semaphore_1.PseudoSemaphore({ collatableWorkableBlockInfo: {}, blocksDest: "", emittingWpmlXml: false }, "Block JSON v3");
20
+ static semaphore = new pseduo_semaphore_1.PseudoSemaphore("Block JSON v3");
22
21
  constructor(config, blocksDest, webpackRemoveEmptyScriptsPlugin, context, entry) {
23
- super(`block-json-${blocksDest}`, [PlainEntrypointsStyleBlockJSONPlugin.semaphore, UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore], context, entry);
24
- this.config = config;
22
+ super(config, `block-json-${blocksDest}`, [PlainEntrypointsStyleBlockJSONPlugin.semaphore, UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore], context, entry);
25
23
  this.blocksDest = blocksDest;
26
24
  this.webpackRemoveEmptyScriptsPlugin = webpackRemoveEmptyScriptsPlugin;
27
25
  }
28
- apply(compiler) {
29
- super.apply(compiler);
30
- compiler.hooks.compilation.tap(this.constructor.name, compilation => {
31
- compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE, additionalAssets: true }, async (assets) => {
32
- if (!("assets.json" in assets)) {
33
- return;
26
+ async processAssets(compilation, rawAssetData) {
27
+ const applicableBlockJsonFiles = {};
28
+ const blockJsonOriginToOutputMapping = {};
29
+ const relevantEntrypoints = this.getRelevantEntrypoints(compilation);
30
+ for (const { entrypoint, metadata, srcPath } of relevantEntrypoints) {
31
+ if (node_path_1.default.basename(srcPath).toLowerCase() !== "block.json" || metadata !== "block-json-inclusion-assurance") {
32
+ continue;
33
+ }
34
+ const entrypointChunk = entrypoint.getEntrypointChunk();
35
+ for (const danglingBlockJsFile of [...entrypointChunk.files, ...entrypointChunk.auxiliaryFiles]) {
36
+ if (!danglingBlockJsFile.endsWith("block.json")) {
37
+ compilation.deleteAsset(danglingBlockJsFile);
34
38
  }
35
- try {
36
- const rawAssetDataSource = assets["assets.json"]?.source();
37
- if (typeof rawAssetDataSource !== 'string') {
38
- PlainEntrypointsStyleBlockJSONPlugin.semaphore.reject(this.id);
39
- compilation.errors.push(new Error("assets.json is unexpectedly missing or not a string"));
40
- return;
41
- }
42
- const assetDataSource = JSON.parse(rawAssetDataSource);
43
- if (!(0, shared_1.isRawAssetData)(assetDataSource)) {
44
- PlainEntrypointsStyleBlockJSONPlugin.semaphore.reject(this.id);
45
- compilation.errors.push(new Error("assets.json is does not match the RawAssetData format"));
46
- return;
47
- }
48
- const applicableBlockJsonFiles = {};
49
- const blockJsonOriginToOutputMapping = {};
50
- const relevantEntrypoints = this.getRelevantEntrypoints(compilation);
51
- for (const { entrypoint, metadata, srcPath } of relevantEntrypoints) {
52
- if (node_path_1.default.basename(srcPath).toLowerCase() !== "block.json" || metadata !== "block-json-inclusion-assurance") {
53
- continue;
54
- }
55
- const entrypointChunk = entrypoint.getEntrypointChunk();
56
- for (const danglingBlockJsFile of [...entrypointChunk.files, ...entrypointChunk.auxiliaryFiles]) {
57
- if (!danglingBlockJsFile.endsWith("block.json")) {
58
- compilation.deleteAsset(danglingBlockJsFile);
59
- }
60
- }
61
- const asset = [...compilation.chunkGraph.getChunkEntryModulesIterable(entrypointChunk)][0]?.originalSource();
62
- if (asset) {
63
- //TODO: Can we guarantee that entrypoint.name is always non-null?
64
- const epBlockJson = entrypoint.name + ".json";
65
- if (!applicableBlockJsonFiles[epBlockJson]) {
66
- const blockJsonText = PlainEntrypointsStyleBlockJSONPlugin.extractAssetSource(compilation, epBlockJson)
67
- ?? await promises_1.default.readFile(srcPath, 'utf-8');
68
- if (!blockJsonText) {
69
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Unable to extract the source for ${epBlockJson}`, srcPath));
70
- continue;
71
- }
72
- applicableBlockJsonFiles[epBlockJson] = { sourcePath: srcPath, workableBlockEntrypointsInfo: [], blockJsonText };
73
- }
74
- blockJsonOriginToOutputMapping[srcPath] = epBlockJson;
75
- }
39
+ }
40
+ const asset = [...compilation.chunkGraph.getChunkEntryModulesIterable(entrypointChunk)][0]?.originalSource();
41
+ if (asset) {
42
+ //TODO: Can we guarantee that entrypoint.name is always non-null?
43
+ const epBlockJson = entrypoint.name + ".json";
44
+ if (!applicableBlockJsonFiles[epBlockJson]) {
45
+ const blockJsonText = PlainEntrypointsStyleBlockJSONPlugin.extractAssetSource(compilation, epBlockJson)
46
+ ?? await promises_1.default.readFile(srcPath, 'utf-8');
47
+ if (!blockJsonText) {
48
+ compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Unable to extract the source for ${epBlockJson}`, srcPath));
49
+ continue;
76
50
  }
77
- for (const { entrypoint, metadata, srcPath } of relevantEntrypoints) {
78
- if (node_path_1.default.basename(srcPath).toLowerCase() === "block.json" || typeof metadata === 'string') {
79
- continue;
80
- }
81
- const entrypointChunk = entrypoint.getEntrypointChunk();
82
- const epBlockJson = entrypointChunk.auxiliaryFiles.values().find(auxFile => node_path_1.default.basename(auxFile) === "block.json")
83
- ?? blockJsonOriginToOutputMapping[metadata.blockJsonOrigin];
84
- if (epBlockJson) {
85
- //TODO: Do we need to handle a single entrypoint potentially emitting multiple primary files?
86
- const assetData = entrypointChunk.files.values().map(file => assetDataSource[file])
87
- .find(assetData => assetData !== undefined);
88
- if (!assetData) {
89
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`assets.json did not contain information for ${srcPath}`, srcPath));
90
- continue;
91
- }
92
- const workableBlockEntrypointsInfo = entrypoint.getFiles()
93
- .map(file => this.stripOffBlocksDestPrefix(file))
94
- .filter(file => !this.webpackRemoveEmptyScriptsPlugin['trash'].includes(node_path_1.default.join(this.blocksDest, file)))
95
- .map(file => [file, (0, shared_1.scriptOrStyleTest)(file, shared_1.scriptExtension)])
96
- .filter((item) => item[1] !== '')
97
- .map(([file, assetType]) => {
98
- const wasOriginallyAStyleField = (0, shared_1.isStyleField)(metadata.entrypointField);
99
- if (wasOriginallyAStyleField !== (assetType === "style")) { // This means that the file is extracted
100
- return {
101
- ...metadata, outputPath: file, assetData, originalValue: undefined, hash: entrypointChunk.hash ?? "",
102
- entrypointField: (0, shared_1.convertEntrypointFieldForAssetType)(metadata.entrypointField, assetType)
103
- };
104
- }
105
- return ({ ...metadata, outputPath: file, assetData, hash: entrypointChunk.hash ?? "" });
106
- });
107
- if (applicableBlockJsonFiles[epBlockJson]) {
108
- applicableBlockJsonFiles[epBlockJson].workableBlockEntrypointsInfo.push(...workableBlockEntrypointsInfo);
109
- }
110
- else {
111
- applicableBlockJsonFiles[epBlockJson] = { sourcePath: workableBlockEntrypointsInfo[0]?.blockJsonOrigin, workableBlockEntrypointsInfo };
112
- }
113
- }
51
+ applicableBlockJsonFiles[epBlockJson] = { sourcePath: srcPath, workableBlockEntrypointsInfo: [], blockJsonText };
52
+ }
53
+ blockJsonOriginToOutputMapping[srcPath] = epBlockJson;
54
+ }
55
+ }
56
+ for (const { entrypoint, metadata, srcPath } of relevantEntrypoints) {
57
+ if (node_path_1.default.basename(srcPath).toLowerCase() === "block.json" || typeof metadata === 'string') {
58
+ continue;
59
+ }
60
+ const entrypointChunk = entrypoint.getEntrypointChunk();
61
+ const epBlockJson = entrypointChunk.auxiliaryFiles.values().find(auxFile => node_path_1.default.basename(auxFile) === "block.json")
62
+ ?? blockJsonOriginToOutputMapping[metadata.blockJsonOrigin];
63
+ if (epBlockJson) {
64
+ //TODO: Do we need to handle a single entrypoint potentially emitting multiple primary files?
65
+ const assetData = entrypointChunk.files.values().map(file => rawAssetData[file])
66
+ .find(assetData => assetData !== undefined);
67
+ if (!assetData) {
68
+ compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`assets.json did not contain information for ${srcPath}`, srcPath));
69
+ continue;
70
+ }
71
+ const workableBlockEntrypointsInfo = entrypoint.getFiles()
72
+ .map(file => this.stripOffBlocksDestPrefix(file))
73
+ .filter(file => !this.webpackRemoveEmptyScriptsPlugin['trash'].includes(node_path_1.default.join(this.blocksDest, file)))
74
+ .map(file => [file, (0, shared_1.scriptOrStyleTest)(file, shared_1.scriptExtension)])
75
+ .filter((item) => item[1] !== '')
76
+ .map(([file, assetType]) => {
77
+ const wasOriginallyAStyleField = (0, shared_1.isStyleField)(metadata.entrypointField);
78
+ if (wasOriginallyAStyleField !== (assetType === "style")) { // This means that the file is extracted
79
+ return {
80
+ ...metadata, outputPath: file, assetData, originalValue: undefined, hash: entrypointChunk.hash ?? "",
81
+ entrypointField: (0, shared_1.convertEntrypointFieldForAssetType)(metadata.entrypointField, assetType)
82
+ };
114
83
  }
115
- compilation.deleteAsset("assets.json");
116
- PlainEntrypointsStyleBlockJSONPlugin.semaphore.resolve(this.id, {
117
- collatableWorkableBlockInfo: applicableBlockJsonFiles, blocksDest: this.blocksDest,
118
- emittingWpmlXml: compilation.getAsset(node_path_1.default.join(this.blocksDest, "wpml-config.xml")) !== undefined
119
- });
120
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, Object.keys(applicableBlockJsonFiles).length ? {
121
- group: this.libraryType,
122
- requiresBaseURI: false,
123
- action: writer => writer.append(`require_once __DIR__.${php_writer_1.Expr.convertJsonToPHP("/" + node_path_1.default.join(this.blocksDest, "blockdir-loader.php"))};`)
124
- } : undefined);
84
+ return ({ ...metadata, outputPath: file, assetData, hash: entrypointChunk.hash ?? "" });
85
+ });
86
+ if (applicableBlockJsonFiles[epBlockJson]) {
87
+ applicableBlockJsonFiles[epBlockJson].workableBlockEntrypointsInfo.push(...workableBlockEntrypointsInfo);
125
88
  }
126
- catch (e) {
127
- PlainEntrypointsStyleBlockJSONPlugin.semaphore.reject(this.id);
128
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.reject(this.id);
129
- throw e;
89
+ else {
90
+ applicableBlockJsonFiles[epBlockJson] = { sourcePath: workableBlockEntrypointsInfo[0]?.blockJsonOrigin, workableBlockEntrypointsInfo };
130
91
  }
131
- });
92
+ }
93
+ }
94
+ PlainEntrypointsStyleBlockJSONPlugin.semaphore.resolve(this.id, {
95
+ collatableWorkableBlockInfo: applicableBlockJsonFiles, blocksDest: this.blocksDest,
96
+ emittingWpmlXml: compilation.getAsset(node_path_1.default.join(this.blocksDest, "wpml-config.xml")) !== undefined
132
97
  });
98
+ UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, Object.keys(applicableBlockJsonFiles).length ? {
99
+ group: this.group,
100
+ requiresBaseURI: false,
101
+ staticallyLoadedEntrypoints: Object.keys(relevantEntrypoints),
102
+ action: writer => writer.append(`require_once __DIR__.${php_writer_1.Expr.convertJsonToPHP("/" + node_path_1.default.join(this.blocksDest, "blockdir-loader.php"))};`)
103
+ } : undefined);
133
104
  }
134
105
  emitBlockLoaderFile(compilation, blockData) {
135
106
  if (this.config.useUnifiedLoader) {
@@ -166,7 +137,6 @@ class PlainEntrypointsStyleBlockJSONPlugin extends AbstractMultiPhaseLibraryAndE
166
137
  const pathsNeedRemapping = !this.config.standaloneBlocks && blockJson["plaudit"] !== "simple";
167
138
  PlainEntrypointsStyleBlockJSONPlugin.remapReferencedPHPFilesOnKey(blockJson, "setup", pathsNeedRemapping, sourceDir, outputDir, compilation, true);
168
139
  PlainEntrypointsStyleBlockJSONPlugin.remapReferencedPHPFilesOnKey(blockJson, "variations", pathsNeedRemapping, sourceDir, outputDir, compilation, false);
169
- PlainEntrypointsStyleBlockJSONPlugin.normalizeRenderTemplate(blockJson, pathsNeedRemapping, sourceDir, outputDir, compilation);
170
140
  const hashForVersion = PlainEntrypointsStyleBlockJSONPlugin
171
141
  .hashThingForAsset([blockJsonText, ...workableBlockEntrypointsInfo.map(bi => bi.hash)].join("~"));
172
142
  if (blockJson["version"]) {
@@ -175,6 +145,7 @@ class PlainEntrypointsStyleBlockJSONPlugin extends AbstractMultiPhaseLibraryAndE
175
145
  else {
176
146
  blockJson["version"] = hashForVersion;
177
147
  }
148
+ PlainEntrypointsStyleBlockJSONPlugin.normalizeRenderTemplate(blockJson, pathsNeedRemapping, sourceDir, outputDir, compilation);
178
149
  const blockDirName = node_path_1.default.dirname(node_path_1.default.relative(this.blocksDest, blockJsonAssetName));
179
150
  blockData[blockDirName] = PlainEntrypointsStyleBlockJSONPlugin
180
151
  .doFileOrHandleReplacements(compilation, Object.fromEntries(Object.entries(blockJson).filter(([k]) => k !== '$schema')), workableBlockEntrypointsInfo, epi => epi.handle);
@@ -373,7 +344,7 @@ class PlainEntrypointsStyleBlockJSONPlugin extends AbstractMultiPhaseLibraryAndE
373
344
  }
374
345
  }
375
346
  }
376
- attachSecondPhase(compilation) {
347
+ attachUniquePhase(compilation) {
377
348
  compilation.hooks.processAssets.tapPromise({ name: `${this.constructor.name}_CompileLoader`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
378
349
  const allSemaphoreData = (await PlainEntrypointsStyleBlockJSONPlugin.semaphore.wait())
379
350
  .reduce((acc, cur) => {
@@ -1,12 +1,11 @@
1
1
  import type { VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
2
- import { AbstractMultiPhaseLibraryPlugin } from "./AbstractMultiPhaseLibraryPlugin";
3
- import { Compilation, type Compiler } from "webpack";
4
- export declare class SpecialAssetHandlingPlugin extends AbstractMultiPhaseLibraryPlugin {
5
- private readonly config;
2
+ import { AbstractBiPhasicGroupPlugin } from "./AbstractBiPhasicGroupPlugin";
3
+ import { Compilation } from "webpack";
4
+ export declare class SpecialAssetHandlingPlugin extends AbstractBiPhasicGroupPlugin {
6
5
  private static readonly semaphore;
7
6
  private static validPathname?;
8
7
  constructor(config: VerifiedPlauditWordpressWebpackConfig);
9
- apply(compiler: Compiler): void;
8
+ protected attachStandardPhase(compilation: Compilation): void;
10
9
  private collateAssets;
11
- protected attachSecondPhase(compilation: Compilation): void;
10
+ protected attachUniquePhase(compilation: Compilation): void;
12
11
  }