@plaudit/webpack-extensions 3.21.2 → 4.0.0-rc.1

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 (61) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/USER-GUIDE.md +2 -1
  3. package/package.json +27 -49
  4. package/dist/plugins/AbstractBiPhasicGroupAndEntryPlugin.d.ts +0 -25
  5. package/dist/plugins/AbstractBiPhasicGroupAndEntryPlugin.js +0 -86
  6. package/dist/plugins/AbstractBiPhasicGroupPlugin.d.ts +0 -31
  7. package/dist/plugins/AbstractBiPhasicGroupPlugin.js +0 -91
  8. package/dist/plugins/AdditionalDependencyInjectorPlugin.d.ts +0 -11
  9. package/dist/plugins/AdditionalDependencyInjectorPlugin.js +0 -58
  10. package/dist/plugins/EnhancedBlockJSONPlugin.d.ts +0 -47
  11. package/dist/plugins/EnhancedBlockJSONPlugin.js +0 -657
  12. package/dist/plugins/EnhancedDynamicEntryPlugin.d.ts +0 -8
  13. package/dist/plugins/EnhancedDynamicEntryPlugin.js +0 -14
  14. package/dist/plugins/ExtensionsConfigFileGeneratorPlugin.d.ts +0 -20
  15. package/dist/plugins/ExtensionsConfigFileGeneratorPlugin.js +0 -191
  16. package/dist/plugins/ExtensionsConfigFileGeneratorPluginV1.d.ts +0 -9
  17. package/dist/plugins/ExtensionsConfigFileGeneratorPluginV1.js +0 -45
  18. package/dist/plugins/MiniCSSExtractPluginErrorCleaner.d.ts +0 -4
  19. package/dist/plugins/MiniCSSExtractPluginErrorCleaner.js +0 -15
  20. package/dist/plugins/MixableBiPhasicGroupAndEntryPlugin.d.ts +0 -6
  21. package/dist/plugins/MixableBiPhasicGroupAndEntryPlugin.js +0 -13
  22. package/dist/plugins/MixableBiPhasicGroupPlugin.d.ts +0 -6
  23. package/dist/plugins/MixableBiPhasicGroupPlugin.js +0 -13
  24. package/dist/plugins/PackageConfigSanityChecker.d.ts +0 -4
  25. package/dist/plugins/PackageConfigSanityChecker.js +0 -30
  26. package/dist/plugins/PlainEntrypointsConfigFileGeneratorPlugin.d.ts +0 -26
  27. package/dist/plugins/PlainEntrypointsConfigFileGeneratorPlugin.js +0 -392
  28. package/dist/plugins/SpecialAssetHandlingPlugin.d.ts +0 -12
  29. package/dist/plugins/SpecialAssetHandlingPlugin.js +0 -134
  30. package/dist/plugins/UnifiedLoaderGenerator.d.ts +0 -21
  31. package/dist/plugins/UnifiedLoaderGenerator.js +0 -144
  32. package/dist/plugins/VariablesJSMonitorPlugin.d.ts +0 -7
  33. package/dist/plugins/VariablesJSMonitorPlugin.js +0 -20
  34. package/dist/plugins/WPMLConfigBuilder.d.ts +0 -17
  35. package/dist/plugins/WPMLConfigBuilder.js +0 -472
  36. package/dist/plugins/dependency-extraction-webpack-plugin-config-builder.d.ts +0 -4
  37. package/dist/plugins/dependency-extraction-webpack-plugin-config-builder.js +0 -147
  38. package/dist/plugins/index.d.ts +0 -8
  39. package/dist/plugins/index.js +0 -24
  40. package/dist/plugins/static-configs.d.ts +0 -3
  41. package/dist/plugins/static-configs.js +0 -44
  42. package/dist/shared.d.ts +0 -311
  43. package/dist/shared.js +0 -536
  44. package/dist/utils/common-config-helpers.d.ts +0 -28
  45. package/dist/utils/common-config-helpers.js +0 -489
  46. package/dist/utils/css-writer.d.ts +0 -4
  47. package/dist/utils/css-writer.js +0 -46
  48. package/dist/utils/entrypoint-resolution-logic.d.ts +0 -13
  49. package/dist/utils/entrypoint-resolution-logic.js +0 -82
  50. package/dist/utils/location-encoding-filename-parser.d.ts +0 -30
  51. package/dist/utils/location-encoding-filename-parser.js +0 -120
  52. package/dist/utils/path-query-and-related-helpers.d.ts +0 -64
  53. package/dist/utils/path-query-and-related-helpers.js +0 -269
  54. package/dist/utils/pseudo-semaphore.d.ts +0 -14
  55. package/dist/utils/pseudo-semaphore.js +0 -79
  56. package/dist/wordpress-ports/dependency-extraction-webpack-plugin/index.d.ts +0 -72
  57. package/dist/wordpress-ports/dependency-extraction-webpack-plugin/index.js +0 -518
  58. package/dist/wordpress-ports/dependency-extraction-webpack-plugin/util.d.ts +0 -56
  59. package/dist/wordpress-ports/dependency-extraction-webpack-plugin/util.js +0 -155
  60. package/dist/wordpress-scripts-wrapper.d.ts +0 -4
  61. package/dist/wordpress-scripts-wrapper.js +0 -698
package/dist/shared.js DELETED
@@ -1,536 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.styleExtension = exports.scriptWithModuleExtension = exports.scriptWithoutModuleExtension = exports.scriptExtension = exports.entrypointFields = exports.standardLocationNamesMeta = void 0;
21
- exports.isParsedAssetsJson = isParsedAssetsJson;
22
- exports.isStandardLocationName = isStandardLocationName;
23
- exports.iterableStandardLocationNamesMeta = iterableStandardLocationNamesMeta;
24
- exports.normalizeLocationName = normalizeLocationName;
25
- exports.isRegisterScriptArgsShorthandName = isRegisterScriptArgsShorthandName;
26
- exports.isNormalizedUsageLocations = isNormalizedUsageLocations;
27
- exports.convertHookLocationToNamesAndPriority = convertHookLocationToNamesAndPriority;
28
- exports.hasDeferringStrategy = hasDeferringStrategy;
29
- exports.canMergeHandles = canMergeHandles;
30
- exports.constantKeys = constantKeys;
31
- exports.constantEntries = constantEntries;
32
- exports.determineCurrentSourceType = determineCurrentSourceType;
33
- exports.shouldWriteDistDev = shouldWriteDistDev;
34
- exports.isDistDevOutputPath = isDistDevOutputPath;
35
- exports.applyStandards = applyStandards;
36
- exports.resolveStandard = resolveStandard;
37
- exports.convertUsageLocationsHandleToEmittableHandle = convertUsageLocationsHandleToEmittableHandle;
38
- exports.makeEmittableConfigPHP = makeEmittableConfigPHP;
39
- exports.convertEntrypointFieldForAssetType = convertEntrypointFieldForAssetType;
40
- exports.leadingSlashIt = leadingSlashIt;
41
- exports.scriptOrStyleTest = scriptOrStyleTest;
42
- exports.isStyleField = isStyleField;
43
- exports.isScriptModuleField = isScriptModuleField;
44
- exports.mergeModuleDependencyArrays = mergeModuleDependencyArrays;
45
- exports.getHandleGroup = getHandleGroup;
46
- exports.hasAtLeastOneItem = hasAtLeastOneItem;
47
- exports.arrayIsLength = arrayIsLength;
48
- exports.kebabCase = kebabCase;
49
- exports.camelCaseForPHPLabels = camelCaseForPHPLabels;
50
- exports.newCleanWebpackError = newCleanWebpackError;
51
- exports.newWebpackErrorForFile = newWebpackErrorForFile;
52
- exports.emitResolveBaseUriFunction = emitResolveBaseUriFunction;
53
- exports.getAssetsJson = getAssetsJson;
54
- exports.getParsedAssetsJsonDataForEntrypoint = getParsedAssetsJsonDataForEntrypoint;
55
- exports.emitPHPWriterAsAsset = emitPHPWriterAsAsset;
56
- exports.dedent = dedent;
57
- exports.resolveLegacyBlockScriptsInFolder = resolveLegacyBlockScriptsInFolder;
58
- exports.appendAddInlineAssetCall = appendAddInlineAssetCall;
59
- exports.wrapInlineAssetContents = wrapInlineAssetContents;
60
- exports.synchronousDirIterator = synchronousDirIterator;
61
- exports.instanceOfNodeError = instanceOfNodeError;
62
- exports.shouldBeSkipped = shouldBeSkipped;
63
- const node_crypto_1 = require("node:crypto");
64
- const node_fs_1 = require("node:fs");
65
- const node_path_1 = __importDefault(require("node:path"));
66
- const php_writer_1 = require("@plaudit/php-writer");
67
- const expressions_1 = require("@plaudit/php-writer/expressions");
68
- const webpack_1 = require("webpack");
69
- __exportStar(require("./utils/entrypoint-resolution-logic"), exports);
70
- function isParsedAssetsJson(thing) {
71
- if (!thing || typeof thing !== 'object') {
72
- return false;
73
- }
74
- for (const value of Object.values(thing)) {
75
- if ((!value || typeof value !== 'object') ||
76
- (!('dependencies' in value) || !Array.isArray(value.dependencies) || (value.dependencies.length > 0 && !value.dependencies.every(d => typeof d === 'string' || (d && typeof d === 'object' && typeof d.id === 'string')))) ||
77
- (!('version' in value) || !value.version || typeof value.version !== 'string')) {
78
- return false;
79
- }
80
- }
81
- return true;
82
- }
83
- exports.standardLocationNamesMeta = {
84
- clientView: { action: "wp_enqueue_scripts", alternate_names: ['client-view', 'view'] },
85
- clientEditor: { action: "enqueue_block_editor_assets", alternate_names: ['client-editor', 'editor'] },
86
- blockAssets: { action: "enqueue_block_assets", alternate_names: ['block-assets'] },
87
- admin: { action: "admin_enqueue_scripts", supports_hook_name: true },
88
- login: { action: "login_enqueue_scripts" },
89
- customizer: { action: "customize_controls_enqueue_scripts" },
90
- analytics: { action: "plaudit_enqueue_analytics" },
91
- };
92
- function isStandardLocationName(name) {
93
- return Object.hasOwn(exports.standardLocationNamesMeta, name);
94
- }
95
- function iterableStandardLocationNamesMeta() {
96
- return constantEntries(exports.standardLocationNamesMeta);
97
- }
98
- function normalizeLocationName(name) {
99
- if (isStandardLocationName(name) || name === 'register') {
100
- return name;
101
- }
102
- for (const [standardName, { alternate_names }] of iterableStandardLocationNamesMeta()) {
103
- if (alternate_names?.includes(name)) {
104
- return standardName;
105
- }
106
- }
107
- throw new Error(`"${name}" is neither a standard nor alternate location name`);
108
- }
109
- function isRegisterScriptArgsShorthandName(name) {
110
- return ['lazy', 'eager', 'inline'].includes(name);
111
- }
112
- function isNormalizedUsageLocations(usageLocations) {
113
- return typeof usageLocations.registerScriptArgs !== 'string';
114
- }
115
- function convertHookLocationToNamesAndPriority(hookLocation) {
116
- if (typeof hookLocation === 'string') {
117
- return [[hookLocation], 10];
118
- }
119
- if (typeof hookLocation === 'number') {
120
- return [[], hookLocation];
121
- }
122
- if (typeof hookLocation === 'boolean') {
123
- return [[], 10];
124
- }
125
- if (Array.isArray(hookLocation)) {
126
- return [hookLocation, 10];
127
- }
128
- // if it's in object-form
129
- return [typeof hookLocation.hook_name === 'string' ? [hookLocation.hook_name] : hookLocation.hook_name ?? [], hookLocation.priority ?? 10];
130
- }
131
- function hasDeferringStrategy(handle) {
132
- return handle.rest[2]?.strategy === 'async' || handle.rest[2]?.strategy === 'defer';
133
- }
134
- /**
135
- * @return {@code true} -> "can share the same handle", {@code false} -> "cannot be merged", {@code 'dependent'} -> "one handle can be listed as a dependency of the other"
136
- */
137
- function canMergeHandles(handleA, handleB) {
138
- if (handleA.inlinedAsset === undefined && handleB.inlinedAsset === undefined) {
139
- return false; // We cannot merge handles for two non-inlined assets
140
- }
141
- if (handleA.lazyLoader !== handleB.lazyLoader) {
142
- return false; // We cannot merge handles for assets that will be loaded under separate conditions
143
- }
144
- if (node_path_1.default.dirname(handleA.src) !== node_path_1.default.dirname(handleB.src)) {
145
- return false; // We don't want assets from different locations to be able to have their handles overlap
146
- }
147
- const additionalArgsA = handleA.rest.length === 3 ? handleA.rest[2] : {};
148
- const additionalArgsB = handleB.rest.length === 3 ? handleB.rest[2] : {};
149
- if (additionalArgsA.module_dependencies !== additionalArgsB.module_dependencies) {
150
- if (additionalArgsA.module_dependencies === undefined) {
151
- return false;
152
- }
153
- if (additionalArgsB.module_dependencies === undefined) {
154
- return false;
155
- }
156
- if (additionalArgsA.module_dependencies.length !== additionalArgsB.module_dependencies.length) {
157
- return false;
158
- }
159
- for (const modDep of additionalArgsA.module_dependencies) {
160
- if (!additionalArgsB.module_dependencies.includes(modDep)) {
161
- return false;
162
- }
163
- }
164
- }
165
- if (additionalArgsA.in_footer !== additionalArgsB.in_footer) {
166
- return 'dependent';
167
- }
168
- if (hasDeferringStrategy(handleA) && handleB.inlinedAsset?.position === 'after') {
169
- return false;
170
- }
171
- if (hasDeferringStrategy(handleB) && handleA.inlinedAsset?.position === 'after') {
172
- return false;
173
- }
174
- if (handleA.locations.register !== handleB.locations.register) {
175
- return false; //TODO: Maybe make this more granular?
176
- }
177
- for (const standardLocation of constantKeys(exports.standardLocationNamesMeta)) {
178
- const locA = handleA.locations[standardLocation];
179
- const locB = handleB.locations[standardLocation];
180
- if (locA === locB) {
181
- continue;
182
- }
183
- if (locA === undefined || locA === false || locB === undefined || locB === false) {
184
- return false;
185
- }
186
- const [locAHookNames, locAPriority] = convertHookLocationToNamesAndPriority(locA);
187
- const [locBHookNames, locBPriority] = convertHookLocationToNamesAndPriority(locB);
188
- if (locAHookNames.length !== locBHookNames.length) {
189
- return false;
190
- }
191
- if (locAHookNames.length > 0) {
192
- for (const hookName of locAHookNames) {
193
- if (!locBHookNames.includes(hookName)) {
194
- return false;
195
- }
196
- }
197
- }
198
- if (locAPriority !== locBPriority) {
199
- return 'dependent'; // We cannot merge hooks across priority boundaries, but we can have one require the other
200
- }
201
- }
202
- return true;
203
- }
204
- function constantKeys(object) {
205
- return Object.keys(object);
206
- }
207
- function constantEntries(object) {
208
- return Object.entries(object);
209
- }
210
- function determineCurrentSourceType(dest, srcIsDirectory) {
211
- if (typeof dest === 'string') {
212
- return srcIsDirectory ? "blocks" /* SourceType.blocks */ : "plain" /* SourceType.plain */;
213
- }
214
- else {
215
- if (dest.directoryLayout === undefined) {
216
- return srcIsDirectory ? "blocks" /* SourceType.blocks */ : "plain" /* SourceType.plain */;
217
- }
218
- if (dest.directoryLayout === "extensions" /* SourceType.extensions */ || dest.directoryLayout === "blocks" /* SourceType.blocks */) {
219
- if (!srcIsDirectory) {
220
- throw new Error(`The '${dest.directoryLayout}' source type must be associated with a directory`);
221
- }
222
- }
223
- return dest.directoryLayout;
224
- }
225
- }
226
- /** Unified-loader watch output: `dist` → `dist-dev` when SERVER_MODE is development. */
227
- function shouldWriteDistDev(config) {
228
- return !!(config.outputDir && config.useUnifiedLoader && !config.omitDistDev && (process.env['SERVER_MODE'] ?? 'development') === 'development');
229
- }
230
- /**
231
- * This MUST be kept in sync with the copy in @plaudit/dev-webpack-plugin
232
- * @returns true for `dist-dev` (or any `*-dev` output folder produced by {@link shouldWriteDistDev}).
233
- */
234
- function isDistDevOutputPath(outputPath) {
235
- return node_path_1.default.basename(outputPath.replace(/[/\\]+$/, '')).endsWith('-dev');
236
- }
237
- function applyStandards(config) {
238
- switch (config.standard) {
239
- case '2026-03-13':
240
- return {
241
- ...resolveStandard('2026-03-13'),
242
- ...config
243
- };
244
- case undefined:
245
- return config;
246
- default:
247
- throw `Invalid standard: ${config.standard}`;
248
- }
249
- }
250
- function resolveStandard(standard) {
251
- switch (standard) {
252
- case "2026-03-13":
253
- return {
254
- useWebpackResourceFiltering: true,
255
- extensionsVersion: 3,
256
- plainEntrypointsVersion: 2,
257
- srcDir: "src",
258
- outputDir: "dist",
259
- useUnifiedLoader: true,
260
- onlyRunPostCSSOnPCSS: true,
261
- };
262
- default:
263
- return undefined;
264
- }
265
- }
266
- function convertUsageLocationsHandleToEmittableHandle(handle, handlePrefix, handleSuffix) {
267
- const generatedHandle = `${handlePrefix}/${handleSuffix}`;
268
- let emittableHandle;
269
- if (!handle) {
270
- return generatedHandle;
271
- }
272
- if (typeof handle === 'string') {
273
- emittableHandle = handle;
274
- }
275
- else if (typeof handle === 'function') {
276
- emittableHandle = handle(generatedHandle);
277
- }
278
- else {
279
- emittableHandle = handle.niceName && `${handlePrefix}/${handle.niceName}`;
280
- }
281
- // A callback is free to return nothing, which means "use the handle you would have generated"
282
- return emittableHandle ? emittableHandle.replaceAll("{basename}", handleSuffix) : generatedHandle;
283
- }
284
- function makeEmittableConfigPHP(data, asFullFile, parentIndent = "") {
285
- const prettyPrintedMetadata = php_writer_1.json2php.make({ indent: "\t", linebreak: "\n", shortArraySyntax: true })(data, parentIndent)
286
- .replaceAll(/(\n\t*)\[\s+],/gs, "$1[],")
287
- .replaceAll(/\[\n\t+([^\n]+)\n\t+]/gs, (_, inner) => `[${inner.trim()}]`)
288
- .replaceAll(/'rest' => \[\n\t+(\[(?:'[^']+')?]),\n\t+('[^']+')(?:,\n\t+(\[[^\n]+]))?\n\t+]/gs, (_, deps, hash, args) => `'rest' => [${[deps, hash, args].filter(value => !!value).join(", ")}]`);
289
- return asFullFile ? `<?php return ${prettyPrintedMetadata};` : prettyPrintedMetadata.trim();
290
- }
291
- exports.entrypointFields = ["editorStyle", "viewStyle", "style", "editorScript", "viewScript", "script", "viewScriptModule"];
292
- function convertEntrypointFieldForAssetType(entrypointField, assetType) {
293
- // Using these word fragments instead of the full words allows us to avoid having to deal with the capitalization of the first letter
294
- const searchRep = assetType === 'script' ? ['tyle', 'cript'] : [/cript(?:Module)?/, 'tyle'];
295
- return entrypointField.replace(...searchRep);
296
- }
297
- function leadingSlashIt(pathOrSomething) {
298
- return pathOrSomething.startsWith('/') ? pathOrSomething : ('/' + pathOrSomething);
299
- }
300
- exports.scriptExtension = /(?<filename>.+)(?<extension>\.m?[jt]sx?)$/i;
301
- exports.scriptWithoutModuleExtension = /(?<filename>.+)(?<extension>\.[jt]sx?)($|\?)/i;
302
- exports.scriptWithModuleExtension = /(?<filename>.+)(?<extension>\.m[jt]sx?)($|\?)/i;
303
- exports.styleExtension = /(?<filename>.+)(?<extension>\.([ps]?c|sa)ss)($|\?)/i;
304
- function scriptOrStyleTest(entryPath, scriptExtension) {
305
- return scriptExtension.test(entryPath) ? "script" : (exports.styleExtension.test(entryPath) ? "style" : "");
306
- }
307
- function isStyleField(field) {
308
- return field.endsWith("tyle");
309
- }
310
- function isScriptModuleField(field) {
311
- return field.includes("odule");
312
- }
313
- function mergeModuleDependencyArrays(a, b) {
314
- if (a === undefined || a.length === 0) {
315
- return b;
316
- }
317
- if (b === undefined || b.length === 0) {
318
- return a;
319
- }
320
- const seenModuleDeps = new Map();
321
- return [...a, ...b].filter(dep => {
322
- let id, type;
323
- if (typeof dep === 'string') {
324
- id = dep;
325
- type = 'static';
326
- }
327
- else {
328
- id = dep.id;
329
- type = dep.import ?? 'static';
330
- }
331
- if (seenModuleDeps.has(id)) {
332
- if (type !== seenModuleDeps.get(id)) {
333
- throw newCleanWebpackError(`Encountered conflicting import types for the "${id}" module dependency`);
334
- }
335
- return false;
336
- }
337
- seenModuleDeps.set(id, type);
338
- return true;
339
- });
340
- }
341
- function getHandleGroup(field) {
342
- if (isStyleField(field)) {
343
- return 'styleHandles';
344
- }
345
- if (isScriptModuleField(field)) {
346
- return 'scriptModuleHandles';
347
- }
348
- return 'scriptHandles';
349
- }
350
- function hasAtLeastOneItem(list) {
351
- return list.length > 0 && list[0] !== undefined && list[0] !== null;
352
- }
353
- function arrayIsLength(arr, length) {
354
- return !!arr && arr.length === length;
355
- }
356
- function kebabCase(value) {
357
- const kebabCaseRegexes = [[/([a-z])([A-Z])/g, "$1-$2"], [/[\s_.\-]+/g, "-"]];
358
- return kebabCaseRegexes.reduce((str, [pattern, replacement]) => str.replace(pattern, replacement), value).toLowerCase();
359
- }
360
- function camelCaseForPHPLabels(value) {
361
- return value
362
- .replaceAll("/", "\\")
363
- .split("\\")
364
- .map(part => {
365
- part = part
366
- .replaceAll(/[^a-zA-Z0-9\x7f-\xff](\w|$)/ig, (_, chr) => typeof chr === 'string' ? chr.toUpperCase() : "")
367
- .replaceAll(/\d[a-z]/g, match => match.toUpperCase());
368
- return part.length > 1 ? part.substring(0, 1).toUpperCase() + part.substring(1) : part.toUpperCase();
369
- })
370
- .join("\\");
371
- }
372
- function newCleanWebpackError(error) {
373
- const res = typeof error === 'string' ? new webpack_1.WebpackError(error) : new webpack_1.WebpackError(...error);
374
- res.hideStack = true;
375
- return res;
376
- }
377
- function newWebpackErrorForFile(error, file) {
378
- const res = newCleanWebpackError(error);
379
- res.file = file;
380
- return res;
381
- }
382
- /**
383
- * 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
384
- */
385
- function emitResolveBaseUriFunction(writer) {
386
- const dir = new expressions_1.Var("dir");
387
- const baseUris = new expressions_1.Var("base_uris");
388
- const assignmentTarget = new expressions_1.ArrayAccess(baseUris, dir);
389
- const path = new expressions_1.Var("path");
390
- writer.function("plaudit_webpack_extensions__resolve_base_uri", [dir], writer => {
391
- writer
392
- .static(baseUris, { initializer: [] })
393
- .if(expressions_1.Expr.isset(assignmentTarget))
394
- .return(assignmentTarget)
395
- .elseIf(expressions_1.Expr.call("str_starts_with", [dir, expressions_1.Constants.ABSPATH]))
396
- .assign(path, expressions_1.Expr.call("ltrim", [expressions_1.Expr.call("substr", [dir, expressions_1.Expr.call("strlen", [expressions_1.Constants.ABSPATH])]), "/"]))
397
- .elseIf(expressions_1.Expr.call("str_starts_with", [dir, "/workspace/website"]))
398
- .assign(path, expressions_1.Expr.call("ltrim", [expressions_1.Expr.call("substr", [dir, 18]), "/"]))
399
- .else()
400
- .call("error_log", ["UNABLE TO FIGURE OUT WHAT THE RELATIVE PATH TO THE BUILT FILES DIRECTORY SHOULD BE"])
401
- .assign(path, "")
402
- .endIf()
403
- .call("trailingslashit", [expressions_1.Expr.call("get_site_url", [new expressions_1.Argument(path, "path")])], { return: true, assignTo: assignmentTarget });
404
- }, { returnType: "string", includeExistenceCheck: true });
405
- }
406
- function getAssetsJson(compilation) {
407
- const asset = compilation.getAsset("assets.json");
408
- if (asset && isParsedAssetsJson(asset.info["parsed-assets-json"])) {
409
- return asset.info["parsed-assets-json"];
410
- }
411
- throw new Error("assets.json is unexpectedly missing");
412
- }
413
- function getParsedAssetsJsonDataForEntrypoint(compilation, entrypoint, metadata) {
414
- const dest = metadata.dest;
415
- const parsedAssetJson = getAssetsJson(compilation);
416
- const assetType = scriptOrStyleTest(metadata.absoluteSrc, exports.scriptExtension);
417
- const chunkFiles = [dest.destination, ...entrypoint.chunks.flatMap(chunk => Array.from(chunk.files))]
418
- .filter(chunkFile => scriptOrStyleTest(chunkFile, exports.scriptExtension) === assetType);
419
- for (const chunkFile of chunkFiles) {
420
- if (parsedAssetJson[chunkFile]) {
421
- return { assetName: chunkFile, assetData: parsedAssetJson[chunkFile] };
422
- }
423
- }
424
- if (assetType !== 'style' || !hasAtLeastOneItem(chunkFiles)) {
425
- return undefined;
426
- }
427
- // The rest of this function is a modified version of the hash-computing logic from @wordpress/dependency-extraction-webpack-plugin
428
- const { hashFunction, hashDigest, hashDigestLength } = compilation.outputOptions;
429
- const hashBuilder = webpack_1.util.createHash(hashFunction);
430
- for (const chunkFile of chunkFiles.toSorted()) {
431
- const source = compilation.getAsset(chunkFile)?.source.buffer();
432
- if (source !== undefined) {
433
- hashBuilder.update(source);
434
- }
435
- }
436
- // Finalise hash.
437
- const contentHash = hashBuilder
438
- .digest(hashDigest)
439
- .slice(0, hashDigestLength);
440
- const assetData = {
441
- dependencies: [],
442
- version: contentHash,
443
- };
444
- compilation.updateAsset("assets.json", s => s, a => ({ ...a, "parsed-assets-json": { ...parsedAssetJson, [chunkFiles[0]]: assetData } }));
445
- return { assetName: chunkFiles[0], assetData };
446
- }
447
- function emitPHPWriterAsAsset(writer, compilation, file, assetInfo) {
448
- const contents = writer.toString() + "\n";
449
- compilation[file in compilation.assets ? 'updateAsset' : 'emitAsset'](file, new webpack_1.sources.RawSource(contents), { size: Buffer.byteLength(contents), ...assetInfo });
450
- }
451
- function dedent(text, ...values) {
452
- const lines = text.reduce((result, part, i) => result + String(values[i - 1]) + part).split(/\r?\n/);
453
- // A template that opens and closes on its own line frames the content with two throwaway lines
454
- if (lines[0]?.trim() === "") {
455
- lines.shift();
456
- }
457
- if (lines.length > 1 && lines.at(-1)?.trim() === "") {
458
- lines.pop();
459
- }
460
- // Only the lines with content get a say in the indent, and a line break must never count as one
461
- const indent = lines.filter(line => line.trim() !== "")
462
- .reduce((shortest, line) => {
463
- const lineIndent = /^[ \t]*/.exec(line)?.[0] ?? "";
464
- return shortest === undefined || lineIndent.length < shortest.length ? lineIndent : shortest;
465
- }, undefined);
466
- return indent
467
- ? lines.map(line => line.startsWith(indent) ? line.substring(indent.length) : line).join("\n")
468
- : lines.join("\n");
469
- }
470
- function resolveLegacyBlockScriptsInFolder(folder) {
471
- const blockScriptEntrypoints = [];
472
- for (const blockDir of (0, node_fs_1.readdirSync)(folder)) {
473
- const fullBlockDir = node_path_1.default.join(folder, blockDir);
474
- const packageJSON = node_path_1.default.join(fullBlockDir, 'package.json');
475
- if ((0, node_fs_1.existsSync)(packageJSON)) {
476
- const main = JSON.parse((0, node_fs_1.readFileSync)(packageJSON, 'utf8'))['main'];
477
- if (main && (0, node_fs_1.existsSync)(node_path_1.default.join(fullBlockDir, main))) {
478
- blockScriptEntrypoints.push(node_path_1.default.join(fullBlockDir, main));
479
- }
480
- }
481
- }
482
- return blockScriptEntrypoints;
483
- }
484
- /**
485
- * @param compilation
486
- * @param writer
487
- * @param handle
488
- * @param type 'script_module' is NOT supported at this time; however, it is *handled* in this function
489
- * @param handleData
490
- */
491
- function appendAddInlineAssetCall(compilation, writer, handle, type, handleData) {
492
- if (type === 'script_module') {
493
- throw newWebpackErrorForFile("WordPress does not support inlined script modules", handleData.src);
494
- }
495
- if (handleData.rest[0]?.length) { // If there are any dependencies
496
- compilation.errors.push(newWebpackErrorForFile("Inlined scripts MUST NOT have dependencies. It WILL cause runtime inconsistencies and potentially cause sever performance issues", handleData.src));
497
- }
498
- const args = [handle, wrapInlineAssetContents(compilation, `plaudit_inlined_${type}`, handle, handleData.assetContents)];
499
- if (type === 'script' && handleData.inlinedAsset.position === 'before') {
500
- args.push('before');
501
- }
502
- writer.call(`wp_add_inline_${type}`, args);
503
- }
504
- function wrapInlineAssetContents(compilation, wrapperIdPrefix, handle, contents) {
505
- if (!compilation.outputOptions.path?.endsWith("-dev")) {
506
- contents = contents.replaceAll(/\/\*#\s+sourceMappingURL=.*?\*\/|\/\/#\s+sourceMappingURL=[^\r\n]*?([\r\n]|$)/gis, "$1");
507
- }
508
- return new expressions_1.HereOrNowDoc(`${wrapperIdPrefix}_${(0, node_crypto_1.createHash)('md5').update(handle).digest("hex")}`, contents.trim(), false);
509
- }
510
- function* synchronousDirIterator(dirPath) {
511
- try {
512
- using dir = (0, node_fs_1.opendirSync)(dirPath);
513
- for (let dirent; (dirent = dir.readSync()) !== null;) {
514
- yield dirent;
515
- }
516
- }
517
- catch (e) {
518
- if (!instanceOfNodeError(e, Error) || e.code !== 'ENOENT') {
519
- throw e;
520
- }
521
- }
522
- }
523
- /**
524
- * A type-guarded version of `instanceof Error` for Node.js.
525
- * @author Joseph JDBar Barron
526
- * @link https://dev.to/jdbar
527
- */
528
- function instanceOfNodeError(value, errorType) {
529
- return !!value && value instanceof errorType;
530
- }
531
- /**
532
- * This tests if the name starts with a "~", is equal to "example" or "examples", or includes "example" as a name segment
533
- */
534
- function shouldBeSkipped(name) {
535
- return name.startsWith("~") || name === "example" || name === "examples" || name.startsWith("example.") || name.includes(".example.");
536
- }
@@ -1,28 +0,0 @@
1
- import type { AbstractBiPhasicGroupAndEntryPlugin, EntryProvider } from "../plugins/AbstractBiPhasicGroupAndEntryPlugin";
2
- import type { AdditionalDependencyInjectorPlugin } from "../plugins/AdditionalDependencyInjectorPlugin";
3
- import { EntrypointFields, VerifiedPlauditWordpressWebpackConfig, BlockEntrypointInfo, VerifiedAdvancedOutputConfig, MinimumViableMetadata } from "../shared";
4
- import type { Compiler, Configuration, DynamicEntryPlugin, WebpackPluginInstance } from "webpack";
5
- import type WebpackRemoveEmptyScriptsPlugin from "webpack-remove-empty-scripts";
6
- export type CommonPluginConfig = {
7
- plugins: (WebpackPluginInstance | ((this: Compiler, compiler: Compiler) => void))[];
8
- removeEmptyScriptsPlugin: WebpackRemoveEmptyScriptsPlugin;
9
- makeAdditionalDependencyInjectorPlugin(referencePlugin: AbstractBiPhasicGroupAndEntryPlugin<any>): AdditionalDependencyInjectorPlugin;
10
- };
11
- export type CommonConfigProcessingResult = {
12
- entrypointFields: EntrypointFields;
13
- fixedRules: NonNullable<Configuration['module']>['rules'];
14
- processingModules: boolean;
15
- scriptExtension: RegExp;
16
- updateCurrentVariables: (value: VerifiedPlauditWordpressWebpackConfig['currentVariables']) => unknown;
17
- };
18
- export declare function joinPossiblyAbsolutePaths(...paths: (string | undefined)[]): string;
19
- export declare function groupEntrypointsByAssetFile<T>(entrypoints: T[], entrypointNameExtractor: (t: T) => string): Map<string, T[]>;
20
- export type BlockJsonExtensibleEntryObject = ExtensibleEntryObject<BlockEntrypointInfo>;
21
- export type EntryStaticNormalized = Awaited<ReturnType<ConstructorParameters<typeof DynamicEntryPlugin>[1]>>;
22
- export type ExtensibleEntryObject<M extends object = {}> = {
23
- [index: string]: Omit<EntryStaticNormalized[string], 'import'> & Required<NonNullable<Pick<EntryStaticNormalized[string], 'import'>>> & {
24
- plauditMetadata: M & MinimumViableMetadata;
25
- };
26
- };
27
- export declare function resolveEntryFromDirectory(commonConfig: CommonConfigProcessingResult, srcRoot: string, dest: VerifiedAdvancedOutputConfig): EntryProvider<BlockEntrypointInfo>;
28
- export declare function commonMakeWebpackConfig(config: VerifiedPlauditWordpressWebpackConfig, commonConfig: CommonConfigProcessingResult, webpackConfig: Configuration, externalize: VerifiedAdvancedOutputConfig['externalize'], plugins: CommonPluginConfig['plugins'], canClean: boolean): Configuration;