-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathbuild.mjs
More file actions
383 lines (352 loc) · 12.6 KB
/
Copy pathbuild.mjs
File metadata and controls
383 lines (352 loc) · 12.6 KB
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
// Build script for @microsoft/msrcrypto.
//
// Replaces the previous Gulp pipeline. Single dev dependency: esbuild.
//
// Pipeline:
// 1. Concatenate the full source list -> dist/msrcrypto.js
// - strip per-file leading license headers (avoid ~30 duplicate copies)
// - strip /* debug-block */ ... /* end-debug-block */ regions
// - prepend a single LICENSE header
// (the src/subtle/* files are concatenated inline, in order, so the
// msrcryptoSubtle IIFE scope is formed by head.js ... tail.js)
// 2. esbuild minify dist/msrcrypto.js -> dist/msrcrypto.min.js
// - target: es5 (source is ES5; refuse to introduce ES6+ syntax)
// - minifySyntax: false (preserves obj["catch"] form needed for IE8)
//
// Usage: npm run build
// npm run build -- --watch
import * as esbuild from "esbuild";
import { readFile, writeFile, rm, mkdir } from "node:fs/promises";
import { existsSync } from "node:fs";
import { dirname } from "node:path";
import { performance } from "node:perf_hooks";
const LICENSE_FILE = "LICENSE";
const FULL_BUNDLE_OUT = "dist/msrcrypto.js";
const MIN_BUNDLE_OUT = "dist/msrcrypto.min.js";
// Single source of truth for the library version: package.json. The value is
// injected into the bundle at build time so the shipped msrCryptoVersion can
// never drift from the published package version.
const PKG_VERSION = JSON.parse(await readFile("package.json", "utf8")).version;
const VERSION_RE = /var msrCryptoVersion = "[^"]*";/;
const fullBuild = [
"src/bundleHead.js",
"src/operations.js",
"src/global.js",
"src/utilities.js",
"src/asn1.js",
"src/worker.js",
"src/jwk.js",
"src/cryptoMath.js",
"src/cryptoECC.js",
"src/curves_NIST.js",
"src/curves_BN.js",
"src/curves_NUMS.js",
"src/sha.js",
"src/sha1.js",
"src/sha256.js",
"src/sha512.js",
"src/hmac.js",
"src/aes.js",
"src/aes-cbc.js",
"src/aes-gcm.js",
"src/aes-kw.js",
"src/random.js",
"src/entropy.js",
"src/prime.js",
"src/rsa-base.js",
"src/rsa-oaep.js",
"src/rsa-pkcs1.js",
"src/rsa-pss.js",
"src/rsa.js",
"src/concat.js",
"src/pbkdf2.js",
"src/hkdf.js",
"src/hkdf-ctr.js",
"src/ecdh.js",
"src/ecdsa.js",
"src/subtle/head.js",
"src/subtle/syncWorker.js",
"src/subtle/operations.js",
"src/subtle/keyManager.js",
"src/subtle/workerManager.js",
"src/subtle/subtleInterface.js",
"src/subtle/tail.js",
"src/bundleTail.js",
"src/subtle/promises.js",
];
const DEBUG_BLOCK_RE =
/\/\*\s*debug-block\s*\*\/[\s\S]*?\/\*\s*end-debug-block\s*\*\//g;
// Strip all comments from source (replicates gulp-strip-comments behaviour).
// Handles // line comments, /* block comments */, string literals, and
// regex literals — so it does not accidentally strip comment-like text
// inside those constructs (e.g. /https?:\/\//).
//
// Regex-vs-division disambiguation: a bare / is a regex literal start when
// the previous significant (non-whitespace) character is NOT one that can
// end a primary expression (identifier, digit, ), ]). This heuristic is
// standard and correct for all ES5 patterns found in this codebase.
function stripAllComments(src) {
let out = "";
let i = 0;
const n = src.length;
var prevSig = ""; // last non-whitespace character written to output
function isOutAtLineStart() {
var p = out.length - 1;
while (p >= 0 && (out[p] === " " || out[p] === "\t" || out[p] === "\r")) {
p--;
}
return p < 0 || out[p] === "\n";
}
function trimOutLineIndent() {
while (out.length > 0) {
var ch = out[out.length - 1];
if (ch === " " || ch === "\t" || ch === "\r") {
out = out.slice(0, out.length - 1);
} else {
break;
}
}
}
while (i < n) {
var c = src[i];
if (c === "/" && i + 1 < n) {
// Block comment
if (src[i + 1] === "*") {
var bEnd = src.indexOf("*/", i + 2);
var bNext = bEnd === -1 ? n : bEnd + 2;
if (bNext < n && isOutAtLineStart()) {
var bi = bNext;
while (bi < n && (src[bi] === " " || src[bi] === "\t" || src[bi] === "\r")) {
bi++;
}
if (bi < n && src[bi] === "\n") {
trimOutLineIndent();
i = bi + 1;
continue;
}
}
i = bNext;
continue;
}
// Line comment
if (src[i + 1] === "/") {
var lEnd = src.indexOf("\n", i + 2);
if (lEnd === -1) {
i = n;
continue;
}
if (isOutAtLineStart()) {
trimOutLineIndent();
i = lEnd + 1;
continue;
}
i = lEnd; // keep newline for end-of-line comments after code
continue;
}
// Regex literal when previous significant char cannot end an expression
if (!/[a-zA-Z0-9_$)\]]/.test(prevSig)) {
out += c; i++; // opening /
while (i < n) {
var rc = src[i];
if (rc === "\\") { // escape sequence
out += rc; i++;
if (i < n) { out += src[i++]; }
continue;
}
if (rc === "[") { // character class [...]
out += rc; i++;
while (i < n) {
var cc = src[i];
out += cc; i++;
if (cc === "\\") { if (i < n) { out += src[i++]; } continue; }
if (cc === "]") break;
}
continue;
}
out += rc; i++;
if (rc === "/") break; // closing /
}
// consume regex flags (g i m y)
while (i < n && /[gimy]/.test(src[i])) { out += src[i++]; }
prevSig = "/";
continue;
}
// Otherwise: division operator — fall through to default
}
// String literals
if (c === '"' || c === "'") {
var q = c;
out += c; i++;
while (i < n) {
var sc = src[i];
out += sc; i++;
if (sc === "\\") { if (i < n) { out += src[i++]; } continue; }
if (sc === q) break;
}
prevSig = q;
continue;
}
out += c; i++;
if (c !== " " && c !== "\t" && c !== "\r" && c !== "\n") prevSig = c;
}
return out;
}
// Remove trailing horizontal whitespace and collapse long runs of blank lines
// introduced by comment stripping.
function collapseEmptyLines(src) {
return src
.replace(/[ \t]+\n/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.replace(/\n+$/, "\n");
}
// Remove only the LEADING comment block(s) from a source file.
// This drops the per-file license header without touching inline comments,
// strings, or regex literals further down. Safe for ES5 sources.
// Also skips a leading UTF-8 BOM (U+FEFF) — 37 of the source files in this
// repo start with one, and without skipping it the loop bails out before
// reaching the comment that follows.
function stripLeadingComments(src) {
let i = 0;
const n = src.length;
while (i < n) {
const c = src[i];
if (c === " " || c === "\t" || c === "\r" || c === "\n" || c === "\uFEFF") {
i++;
continue;
}
if (c === "/" && src[i + 1] === "*") {
const end = src.indexOf("*/", i + 2);
if (end === -1) break;
i = end + 2;
continue;
}
if (c === "/" && src[i + 1] === "/") {
const end = src.indexOf("\n", i + 2);
i = end === -1 ? n : end + 1;
continue;
}
break;
}
return src.slice(i);
}
async function concatFiles(files, { stripHeader } = { stripHeader: true }) {
const parts = await Promise.all(
files.map(async (f) => {
let text = await readFile(f, "utf8");
// Strip BOM unconditionally — embedded BOMs in the middle of a
// concatenated bundle are invalid as a token.
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
return stripHeader ? stripLeadingComments(text) : text;
}),
);
return parts.join("\n");
}
async function ensureDir(path) {
const dir = dirname(path);
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true });
}
}
async function cleanOutputs() {
for (const f of [FULL_BUNDLE_OUT, MIN_BUNDLE_OUT]) {
if (existsSync(f)) {
await rm(f, { force: true });
}
}
}
function fmtBytes(n) {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / 1024 / 1024).toFixed(2)} MB`;
}
async function build() {
const t0 = performance.now();
const license = await readFile(LICENSE_FILE, "utf8");
// 1. dist/msrcrypto.js — full UMD bundle.
let fullBundle = await concatFiles(fullBuild);
fullBundle = fullBundle.replace(DEBUG_BLOCK_RE, "");
fullBundle = stripAllComments(fullBundle);
fullBundle = collapseEmptyLines(fullBundle);
// Inject the package.json version so the bundle's msrCryptoVersion always
// matches the published package version.
if (!VERSION_RE.test(fullBundle)) {
throw new Error("build: could not find msrCryptoVersion declaration to inject version");
}
fullBundle = fullBundle.replace(VERSION_RE, `var msrCryptoVersion = "${PKG_VERSION}";`);
fullBundle = license + "\n" + fullBundle;
await ensureDir(FULL_BUNDLE_OUT);
await writeFile(FULL_BUNDLE_OUT, fullBundle);
// 2. dist/msrcrypto.min.js — minified.
// minifySyntax is intentionally OFF so esbuild does not rewrite
// obj["catch"] to obj.catch (catch is a reserved word on IE8).
const minified = await esbuild.transform(fullBundle, {
loader: "js",
target: "es5",
minifyWhitespace: true,
minifyIdentifiers: true,
minifySyntax: false,
legalComments: "none",
charset: "utf8",
});
await writeFile(MIN_BUNDLE_OUT, license + "\n" + minified.code);
const t1 = performance.now();
const sizes = await Promise.all(
[FULL_BUNDLE_OUT, MIN_BUNDLE_OUT].map(async (f) => {
const buf = await readFile(f);
return { file: f, bytes: buf.length };
}),
);
console.log(`built in ${(t1 - t0).toFixed(0)} ms (v${PKG_VERSION})`);
for (const s of sizes) {
console.log(` ${s.file.padEnd(24)} ${fmtBytes(s.bytes)}`);
}
}
async function watch() {
const { watch: fsWatch } = await import("node:fs");
const all = new Set([...fullBuild, LICENSE_FILE]);
let timer = null;
const rebuild = () => {
clearTimeout(timer);
timer = setTimeout(() => {
build().catch((err) => console.error(err));
}, 50);
};
await build();
console.log("watching for changes...");
// Keep references to every FSWatcher so they are not garbage-collected
// and stay active for the lifetime of the process.
const watchers = [];
for (const f of all) {
try {
watchers.push(fsWatch(f, rebuild));
} catch {
// file may not exist yet — that's fine
}
}
// Also watch the directories that contain source files so newly-added
// files trigger rebuilds. fs.watch({ recursive: true }) is not supported
// on all platforms (notably Linux), where it throws — fall back to a
// non-recursive watch on the src directory in that case. The per-file
// watchers above still cover every file in the build list either way.
try {
watchers.push(fsWatch("src", { recursive: true }, rebuild));
} catch {
try {
watchers.push(fsWatch("src", rebuild));
} catch {
// src may not be watchable — per-file watchers still apply
}
}
return watchers;
}
const args = process.argv.slice(2);
if (args.includes("--clean")) {
await cleanOutputs();
console.log("cleaned build outputs");
} else if (args.includes("--watch")) {
await cleanOutputs();
await watch();
} else {
await cleanOutputs();
await build();
}