aboutsummaryrefslogtreecommitdiffstats
path: root/build/tasks/build.js
blob: 69a4de7c7c7228eefae31925a830f4becd30b374 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/**
 * Special build task to handle various jQuery build requirements.
 * Compiles JS modules into one bundle, sets the custom AMD name,
 * and includes/excludes specified modules
 */

"use strict";

const fs = require( "fs" );
const path = require( "path" );
const util = require( "util" );
const exec = util.promisify( require( "child_process" ).exec );
const rollup = require( "rollup" );
const excludedFromSlim = require( "./lib/slim-exclude" );
const rollupFileOverrides = require( "./lib/rollup-plugin-file-overrides" );
const pkg = require( "../../package.json" );
const isCleanWorkingDir = require( "./lib/isCleanWorkingDir" );
const processForDist = require( "./dist" );
const minify = require( "./minify" );
const getTimestamp = require( "./lib/getTimestamp" );
const verifyNodeVersion = require( "./lib/verifyNodeVersion" );
const srcFolder = path.resolve( __dirname, "../../src" );

const minimum = [ "core" ];

// Exclude specified modules if the module matching the key is removed
const removeWith = {
	ajax: [ "manipulation/_evalUrl", "deprecated/ajax-event-alias" ],
	callbacks: [ "deferred" ],
	css: [ "effects", "dimensions", "offset" ],
	"css/showHide": [ "effects" ],
	deferred: {
		remove: [ "ajax", "effects", "queue", "core/ready" ],
		include: [ "core/ready-no-deferred" ]
	},
	event: [ "deprecated/ajax-event-alias", "deprecated/event" ],
	selector: [ "css/hiddenVisibleSelectors", "effects/animatedSelector" ]
};

async function read( filename ) {
	return fs.promises.readFile( path.join( srcFolder, filename ), "utf8" );
}

// Remove the src folder and file extension
// and ensure unix-style path separators
function moduleName( filename ) {
	return filename
		.replace( `${srcFolder}${path.sep}`, "" )
		.replace( /\.js$/, "" )
		.split( path.sep )
		.join( path.posix.sep );
}

async function readdirRecursive( dir, all = [] ) {
	let files;
	try {
		files = await fs.promises.readdir( path.join( srcFolder, dir ), {
			withFileTypes: true
		} );
	} catch ( e ) {
		return all;
	}
	for ( const file of files ) {
		const filepath = path.join( dir, file.name );

		if ( file.isDirectory() ) {
			all.push( ...( await readdirRecursive( filepath ) ) );
		} else {
			all.push( moduleName( filepath ) );
		}
	}
	return all;
}

async function getOutputRollupOptions( {
	esm = false,
	factory = false
} = {} ) {
	const wrapperFileName = `wrapper${
		factory ? "-factory" : ""
	}${
		esm ? "-esm" : ""
	}.js`;

	const wrapperSource = await read( wrapperFileName );

	// Catch `// @CODE` and subsequent comment lines event if they don't start
	// in the first column.
	const wrapper = wrapperSource.split(
		/[\x20\t]*\/\/ @CODE\n(?:[\x20\t]*\/\/[^\n]+\n)*/
	);

	return {

		// The ESM format is not actually used as we strip it during the
		// build, inserting our own wrappers; it's just that it doesn't
		// generate any extra wrappers so there's nothing for us to remove.
		format: "esm",

		intro: wrapper[ 0 ].replace( /\n*$/, "" ),
		outro: wrapper[ 1 ].replace( /^\n*/, "" )
	};
}

const fileOverrides = new Map();

function setOverride( filePath, source ) {

	// We want normalized paths in overrides as they will be matched
	// against normalized paths in the file overrides Rollup plugin.
	fileOverrides.set( path.resolve( filePath ), source );
}

function unique( array ) {
	return [ ...new Set( array ) ];
}

async function checkExclude( exclude, include ) {
	const included = [ ...include ];
	const excluded = [ ...exclude ];

	for ( const module of exclude ) {
		if ( minimum.indexOf( module ) !== -1 ) {
			throw new Error( `Module \"${module}\" is a minimum requirement.` );
		}

		// Exclude all files in the dir of the same name
		// These are the removable dependencies
		// It's fine if the directory is not there
		// `selector` is a special case as we don't just remove
		// the module, but we replace it with `selector-native`
		// which re-uses parts of the `src/selector` dir.
		if ( module !== "selector" ) {
			const files = await readdirRecursive( module );
			excluded.push( ...files );
		}

		// Check removeWith list
		const additional = removeWith[ module ];
		if ( additional ) {
			const [ additionalExcluded, additionalIncluded ] = await checkExclude(
				additional.remove || additional,
				additional.include || []
			);
			excluded.push( ...additionalExcluded );
			included.push( ...additionalIncluded );
		}
	}

	return [ unique( excluded ), unique( included ) ];
}

async function writeCompiled( { code, dir, filename, version } ) {
	const compiledContents = code

		// Embed Version
		.replace( /@VERSION/g, version )

		// Embed Date
		// yyyy-mm-ddThh:mmZ
		.replace( /@DATE/g, new Date().toISOString().replace( /:\d+\.\d+Z$/, "Z" ) );

	await fs.promises.writeFile( path.join( dir, filename ), compiledContents );
	console.log( `[${getTimestamp()}] ${filename} v${version} created.` );
}

// Build jQuery ECMAScript modules
async function build( {
	amd,
	dir = "dist",
	exclude = [],
	filename = "jquery.js",
	include = [],
	esm = false,
	factory = false,
	slim = false,
	version,
	watch = false
} = {} ) {
	const pureSlim = slim && !exclude.length && !include.length;

	// Add the short commit hash to the version string
	// when the version is not for a release.
	if ( !version ) {
		const { stdout } = await exec( "git rev-parse --short HEAD" );
		const isClean = await isCleanWorkingDir();

		// "+[slim.]SHA" is semantically correct
		// Add ".dirty" as well if the working dir is not clean
		version = `${pkg.version}+${slim ? "slim." : ""}${stdout.trim()}${isClean ? "" : ".dirty"}`;
	} else if ( slim ) {
		version += "+slim";
	}

	await fs.promises.mkdir( dir, { recursive: true } );

	// Exclude slim modules when slim is true
	const [ excluded, included ] = await checkExclude(
		slim ? exclude.concat( excludedFromSlim ) : exclude,
		include
	);

	// Replace exports/global with a noop noConflict
	if ( excluded.includes( "exports/global" ) ) {
		const index = excluded.indexOf( "exports/global" );
		setOverride(
			`${srcFolder}/exports/global.js`,
			"import { jQuery } from \"../core.js\";\n\n" +
				"jQuery.noConflict = function() {};"
		);
		excluded.splice( index, 1 );
	}

	// Set a desired AMD name.
	if ( amd != null ) {
		if ( amd ) {
			console.log( "Naming jQuery with AMD name: " + amd );
		} else {
			console.log( "AMD name now anonymous" );
		}

		// Replace the AMD name in the AMD export
		// No name means an anonymous define
		const amdExportContents = await read( "exports/amd.js" );
		setOverride(
			`${srcFolder}/exports/amd.js`,
			amdExportContents.replace(

				// Remove the comma for anonymous defines
				/(\s*)"jquery"(,\s*)/,
				amd ? `$1\"${amd}\"$2` : " "
			)
		);
	}

	// Append excluded modules to version.
	// Skip adding exclusions for slim builds.
	// Don't worry about semver syntax for these.
	if ( !pureSlim && excluded.length ) {
		version += " -" + excluded.join( ",-" );
	}

	// Append extra included modules to version.
	if ( !pureSlim && included.length ) {
		version += " +" + included.join( ",+" );
	}

	const inputOptions = {
		input: `${srcFolder}/jquery.js`
	};

	const includedImports = included
		.map( ( module ) => `import "./${module}.js";` )
		.join( "\n" );

	const jQueryFileContents = await read( "jquery.js" );
	if ( include.length ) {

		// If include is specified, only add those modules.
		setOverride( inputOptions.input, includedImports );
	} else {

		// Remove the jQuery export from the entry file, we'll use our own
		// custom wrapper.
		setOverride(
			inputOptions.input,
			jQueryFileContents.replace( /\n*export \{ jQuery, jQuery as \$ };\n*/, "\n" ) +
				includedImports
		);
	}

	// Replace excluded modules with empty sources.
	for ( const module of excluded ) {
		setOverride(
			`${srcFolder}/${module}.js`,

			// The `selector` module is not removed, but replaced
			// with `selector-native`.
			module === "selector" ? await read( "selector-native.js" ) : ""
		);
	}

	const bundle = await rollup.rollup( {
		...inputOptions,
		plugins: [ rollupFileOverrides( fileOverrides ) ]
	} );

	const outputOptions = await getOutputRollupOptions( { esm, factory } );

	if ( watch ) {
		const watcher = rollup.watch( {
			...inputOptions,
			output: [ outputOptions ],
			plugins: [ rollupFileOverrides( fileOverrides ) ],
			watch: {
				include: `${srcFolder}/**`,
				skipWrite: true
			}
		} );

		watcher.on( "event", async( event ) => {
			switch ( event.code ) {
				case "ERROR":
					console.error( event.error );
					break;
				case "BUNDLE_END":
					const {
						output: [ { code } ]
					} = await event.result.generate( outputOptions );

					await writeCompiled( {
						code,
						dir,
						filename,
						version
					} );

					// Don't minify factory files; they are not meant
					// for the browser anyway.
					if ( !factory ) {
						await minify( { dir, filename, esm } );
					}
					break;
			}
		} );

		return watcher;
	} else {
		const {
			output: [ { code } ]
		} = await bundle.generate( outputOptions );

		await writeCompiled( { code, dir, filename, version } );

		// Don't minify factory files; they are not meant
		// for the browser anyway.
		if ( !factory ) {
			await minify( { dir, filename, esm } );
		} else {

			// We normally process for dist during minification to save
			// file reads. However, some files are not minified and then
			// we need to do it separately.
			const contents = await fs.promises.readFile(
				path.join( dir, filename ),
				"utf8"
			);
			processForDist( contents, filename );
		}
	}
}

async function buildDefaultFiles( { version, watch } = {} ) {
	await Promise.all( [
		build( { version, watch } ),
		build( { filename: "jquery.slim.js", slim: true, version, watch } ),
		build( {
			dir: "dist-module",
			filename: "jquery.module.js",
			esm: true,
			version,
			watch
		} ),
		build( {
			dir: "dist-module",
			filename: "jquery.slim.module.js",
			esm: true,
			slim: true,
			version,
			watch
		} ),

		build( {
			filename: "jquery.factory.js",
			factory: true,
			version,
			watch
		} ),
		build( {
			filename: "jquery.factory.slim.js",
			slim: true,
			factory: true,
			version,
			watch
		} ),
		build( {
			dir: "dist-module",
			filename: "jquery.factory.module.js",
			esm: true,
			factory: true,
			version,
			watch
		} ),
		build( {
			dir: "dist-module",
			filename: "jquery.factory.slim.module.js",
			esm: true,
			slim: true,
			factory: true,
			version,
			watch
		} )
	] );

	// Earlier Node.js versions do not support the ESM format.
	if ( !verifyNodeVersion() ) {
		return;
	}

	const { compareSize } = await import( "./compare_size.mjs" );
	return compareSize( {
		files: [
			"dist/jquery.min.js",
			"dist/jquery.slim.min.js",
			"dist-module/jquery.module.min.js",
			"dist-module/jquery.slim.module.min.js"
		]
	} );
}

module.exports = { build, buildDefaultFiles };