@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
@@ -0,0 +1,22 @@
1
+ import { ParsedAssetsJson } from "../shared";
2
+ import type { ExtensibleEntryObject, VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
3
+ import { PseudoSemaphore } from "../utils/pseduo-semaphore";
4
+ import { AbstractBiPhasicGroupPlugin } from "./AbstractBiPhasicGroupPlugin";
5
+ import { Compilation, Compiler, Entrypoint } from "webpack";
6
+ export type EntryProvider<M> = () => ExtensibleEntryObject<M> | Promise<ExtensibleEntryObject<M>>;
7
+ export declare abstract class AbstractBiPhasicGroupAndEntryPlugin<M> extends AbstractBiPhasicGroupPlugin {
8
+ private readonly context;
9
+ private readonly entry;
10
+ private static readonly configuredCompilations;
11
+ private readonly entryMetadataRecord;
12
+ protected constructor(config: VerifiedPlauditWordpressWebpackConfig, group: string, semaphores: PseudoSemaphore<any>[], context: string, entry: EntryProvider<M>);
13
+ apply(compiler: Compiler): void;
14
+ protected attachStandardPhase(compilation: Compilation): void;
15
+ getRelevantEntrypoints(compilation: Compilation): {
16
+ entrypoint: Entrypoint;
17
+ srcPath: string;
18
+ metadata: M;
19
+ }[];
20
+ protected abstract processAssets(compilation: Compilation, parsedAssetsJson: ParsedAssetsJson): Promise<void> | void;
21
+ protected extractRelevantAssetData(compilation: Compilation, parsedAssetsJson: ParsedAssetsJson): ParsedAssetsJson;
22
+ }
@@ -1,22 +1,27 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AbstractMultiPhaseLibraryAndEntryPlugin = void 0;
4
- const AbstractMultiPhaseLibraryPlugin_1 = require("./AbstractMultiPhaseLibraryPlugin");
3
+ exports.AbstractBiPhasicGroupAndEntryPlugin = void 0;
4
+ const shared_1 = require("../shared");
5
+ const AbstractBiPhasicGroupPlugin_1 = require("./AbstractBiPhasicGroupPlugin");
5
6
  const webpack_1 = require("webpack");
6
- class AbstractMultiPhaseLibraryAndEntryPlugin extends AbstractMultiPhaseLibraryPlugin_1.AbstractMultiPhaseLibraryPlugin {
7
+ class AbstractBiPhasicGroupAndEntryPlugin extends AbstractBiPhasicGroupPlugin_1.AbstractBiPhasicGroupPlugin {
7
8
  context;
8
9
  entry;
10
+ static configuredCompilations = new WeakSet();
9
11
  entryMetadataRecord = {};
10
- constructor(libraryType, semaphores, context, entry) {
11
- super(libraryType, semaphores);
12
+ constructor(config, group, semaphores, context, entry) {
13
+ super(config, group, semaphores);
12
14
  this.context = context;
13
15
  this.entry = entry;
14
16
  }
15
17
  apply(compiler) {
16
18
  super.apply(compiler);
17
19
  compiler.hooks.compilation.tap(this.constructor.name, (compilation, { normalModuleFactory }) => {
18
- const dummyEntry = webpack_1.EntryPlugin.createDependency("", "");
19
- compilation.dependencyFactories.set(dummyEntry.constructor, normalModuleFactory);
20
+ if (!AbstractBiPhasicGroupAndEntryPlugin.configuredCompilations.has(compilation)) {
21
+ AbstractBiPhasicGroupAndEntryPlugin.configuredCompilations.add(compilation);
22
+ const dummyEntry = webpack_1.EntryPlugin.createDependency("", "");
23
+ compilation.dependencyFactories.set(dummyEntry.constructor, normalModuleFactory);
24
+ }
20
25
  });
21
26
  compiler.hooks.make.tapPromise(this.constructor.name, async (compilation) => {
22
27
  const entry = await this.entry();
@@ -38,6 +43,11 @@ class AbstractMultiPhaseLibraryAndEntryPlugin extends AbstractMultiPhaseLibraryP
38
43
  await Promise.all(promises);
39
44
  });
40
45
  }
46
+ attachStandardPhase(compilation) {
47
+ this.tapWithParsedAssetsJson(compilation, async (parsedAssetsJson) => {
48
+ await this.processAssets(compilation, parsedAssetsJson);
49
+ });
50
+ }
41
51
  getRelevantEntrypoints(compilation) {
42
52
  return compilation.entrypoints.values()
43
53
  .map(entrypoint => {
@@ -58,5 +68,18 @@ class AbstractMultiPhaseLibraryAndEntryPlugin extends AbstractMultiPhaseLibraryP
58
68
  .filter(item => item !== undefined)
59
69
  .toArray();
60
70
  }
71
+ extractRelevantAssetData(compilation, parsedAssetsJson) {
72
+ const relevantAssetData = {};
73
+ const relevantEntrypoints = this.getRelevantEntrypoints(compilation);
74
+ for (const { entrypoint, srcPath } of relevantEntrypoints) {
75
+ const fileWithAssetData = entrypoint.getEntrypointChunk().files.values().find(file => parsedAssetsJson[file]);
76
+ if (!fileWithAssetData) {
77
+ compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`assets.json did not contain information for ${srcPath}`, srcPath));
78
+ continue;
79
+ }
80
+ relevantAssetData[fileWithAssetData] = parsedAssetsJson[fileWithAssetData];
81
+ }
82
+ return relevantAssetData;
83
+ }
61
84
  }
62
- exports.AbstractMultiPhaseLibraryAndEntryPlugin = AbstractMultiPhaseLibraryAndEntryPlugin;
85
+ exports.AbstractBiPhasicGroupAndEntryPlugin = AbstractBiPhasicGroupAndEntryPlugin;
@@ -0,0 +1,33 @@
1
+ import { Compilation, Compiler, type WebpackPluginInstance } from "webpack";
2
+ import { PseudoSemaphore } from "../utils/pseduo-semaphore";
3
+ import type { VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
4
+ import { ParsedAssetsJson } from "../shared";
5
+ type TapWithAssetsJsonOptions = {
6
+ name?: string;
7
+ stage?: (typeof Compilation.PROCESS_ASSETS_STAGE_REPORT) | (typeof Compilation.PROCESS_ASSETS_STAGE_ANALYSE);
8
+ additionalAssets?: any;
9
+ };
10
+ type TapWithAssetsJsonFn = Parameters<Compilation['hooks']['processAssets']['tapPromise']>[1];
11
+ type TapWithParsedAssetsJsonFn = (parsedAssetsJson: ParsedAssetsJson, assets: Parameters<TapWithAssetsJsonFn>[0]) => Promise<void> | void;
12
+ export declare abstract class AbstractBiPhasicGroupPlugin implements WebpackPluginInstance {
13
+ protected readonly config: VerifiedPlauditWordpressWebpackConfig;
14
+ readonly group: string;
15
+ private readonly semaphores;
16
+ protected static readonly uniquePhaseAttached: {
17
+ [key in string]: any;
18
+ };
19
+ protected readonly id: string;
20
+ protected constructor(config: VerifiedPlauditWordpressWebpackConfig, group: string, semaphores: PseudoSemaphore<any>[]);
21
+ apply(compiler: Compiler): void;
22
+ protected resetSemaphores(): void;
23
+ protected rejectSemaphores(): void;
24
+ protected abstract attachStandardPhase(compilation: Compilation): void;
25
+ protected abstract attachUniquePhase(compilation: Compilation): void;
26
+ protected tapRequiringAssetsJson(compilation: Compilation, fnOrOptions: TapWithAssetsJsonFn): void;
27
+ protected tapRequiringAssetsJson(compilation: Compilation, fnOrOptions: TapWithAssetsJsonOptions, fnIfOptions: TapWithAssetsJsonFn): void;
28
+ protected tapWithParsedAssetsJson(compilation: Compilation, fnOrOptions: TapWithParsedAssetsJsonFn): void;
29
+ protected tapWithParsedAssetsJson(compilation: Compilation, fnOrOptions: TapWithAssetsJsonOptions, fnIfOptions: TapWithParsedAssetsJsonFn): void;
30
+ private sharedTapLogicForAssetsJsonHelpers;
31
+ private extractTapAndFunction;
32
+ }
33
+ export {};
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AbstractBiPhasicGroupPlugin = void 0;
4
+ const webpack_1 = require("webpack");
5
+ const shared_1 = require("../shared");
6
+ class AbstractBiPhasicGroupPlugin {
7
+ config;
8
+ group;
9
+ semaphores;
10
+ static uniquePhaseAttached = {};
11
+ id;
12
+ constructor(config, group, semaphores) {
13
+ this.config = config;
14
+ this.group = group;
15
+ this.semaphores = semaphores;
16
+ this.id = Math.random().toString();
17
+ }
18
+ apply(compiler) {
19
+ webpack_1.library.EnableLibraryPlugin.setEnabled(compiler, this.group);
20
+ for (const semaphore of this.semaphores) {
21
+ semaphore.register(this.id);
22
+ }
23
+ compiler.hooks.compilation.tap(this.constructor.name, compilation => {
24
+ AbstractBiPhasicGroupPlugin.uniquePhaseAttached[this.group] = false;
25
+ this.resetSemaphores();
26
+ compilation.hooks.beforeChunkIds.tap(this.constructor.name, () => {
27
+ if (!AbstractBiPhasicGroupPlugin.uniquePhaseAttached[this.group]) {
28
+ AbstractBiPhasicGroupPlugin.uniquePhaseAttached[this.group] = this;
29
+ this.attachUniquePhase(compilation);
30
+ }
31
+ });
32
+ this.attachStandardPhase(compilation);
33
+ });
34
+ }
35
+ resetSemaphores() {
36
+ for (const semaphore of this.semaphores) {
37
+ semaphore.reset(this.id);
38
+ }
39
+ }
40
+ rejectSemaphores() {
41
+ for (const semaphore of this.semaphores) {
42
+ semaphore.reject(this.id);
43
+ }
44
+ }
45
+ tapRequiringAssetsJson(compilation, fnOrOptions, fnIfOptions) {
46
+ this.sharedTapLogicForAssetsJsonHelpers(compilation, this.extractTapAndFunction(fnOrOptions, fnIfOptions));
47
+ }
48
+ tapWithParsedAssetsJson(compilation, fnOrOptions, fnIfOptions) {
49
+ const { tap, earlyStage, fn } = this.extractTapAndFunction(fnOrOptions, fnIfOptions);
50
+ this.sharedTapLogicForAssetsJsonHelpers(compilation, { tap, earlyStage, fn: async (assets) => {
51
+ try {
52
+ await fn((0, shared_1.getAssetsJson)(compilation), assets);
53
+ }
54
+ catch (e) {
55
+ console.error(e);
56
+ this.rejectSemaphores();
57
+ if (e instanceof Error) {
58
+ compilation.errors.push(e);
59
+ }
60
+ else {
61
+ throw e;
62
+ }
63
+ }
64
+ } });
65
+ }
66
+ sharedTapLogicForAssetsJsonHelpers(compilation, { tap, earlyStage, fn }) {
67
+ compilation.hooks.processAssets.tapPromise({ ...tap, additionalAssets: true }, async (assets, ...args) => {
68
+ if (!earlyStage || "assets.json" in assets) {
69
+ await fn(assets, ...args);
70
+ }
71
+ });
72
+ }
73
+ extractTapAndFunction(fnOrOptions, fnIfOptions) {
74
+ let tap = { name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE };
75
+ let fn;
76
+ if (typeof fnOrOptions === 'function') {
77
+ fn = fnOrOptions;
78
+ }
79
+ else if (!fnIfOptions) {
80
+ throw new Error("Somehow reached an impossible state. Make sure that you're using TypeScript.");
81
+ }
82
+ else {
83
+ tap = { ...tap, ...fnOrOptions };
84
+ fn = fnIfOptions;
85
+ }
86
+ const earlyStage = tap.stage === webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE;
87
+ if (earlyStage && tap.additionalAssets === undefined) {
88
+ tap.additionalAssets = true;
89
+ }
90
+ return { tap, earlyStage, fn };
91
+ }
92
+ }
93
+ exports.AbstractBiPhasicGroupPlugin = AbstractBiPhasicGroupPlugin;
@@ -1,8 +1,10 @@
1
1
  import { type Compiler, type WebpackPluginInstance } from "webpack";
2
+ import { AbstractBiPhasicGroupAndEntryPlugin } from "./AbstractBiPhasicGroupAndEntryPlugin";
2
3
  export declare class AdditionalDependencyInjectorPlugin implements WebpackPluginInstance {
3
4
  private readonly entrypointAdditionalDependencies;
4
5
  private readonly processingModules;
5
6
  private readonly addExternalizedDep;
6
- constructor(entrypointAdditionalDependencies: string[], processingModules: boolean, addExternalizedDep: (dep: string) => void);
7
+ private readonly referencePlugin;
8
+ constructor(entrypointAdditionalDependencies: string[], processingModules: boolean, addExternalizedDep: (dep: string) => void, referencePlugin: AbstractBiPhasicGroupAndEntryPlugin<any>);
7
9
  apply(compiler: Compiler): void;
8
10
  }
@@ -10,10 +10,12 @@ class AdditionalDependencyInjectorPlugin {
10
10
  entrypointAdditionalDependencies;
11
11
  processingModules;
12
12
  addExternalizedDep;
13
- constructor(entrypointAdditionalDependencies, processingModules, addExternalizedDep) {
13
+ referencePlugin;
14
+ constructor(entrypointAdditionalDependencies, processingModules, addExternalizedDep, referencePlugin) {
14
15
  this.entrypointAdditionalDependencies = entrypointAdditionalDependencies;
15
16
  this.processingModules = processingModules;
16
17
  this.addExternalizedDep = addExternalizedDep;
18
+ this.referencePlugin = referencePlugin;
17
19
  }
18
20
  apply(compiler) {
19
21
  compiler.hooks.thisCompilation.tap(this.constructor.name, compilation => {
@@ -22,7 +24,7 @@ class AdditionalDependencyInjectorPlugin {
22
24
  stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
23
25
  }, () => {
24
26
  const usableEntrypointTest = this.processingModules ? /\.m[jt]sx?$/i : /\.[jt]sx?$/i;
25
- for (const entrypoint of compilation.entrypoints.values()) {
27
+ for (const { entrypoint } of this.referencePlugin.getRelevantEntrypoints(compilation)) {
26
28
  const req = entrypoint.origins.filter(origin => usableEntrypointTest.test(origin.request))[0]?.request;
27
29
  if (!req) {
28
30
  continue;
@@ -43,7 +45,7 @@ class AdditionalDependencyInjectorPlugin {
43
45
  name: `${this.constructor.name}_ProcessAssets_RemoveFakeModules`,
44
46
  stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT
45
47
  }, () => {
46
- for (const entrypoint of compilation.entrypoints.values()) {
48
+ for (const { entrypoint } of this.referencePlugin.getRelevantEntrypoints(compilation)) {
47
49
  const entrypointChunk = entrypoint.getEntrypointChunk();
48
50
  for (const module of compilation.chunkGraph.getChunkModules(entrypointChunk)) {
49
51
  if (module instanceof webpack_1.ExternalModule && module.request === '__REMOVE_ME__') {
@@ -0,0 +1,8 @@
1
+ import { AbstractBiPhasicGroupAndEntryPlugin, EntryProvider } from "./AbstractBiPhasicGroupAndEntryPlugin";
2
+ import type { UnpackedBlockEntrypointInfo } from "../shared";
3
+ import type { VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
4
+ export declare class EnhancedDynamicEntryPlugin extends AbstractBiPhasicGroupAndEntryPlugin<UnpackedBlockEntrypointInfo | string> {
5
+ constructor(config: VerifiedPlauditWordpressWebpackConfig, context: string, entry: EntryProvider<UnpackedBlockEntrypointInfo | string>);
6
+ protected attachUniquePhase(): void;
7
+ protected processAssets(): void;
8
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EnhancedDynamicEntryPlugin = void 0;
4
+ const AbstractBiPhasicGroupAndEntryPlugin_1 = require("./AbstractBiPhasicGroupAndEntryPlugin");
5
+ class EnhancedDynamicEntryPlugin extends AbstractBiPhasicGroupAndEntryPlugin_1.AbstractBiPhasicGroupAndEntryPlugin {
6
+ constructor(config, context, entry) {
7
+ super(config, `enhanced-dynamic-entries`, [], context, entry);
8
+ }
9
+ attachUniquePhase() { }
10
+ processAssets() { }
11
+ }
12
+ exports.EnhancedDynamicEntryPlugin = EnhancedDynamicEntryPlugin;
@@ -1,15 +1,16 @@
1
- import { AbstractMultiPhaseLibraryAndEntryPlugin, EntryProvider } from "./AbstractMultiPhaseLibraryAndEntryPlugin";
2
- import { UnpackedBlockEntrypointInfo, VerifiedAdvancedOutputConfig } from "../shared";
1
+ import { AbstractBiPhasicGroupAndEntryPlugin, EntryProvider } from "./AbstractBiPhasicGroupAndEntryPlugin";
2
+ import { ParsedAssetsJson, VerifiedAdvancedOutputConfig } from "../shared";
3
3
  import type { VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
4
4
  import { Compilation, type Compiler } from "webpack";
5
- export declare class ExtensionsConfigFileGeneratorPlugin extends AbstractMultiPhaseLibraryAndEntryPlugin<UnpackedBlockEntrypointInfo | string> {
6
- private readonly config;
7
- private readonly extensionsPath;
5
+ export declare class ExtensionsConfigFileGeneratorPlugin extends AbstractBiPhasicGroupAndEntryPlugin<string> {
6
+ private readonly extensionsSrcPath;
8
7
  private readonly dest;
9
8
  private static readonly semaphore;
10
- private static readonly perLibraryTypeSetupFilePaths;
11
- constructor(config: VerifiedPlauditWordpressWebpackConfig, extensionsPath: string, dest: VerifiedAdvancedOutputConfig, context: string, entry: EntryProvider<UnpackedBlockEntrypointInfo | string>);
9
+ private setupFiles;
10
+ constructor(config: VerifiedPlauditWordpressWebpackConfig, extensionsSrcPath: string, dest: VerifiedAdvancedOutputConfig, context: string, entry: EntryProvider<string>);
11
+ get extensionsDestPath(): string;
12
12
  apply(compiler: Compiler): void;
13
13
  private generateVersionTwoConfigFile;
14
- protected attachSecondPhase(compilation: Compilation): void;
14
+ protected attachUniquePhase(compilation: Compilation): void;
15
+ protected processAssets(compilation: Compilation, rawAssetData: ParsedAssetsJson): void;
15
16
  }
@@ -6,34 +6,36 @@ 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 AbstractMultiPhaseLibraryAndEntryPlugin_1 = require("./AbstractMultiPhaseLibraryAndEntryPlugin");
9
+ const AbstractBiPhasicGroupAndEntryPlugin_1 = require("./AbstractBiPhasicGroupAndEntryPlugin");
10
10
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
11
11
  const shared_1 = require("../shared");
12
12
  const php_writer_1 = require("../utils/php-writer");
13
13
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
14
14
  const webpack_1 = require("webpack");
15
- class ExtensionsConfigFileGeneratorPlugin extends AbstractMultiPhaseLibraryAndEntryPlugin_1.AbstractMultiPhaseLibraryAndEntryPlugin {
16
- config;
17
- extensionsPath;
15
+ class ExtensionsConfigFileGeneratorPlugin extends AbstractBiPhasicGroupAndEntryPlugin_1.AbstractBiPhasicGroupAndEntryPlugin {
16
+ extensionsSrcPath;
18
17
  dest;
19
- static semaphore = new pseduo_semaphore_1.PseudoSemaphore({ libraryType: "", assets: [], setupFiles: [] }, "Extensions");
20
- static perLibraryTypeSetupFilePaths = {};
21
- constructor(config, extensionsPath, dest, context, entry) {
22
- super(`extensions-v2-${dest.destination}`, [ExtensionsConfigFileGeneratorPlugin.semaphore, UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore], context, entry);
23
- this.config = config;
24
- this.extensionsPath = extensionsPath;
18
+ static semaphore = new pseduo_semaphore_1.PseudoSemaphore("Extensions");
19
+ setupFiles = [];
20
+ constructor(config, extensionsSrcPath, dest, context, entry) {
21
+ super(config, `extensions-v2-${dest.destination}`, [ExtensionsConfigFileGeneratorPlugin.semaphore, UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore], context, entry);
22
+ this.extensionsSrcPath = extensionsSrcPath;
25
23
  this.dest = dest;
26
24
  }
25
+ get extensionsDestPath() {
26
+ let extensionsDestPath = this.dest.destination.endsWith("/") ? this.dest.destination : this.dest.destination + "/";
27
+ return !extensionsDestPath.startsWith("/") ? "/" + extensionsDestPath : extensionsDestPath;
28
+ }
27
29
  apply(compiler) {
28
30
  super.apply(compiler);
29
31
  compiler.hooks.make.tapPromise(this.constructor.name, async (compilation) => {
30
- if (!compilation.contextDependencies.has(this.extensionsPath)) {
31
- compilation.contextDependencies.add(this.extensionsPath);
32
+ if (!compilation.contextDependencies.has(this.extensionsSrcPath)) {
33
+ compilation.contextDependencies.add(this.extensionsSrcPath);
32
34
  }
33
35
  const emissionPromises = [];
34
- for await (const { name: setupFilePath } of await promises_1.default.opendir(this.extensionsPath, { encoding: 'utf-8' })) {
36
+ for await (const { name: setupFilePath } of await promises_1.default.opendir(this.extensionsSrcPath, { encoding: 'utf-8' })) {
35
37
  if (setupFilePath.endsWith("-setup.php")) {
36
- const setupFileSourcePath = node_path_1.default.join(this.extensionsPath, setupFilePath);
38
+ const setupFileSourcePath = node_path_1.default.join(this.extensionsSrcPath, setupFilePath);
37
39
  compilation.fileDependencies.add(setupFileSourcePath);
38
40
  emissionPromises.push(promises_1.default.readFile(setupFileSourcePath).then(contents => {
39
41
  compilation.emitAsset(node_path_1.default.join(this.dest.destination, setupFilePath), new webpack_1.sources.RawSource(contents), { size: Buffer.byteLength(contents) });
@@ -42,134 +44,45 @@ class ExtensionsConfigFileGeneratorPlugin extends AbstractMultiPhaseLibraryAndEn
42
44
  }));
43
45
  }
44
46
  }
45
- ExtensionsConfigFileGeneratorPlugin.perLibraryTypeSetupFilePaths[this.libraryType] = (await Promise.all(emissionPromises))
47
+ this.setupFiles = (await Promise.all(emissionPromises))
46
48
  .filter((item) => item[0] !== undefined).sort((a, b) => a[0].localeCompare(b[0]));
47
49
  });
48
- compiler.hooks.compilation.tap(this.constructor.name, compilation => {
49
- compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE, additionalAssets: true }, async (assets) => {
50
- if (!("assets.json" in assets)) {
51
- return;
52
- }
53
- try {
54
- //TODO: It should be possible to use EntryPoints to determine the "original" file
55
- //TODO: There is no reason to not use basically the exact same logic to implement support for this in plain file contexts
56
- const myCacheData = { libraryType: this.libraryType, assets: [],
57
- setupFiles: ExtensionsConfigFileGeneratorPlugin.perLibraryTypeSetupFilePaths[this.libraryType] ?? [] };
58
- const rawAssetDataSource = assets["assets.json"]?.source();
59
- if (typeof rawAssetDataSource !== 'string') {
60
- ExtensionsConfigFileGeneratorPlugin.semaphore.reject(this.id);
61
- compilation.errors.push(new Error("assets.json is unexpectedly missing or not a string"));
62
- return;
63
- }
64
- const assetDataSource = JSON.parse(rawAssetDataSource);
65
- if (!(0, shared_1.isRawAssetData)(assetDataSource)) {
66
- ExtensionsConfigFileGeneratorPlugin.semaphore.reject(this.id);
67
- compilation.errors.push(new Error("assets.json is does not match the RawAssetData format"));
68
- return;
69
- }
70
- const relevantAssetData = {};
71
- const relevantEntrypoints = this.getRelevantEntrypoints(compilation);
72
- for (const { entrypoint, srcPath } of relevantEntrypoints) {
73
- const fileWithAssetData = entrypoint.getEntrypointChunk().files.values().find(file => assetDataSource[file]);
74
- if (!fileWithAssetData) {
75
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`assets.json did not contain information for ${srcPath}`, srcPath));
76
- continue;
77
- }
78
- relevantAssetData[fileWithAssetData] = assetDataSource[fileWithAssetData];
79
- }
80
- myCacheData.assets.push(relevantAssetData);
81
- compilation.deleteAsset("assets.json");
82
- ExtensionsConfigFileGeneratorPlugin.semaphore.resolve(this.id, myCacheData);
83
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, myCacheData.setupFiles.length > 0 || myCacheData.assets.length > 0 ? {
84
- group: this.libraryType,
85
- requiresBaseURI: true,
86
- action: writer => {
87
- const generateLoader = (writer) => {
88
- let finalExtensionsDest = this.dest.destination.endsWith("/") ? this.dest.destination : this.dest.destination + "/";
89
- if (!finalExtensionsDest.startsWith("/")) {
90
- finalExtensionsDest = "/" + finalExtensionsDest;
91
- }
92
- const filePathPrefixVar = new php_writer_1.Var("filePathPrefix");
93
- const fileUriPrefixVar = new php_writer_1.Var("fileUriPrefix");
94
- writer
95
- .assign(filePathPrefixVar, new php_writer_1.Literal(`__DIR__.${php_writer_1.Expr.convertJsonToPHP(finalExtensionsDest)}`))
96
- .call("plaudit_webpack_extensions__resolve_base_uri", [filePathPrefixVar], { assignTo: fileUriPrefixVar })
97
- .call("GutenbergUtils::loadExtensionsV2", [
98
- new php_writer_1.Literal(`__DIR__.${php_writer_1.Expr.convertJsonToPHP(finalExtensionsDest + "mapping.config.php")}`),
99
- filePathPrefixVar, fileUriPrefixVar,
100
- `${this.config.plainEntrypointsHandlePrefix || node_path_1.default.basename(process.cwd())}_extension_`
101
- ]);
102
- };
103
- writer.use("Plaudit\\Common\\Lib\\GutenbergUtils");
104
- const potentialHandle = this.dest.locations?.handle;
105
- if (potentialHandle) {
106
- if (typeof potentialHandle === 'string') {
107
- try {
108
- //TODO: Generate a function
109
- writer.function(potentialHandle, [], generateLoader, { returnType: 'void' });
110
- return;
111
- }
112
- catch (e) {
113
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(["An error occurred while emitting a function for dynamically loading extensions", { cause: e }], this.extensionsPath));
114
- }
115
- }
116
- else {
117
- compilation.errors.push(new Error("The extensions directoryLayout's handle support is limited to static strings"));
118
- }
119
- }
120
- writer.withScope(generateLoader);
121
- }
122
- } : undefined);
123
- }
124
- catch (e) {
125
- ExtensionsConfigFileGeneratorPlugin.semaphore.reject(this.id);
126
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.reject(this.id);
127
- if (e instanceof Error) {
128
- compilation.errors.push(e);
129
- return;
130
- }
131
- throw e;
132
- }
133
- });
134
- });
135
50
  }
136
- generateVersionTwoConfigFile(compilation, combinedExtensionData) {
51
+ generateVersionTwoConfigFile(compilation, relevantAssetData, setupFilePaths) {
137
52
  const regex = /^(.+?)-((?:editor-|view-|)(?:style|script|script-module))\.(?:css|m?js)$/i;
138
53
  const blockExtensionsConfig = {
139
54
  metadata: { version: this.config.extensionsVersion }, scriptHandles: {}, scriptModuleHandles: {}, styleHandles: {}, blocks: {}, setupFiles: {}
140
55
  };
141
- for (const assetDataSource of combinedExtensionData.assets) {
142
- const normalizedAssetData = Object.entries(assetDataSource)
143
- .map(entry => {
144
- const assetPath = this.dest.destination && entry[0].startsWith(this.dest.destination + "/")
145
- ? entry[0].substring(this.dest.destination.length + 1) : entry[0];
146
- return [assetPath, entry[1]];
147
- });
148
- for (const [assetPath, assetData] of normalizedAssetData) {
149
- const match = regex.exec(assetPath);
150
- if (!match) {
151
- continue;
152
- }
153
- const blockSlug = match[1], assetType = match[2];
154
- if (blockSlug && assetType) {
155
- const key = assetType.replace(/-[sm]/gi, chars => chars.substring(1).toUpperCase());
156
- const handle = `plaudit_block-extension_${blockSlug}-${assetType}`;
157
- const isCss = (0, shared_1.isStyleField)(assetType);
158
- const handleGroup = isCss ? 'styleHandles'
159
- : ((0, shared_1.isScriptModuleField)(assetType) ? 'scriptModuleHandles' : 'scriptHandles');
160
- blockExtensionsConfig[handleGroup][handle] = {
161
- src: isCss ? assetPath.replace(/\.js$/, ".css") : assetPath,
162
- rest: isCss || key.startsWith("editor")
163
- ? [assetData.dependencies, assetData.version]
164
- : [assetData.dependencies, assetData.version, { strategy: 'defer' }]
165
- };
166
- (blockExtensionsConfig.blocks[blockSlug] ?? (blockExtensionsConfig.blocks[blockSlug] = {}))[key] = handle;
167
- }
56
+ const normalizedAssetData = Object.entries(relevantAssetData)
57
+ .map(entry => {
58
+ const assetPath = this.dest.destination && entry[0].startsWith(this.dest.destination + "/")
59
+ ? entry[0].substring(this.dest.destination.length + 1) : entry[0];
60
+ return [assetPath, entry[1]];
61
+ });
62
+ for (const [assetPath, assetData] of normalizedAssetData) {
63
+ const match = regex.exec(assetPath);
64
+ if (!match) {
65
+ continue;
168
66
  }
169
- for (const [blockSlug, asset] of combinedExtensionData.setupFiles) {
170
- blockExtensionsConfig.setupFiles[blockSlug] = asset;
67
+ const blockSlug = match[1], assetType = match[2];
68
+ if (blockSlug && assetType) {
69
+ const key = assetType.replace(/-[sm]/gi, chars => chars.substring(1).toUpperCase());
70
+ const handle = `plaudit_block-extension_${blockSlug}-${assetType}`;
71
+ const isCss = (0, shared_1.isStyleField)(assetType);
72
+ const handleGroup = isCss ? 'styleHandles'
73
+ : ((0, shared_1.isScriptModuleField)(assetType) ? 'scriptModuleHandles' : 'scriptHandles');
74
+ blockExtensionsConfig[handleGroup][handle] = {
75
+ src: isCss ? assetPath.replace(/\.js$/, ".css") : assetPath,
76
+ rest: isCss || key.startsWith("editor")
77
+ ? [assetData.dependencies, assetData.version]
78
+ : [assetData.dependencies, assetData.version, { strategy: 'defer' }]
79
+ };
80
+ (blockExtensionsConfig.blocks[blockSlug] ?? (blockExtensionsConfig.blocks[blockSlug] = {}))[key] = handle;
171
81
  }
172
82
  }
83
+ for (const [blockSlug, asset] of setupFilePaths) {
84
+ blockExtensionsConfig.setupFiles[blockSlug] = asset;
85
+ }
173
86
  blockExtensionsConfig.scriptHandles = Object.fromEntries(Object.entries(blockExtensionsConfig.scriptHandles)
174
87
  .toSorted(([a], [b]) => a.localeCompare(b)));
175
88
  blockExtensionsConfig.scriptModuleHandles = Object.fromEntries(Object.entries(blockExtensionsConfig.scriptModuleHandles)
@@ -185,18 +98,71 @@ class ExtensionsConfigFileGeneratorPlugin extends AbstractMultiPhaseLibraryAndEn
185
98
  .toSorted(([a], [b]) => a.localeCompare(b)));
186
99
  compilation.emitAsset(node_path_1.default.join(this.dest.destination, "mapping.config.php"), new webpack_1.sources.RawSource((0, shared_1.makeEmittableConfigPHP)(blockExtensionsConfig, true)));
187
100
  }
188
- attachSecondPhase(compilation) {
189
- compilation.hooks.processAssets.tapPromise({ name: `${this.constructor.name}_GenerateConfigFile`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
190
- const combinedExtensionData = (await ExtensionsConfigFileGeneratorPlugin.semaphore.wait())
191
- .reduce((main, { assets, setupFiles }) => {
192
- main.assets.push(...assets);
193
- main.setupFiles.push(...setupFiles);
194
- return main;
195
- }, { assets: [], setupFiles: [], libraryType: "" });
196
- if (combinedExtensionData.assets.length > 0 || combinedExtensionData.setupFiles.length > 0 || !this.config.useUnifiedLoader) {
197
- this.generateVersionTwoConfigFile(compilation, combinedExtensionData);
101
+ attachUniquePhase(compilation) {
102
+ compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
103
+ const plugins = Object.values((await ExtensionsConfigFileGeneratorPlugin.semaphore.wait())
104
+ .reduce((acc, cur) => {
105
+ const accValue = acc[cur.plugin.group];
106
+ if (accValue === undefined) {
107
+ acc[cur.plugin.group] = { ...cur, setupFiles: cur.setupFiles?.length ? [...cur.setupFiles] : [] };
108
+ return acc;
109
+ }
110
+ if (cur.relevantAssetData) {
111
+ accValue.relevantAssetData = { ...accValue.relevantAssetData, ...cur.relevantAssetData };
112
+ }
113
+ if (cur.setupFiles?.length) {
114
+ accValue.setupFiles.push(...cur.setupFiles);
115
+ }
116
+ return acc;
117
+ }, {}))
118
+ .sort((a, b) => a.plugin.group.localeCompare(b.plugin.group));
119
+ for (const { plugin, relevantAssetData, setupFiles } of plugins) {
120
+ plugin.generateVersionTwoConfigFile(compilation, relevantAssetData, setupFiles);
198
121
  }
199
122
  });
200
123
  }
124
+ processAssets(compilation, rawAssetData) {
125
+ const relevantAssetData = this.extractRelevantAssetData(compilation, rawAssetData);
126
+ const staticallyLoadedEntrypoints = Object.keys(relevantAssetData);
127
+ const generateLoader = (writer) => {
128
+ const filePathPrefixVar = new php_writer_1.Var("filePathPrefix");
129
+ const fileUriPrefixVar = new php_writer_1.Var("fileUriPrefix");
130
+ writer
131
+ .assign(filePathPrefixVar, new php_writer_1.Literal(`__DIR__.${php_writer_1.Expr.convertJsonToPHP(this.extensionsDestPath)}`))
132
+ .call("plaudit_webpack_extensions__resolve_base_uri", [filePathPrefixVar], { assignTo: fileUriPrefixVar })
133
+ .call("GutenbergUtils::loadExtensionsV2", [
134
+ new php_writer_1.Literal(`__DIR__.${php_writer_1.Expr.convertJsonToPHP(this.extensionsDestPath + "mapping.config.php")}`),
135
+ filePathPrefixVar, fileUriPrefixVar,
136
+ `${this.config.plainEntrypointsHandlePrefix || node_path_1.default.basename(process.cwd())}_extension_`
137
+ ]);
138
+ };
139
+ let action;
140
+ const potentialHandle = this.dest.locations?.handle;
141
+ if (potentialHandle) {
142
+ if (typeof potentialHandle === 'string') {
143
+ try {
144
+ action = writer => writer.use("Plaudit\\Common\\Lib\\GutenbergUtils").function(potentialHandle, [], generateLoader, { returnType: 'void' });
145
+ }
146
+ catch (e) {
147
+ compilation.errors.push((0, shared_1.newWebpackErrorForFile)(["An error occurred while emitting a function for dynamically loading extensions", { cause: e }], this.extensionsSrcPath));
148
+ this.rejectSemaphores();
149
+ return;
150
+ }
151
+ }
152
+ else {
153
+ compilation.errors.push(new Error("The extensions directoryLayout's handle support is limited to static strings"));
154
+ this.rejectSemaphores();
155
+ return;
156
+ }
157
+ }
158
+ else {
159
+ action = writer => writer.use("Plaudit\\Common\\Lib\\GutenbergUtils").withScope(generateLoader);
160
+ }
161
+ const myCacheData = { plugin: this, setupFiles: this.setupFiles, relevantAssetData };
162
+ ExtensionsConfigFileGeneratorPlugin.semaphore.resolve(this.id, myCacheData);
163
+ UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, this.setupFiles.length > 0 || staticallyLoadedEntrypoints.length > 0
164
+ ? { group: this.group, requiresBaseURI: true, action, staticallyLoadedEntrypoints }
165
+ : undefined);
166
+ }
201
167
  }
202
168
  exports.ExtensionsConfigFileGeneratorPlugin = ExtensionsConfigFileGeneratorPlugin;
@@ -1,8 +1,10 @@
1
- import { AbstractMultiPhaseLibraryPlugin } from "./AbstractMultiPhaseLibraryPlugin";
2
- import { Compilation, type Compiler } from "webpack";
3
- export declare class ExtensionsConfigFileGeneratorPluginV1 extends AbstractMultiPhaseLibraryPlugin {
1
+ import { AbstractBiPhasicGroupAndEntryPlugin, EntryProvider } from "./AbstractBiPhasicGroupAndEntryPlugin";
2
+ import type { ParsedAssetsJson } from "../shared";
3
+ import type { VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
4
+ import { Compilation } from "webpack";
5
+ export declare class ExtensionsConfigFileGeneratorPluginV1 extends AbstractBiPhasicGroupAndEntryPlugin<string> {
4
6
  private readonly extensionsDest;
5
- constructor(extensionsDest: string);
6
- apply(compiler: Compiler): void;
7
- protected attachSecondPhase(compilation: Compilation): void;
7
+ constructor(config: VerifiedPlauditWordpressWebpackConfig, extensionsDest: string, context: string, entry: EntryProvider<string>);
8
+ protected attachUniquePhase(): void;
9
+ protected processAssets(compilation: Compilation, assetsJson: ParsedAssetsJson): void;
8
10
  }