@signageos/lib-bundler 23.8.1 → 23.8.2-master.4405

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,889 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
13
+ var __typeError = (msg) => {
14
+ throw TypeError(msg);
15
+ };
16
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
17
+ var __spreadValues = (a, b) => {
18
+ for (var prop in b || (b = {}))
19
+ if (__hasOwnProp.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ if (__getOwnPropSymbols)
22
+ for (var prop of __getOwnPropSymbols(b)) {
23
+ if (__propIsEnum.call(b, prop))
24
+ __defNormalProp(a, prop, b[prop]);
25
+ }
26
+ return a;
27
+ };
28
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, { get: all[name], enumerable: true });
32
+ };
33
+ var __copyProps = (to, from, except, desc) => {
34
+ if (from && typeof from === "object" || typeof from === "function") {
35
+ for (let key of __getOwnPropNames(from))
36
+ if (!__hasOwnProp.call(to, key) && key !== except)
37
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
38
+ }
39
+ return to;
40
+ };
41
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
42
+ // If the importer is in node compatibility mode or this is not an ESM
43
+ // file that has been converted to a CommonJS file using a Babel-
44
+ // compatible transform (i.e. "__esModule" has not been set), then set
45
+ // "default" to the CommonJS "module.exports" for node compatibility.
46
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
47
+ mod
48
+ ));
49
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
50
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
51
+ var __async = (__this, __arguments, generator) => {
52
+ return new Promise((resolve4, reject) => {
53
+ var fulfilled = (value) => {
54
+ try {
55
+ step(generator.next(value));
56
+ } catch (e) {
57
+ reject(e);
58
+ }
59
+ };
60
+ var rejected = (value) => {
61
+ try {
62
+ step(generator.throw(value));
63
+ } catch (e) {
64
+ reject(e);
65
+ }
66
+ };
67
+ var step = (x) => x.done ? resolve4(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
68
+ step((generator = generator.apply(__this, __arguments)).next());
69
+ });
70
+ };
71
+ var __await = function(promise, isYieldStar) {
72
+ this[0] = promise;
73
+ this[1] = isYieldStar;
74
+ };
75
+ var __asyncGenerator = (__this, __arguments, generator) => {
76
+ var resume = (k, v, yes, no) => {
77
+ try {
78
+ var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
79
+ Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
80
+ } catch (e) {
81
+ no(e);
82
+ }
83
+ }, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
84
+ return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
85
+ };
86
+ var __yieldStar = (value) => {
87
+ var obj = value[__knownSymbol("asyncIterator")], isAwait = false, method, it = {};
88
+ if (obj == null) {
89
+ obj = value[__knownSymbol("iterator")]();
90
+ method = (k) => it[k] = (x) => obj[k](x);
91
+ } else {
92
+ obj = obj.call(value);
93
+ method = (k) => it[k] = (v) => {
94
+ if (isAwait) {
95
+ isAwait = false;
96
+ if (k === "throw") throw v;
97
+ return v;
98
+ }
99
+ isAwait = true;
100
+ return {
101
+ done: false,
102
+ value: new __await(new Promise((resolve4) => {
103
+ var x = obj[k](v);
104
+ if (!(x instanceof Object)) __typeError("Object expected");
105
+ resolve4(x);
106
+ }), 1)
107
+ };
108
+ };
109
+ }
110
+ return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x) => {
111
+ throw x;
112
+ }, "return" in obj && method("return"), it;
113
+ };
114
+ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
115
+
116
+ // src/index.ts
117
+ var src_exports = {};
118
+ __export(src_exports, {
119
+ AbortControllerShim: () => AbortControllerShim,
120
+ BUNDLED_FILE_NAME: () => BUNDLED_FILE_NAME,
121
+ BUNDLER_DIRECTORY_PATH: () => BUNDLER_DIRECTORY_PATH,
122
+ BUNDLER_NAME: () => BUNDLER_NAME,
123
+ Bundler: () => Bundler,
124
+ ES_6_FOLDER_NAME: () => ES_6_FOLDER_NAME,
125
+ TEMP_FOLDER_NAME: () => TEMP_FOLDER_NAME,
126
+ buildPolyfill: () => buildPolyfill,
127
+ getHtml5TestScript: () => getHtml5TestScript,
128
+ globalObjectPlugin: () => globalObjectPlugin,
129
+ nodePolyfillPlugin: () => nodePolyfillPlugin,
130
+ packDist: () => packDist,
131
+ sassPlugin: () => sassPlugin,
132
+ stopwatch: () => stopwatch,
133
+ svgrPlugin: () => svgrPlugin,
134
+ transpileToES5: () => transpileToES5
135
+ });
136
+ module.exports = __toCommonJS(src_exports);
137
+
138
+ // src/buildPolyfill.ts
139
+ var import_core_js_compat = __toESM(require("core-js-compat"));
140
+ var import_esbuild = require("esbuild");
141
+ function buildPolyfill(_0) {
142
+ return __async(this, arguments, function* ({
143
+ entries = [],
144
+ dest,
145
+ minify = true
146
+ }) {
147
+ try {
148
+ console.info("\x1B[34m%s\x1B[0m", `\u{1F528} Building polyfill into ${dest}`);
149
+ const { list } = (0, import_core_js_compat.default)({
150
+ modules: ["core-js/actual"],
151
+ targets: {
152
+ chrome: "28",
153
+ safari: 5
154
+ }
155
+ });
156
+ const polyfills = createSourceFile([...list.map(prependCoreJsPath), ...entries]);
157
+ yield (0, import_esbuild.build)({
158
+ minify,
159
+ bundle: true,
160
+ stdin: {
161
+ contents: polyfills,
162
+ resolveDir: process.cwd()
163
+ },
164
+ outfile: dest
165
+ });
166
+ console.info("\x1B[32m%s\x1B[0m", `\u2705 Polyfill successfully built into ${dest}`);
167
+ return { dest };
168
+ } catch (error) {
169
+ console.error("\x1B[31m%s\x1B[0m", `\u274C Failed to build polyfill into ${dest}: ${error}`);
170
+ throw error;
171
+ }
172
+ });
173
+ }
174
+ var createSourceFile = (list) => list.map(wrapEntryByRequireCall).join(";\n");
175
+ var prependCoreJsPath = (element) => `core-js/modules/${element}`;
176
+ var wrapEntryByRequireCall = (module2) => `require('${module2}')`;
177
+
178
+ // src/Bundler.ts
179
+ var fs2 = __toESM(require("fs-extra"));
180
+ var path2 = __toESM(require("path"));
181
+ var import_child_process = require("child_process");
182
+ var import_glob = require("glob");
183
+
184
+ // src/utils/index.ts
185
+ var import_core = require("@swc/core");
186
+ var fs = __toESM(require("fs"));
187
+ var path = __toESM(require("path"));
188
+
189
+ // src/IBundler.ts
190
+ var BUNDLER_NAME = "signageOS Assets Bundler";
191
+
192
+ // src/utils/index.ts
193
+ function addLiveReloading(source, dest, origin = "") {
194
+ return __async(this, null, function* () {
195
+ const indexFile = yield fs.promises.readFile(source);
196
+ yield fs.promises.writeFile(
197
+ dest,
198
+ indexFile.toString("utf-8").replace(
199
+ "</body>",
200
+ `<script>new EventSource("${origin}/esbuild").addEventListener('change', () => location.reload())</script></body>`
201
+ )
202
+ );
203
+ });
204
+ }
205
+ function handleBuildMode(ctx) {
206
+ return __async(this, null, function* () {
207
+ console.log("ESBuild is rebuilding...");
208
+ const { metafile } = yield ctx.rebuild();
209
+ if (metafile) {
210
+ fs.promises.writeFile("./meta.json", JSON.stringify(metafile));
211
+ }
212
+ yield ctx.dispose();
213
+ });
214
+ }
215
+ function handleWatchMode(ctx, mode, serveOptions) {
216
+ return __async(this, null, function* () {
217
+ console.info("ESBuild is watching...");
218
+ yield ctx.rebuild();
219
+ yield ctx.watch();
220
+ if (mode === "serve") {
221
+ const { port } = yield ctx.serve(serveOptions);
222
+ console.info(`Serving files on http://localhost:${port}`);
223
+ }
224
+ });
225
+ }
226
+ function printBanner(config) {
227
+ const entries = Object.entries(config);
228
+ const maxKeyLength = Math.max(...entries.map(([key]) => key.length));
229
+ const lines = entries.map(([key, value]) => {
230
+ const paddedKey = key.padEnd(maxKeyLength + 2, " ");
231
+ return `${paddedKey}: ${String(value)}`;
232
+ });
233
+ console.log(`
234
+ ${BUNDLER_NAME}
235
+ ${lines.join("\n")}
236
+ `);
237
+ }
238
+ function resolveConfig({ outdir, parameters, argv }) {
239
+ const mode = argv.includes("--serve") ? "serve" : argv.includes("--watch") ? "watch" : "build";
240
+ const config = {
241
+ environment: parameters.environment,
242
+ NODE_ENV: parameters.NODE_ENV,
243
+ outdir,
244
+ mode,
245
+ typeCheck: !argv.includes("--skipTypeCheck") && mode === "build"
246
+ };
247
+ return config;
248
+ }
249
+ function transpileFiles(files, options) {
250
+ return __async(this, null, function* () {
251
+ const promises6 = [];
252
+ try {
253
+ for (var iter = __forAwait(files), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
254
+ const file = temp.value;
255
+ promises6.push(
256
+ (() => __async(this, null, function* () {
257
+ if (!file.endsWith(".js")) {
258
+ return;
259
+ }
260
+ console.info("\x1B[36m%s\x1B[0m", `\u{1F504} Transpiling the file ${file} to ES5`);
261
+ const source = yield fs.promises.readFile(file);
262
+ const output = yield (0, import_core.transform)(source.toString("utf-8"), options);
263
+ const searchPattern = /return "\\u\{20BB7\}".at\(-2\) !== "\\uD842";/g;
264
+ const paddedReplacePattern = 'return "\\uD842\\uDFB7".at(-2) !== "\\uD842";';
265
+ yield fs.promises.writeFile(file, output.code.replace(searchPattern, paddedReplacePattern));
266
+ }))()
267
+ );
268
+ }
269
+ } catch (temp) {
270
+ error = [temp];
271
+ } finally {
272
+ try {
273
+ more && (temp = iter.return) && (yield temp.call(iter));
274
+ } finally {
275
+ if (error)
276
+ throw error[0];
277
+ }
278
+ }
279
+ yield Promise.all(promises6);
280
+ });
281
+ }
282
+ function transpileToES5(_0) {
283
+ return __async(this, arguments, function* ({ outdir, options = {}, sourceFiles = [] }) {
284
+ const extendedOptions = __spreadValues({
285
+ isModule: false,
286
+ env: {
287
+ targets: {
288
+ chrome: "28",
289
+ safari: 5
290
+ }
291
+ }
292
+ }, options);
293
+ let files;
294
+ if (sourceFiles.length > 0) {
295
+ files = yieldFiles(sourceFiles);
296
+ } else if (outdir) {
297
+ files = walk(outdir);
298
+ } else {
299
+ throw new Error("Unexpected state: neither outdir nor sourceFiles provided.");
300
+ }
301
+ yield transpileFiles(files, extendedOptions);
302
+ });
303
+ }
304
+ function walk(root, p = ".") {
305
+ return __asyncGenerator(this, null, function* () {
306
+ if ((yield new __await(fs.promises.stat(root))).isFile()) {
307
+ yield root;
308
+ return;
309
+ }
310
+ const dir = yield new __await(fs.promises.readdir(path.join(root, p), { withFileTypes: true }));
311
+ for (const e of dir) {
312
+ if (e.isDirectory()) {
313
+ yield* __yieldStar(walk(root, path.join(p, e.name)));
314
+ }
315
+ if (e.isFile()) {
316
+ yield path.join(root, p, e.name);
317
+ }
318
+ }
319
+ });
320
+ }
321
+ function yieldFiles(sourceFiles) {
322
+ return __asyncGenerator(this, null, function* () {
323
+ for (const file of sourceFiles) {
324
+ yield file;
325
+ }
326
+ });
327
+ }
328
+
329
+ // src/Bundler.ts
330
+ var BUNDLED_FILE_NAME = "bundle.js";
331
+ var BUNDLER_DIRECTORY_PATH = "./node_modules/@signageos/lib/dist/ESBuild/";
332
+ var ES_6_FOLDER_NAME = "es6";
333
+ var TEMP_FOLDER_NAME = "temp";
334
+ var Bundler = class {
335
+ constructor({ outdir, parameters, serveOptions, argv }) {
336
+ __publicField(this, "DEFAULT_CHROME_VERSION", 32);
337
+ __publicField(this, "config");
338
+ __publicField(this, "serveOptions", {
339
+ port: 3e3
340
+ });
341
+ // ts generates better types w/o typedef
342
+ // eslint-disable-next-line @typescript-eslint/typedef
343
+ __publicField(this, "esbuildOptions", {
344
+ outdir: "",
345
+ bundle: true,
346
+ format: "iife",
347
+ logLevel: "info",
348
+ sourcemap: true,
349
+ target: "es6",
350
+ treeShaking: true
351
+ });
352
+ const config = resolveConfig({ outdir, parameters, argv });
353
+ printBanner(config);
354
+ this.config = config;
355
+ this.serveOptions = __spreadValues(__spreadValues({}, this.serveOptions), serveOptions);
356
+ this.esbuildOptions = __spreadProps(__spreadValues({}, this.esbuildOptions), { outdir });
357
+ }
358
+ static copyAssetsToEs6Folder(expression = "src/**/*.{sass,svg}") {
359
+ return __async(this, null, function* () {
360
+ try {
361
+ const files = yield (0, import_glob.glob)(expression);
362
+ const copyPromises = files.map((file) => {
363
+ const destinationPath = ES_6_FOLDER_NAME + "/" + file.substr("src/".length);
364
+ return fs2.copy(file, destinationPath);
365
+ });
366
+ yield Promise.all(copyPromises);
367
+ } catch (error) {
368
+ console.error(`Failed to copy assets to ES6 folder: ${error}`);
369
+ throw error;
370
+ }
371
+ });
372
+ }
373
+ // Converts the input to a JSON string.
374
+ static enc(x) {
375
+ try {
376
+ return x === void 0 ? "undefined" : JSON.stringify(x);
377
+ } catch (error) {
378
+ console.error(`Failed to stringify JSON: ${error}`);
379
+ throw error;
380
+ }
381
+ }
382
+ static prepareEs6Folder() {
383
+ return __async(this, null, function* () {
384
+ try {
385
+ yield fs2.mkdir("./" + ES_6_FOLDER_NAME, { recursive: true });
386
+ } catch (error) {
387
+ console.error(`Failed to prepare ES6 folder: ${error}`);
388
+ throw error;
389
+ }
390
+ });
391
+ }
392
+ // Bundles source files to `outdir` and watch & serve them in watch mode
393
+ build(ctx, watchInsteadOfServe = false) {
394
+ return __async(this, null, function* () {
395
+ try {
396
+ let mode = this.config.mode;
397
+ mode = mode === "serve" && watchInsteadOfServe ? "watch" : mode;
398
+ if (mode === "watch" || mode === "serve") {
399
+ const serveOptions = {
400
+ servedir: this.config.outdir,
401
+ port: this.serveOptions.port
402
+ };
403
+ yield handleWatchMode(ctx, mode, serveOptions);
404
+ } else {
405
+ yield handleBuildMode(ctx);
406
+ }
407
+ } catch (error) {
408
+ console.error(`Failed to build: ${error}`);
409
+ throw error;
410
+ }
411
+ });
412
+ }
413
+ compileTypescript() {
414
+ return __async(this, arguments, function* (tscArgs = ["-p", "tsconfig.es6.json"], force) {
415
+ const shouldTypecheck = force || this.config.typeCheck;
416
+ if (!shouldTypecheck) {
417
+ console.log("Skipping typescript compilation because of the --serve or --skipTypeCheck flag.");
418
+ return;
419
+ }
420
+ try {
421
+ const tsc = (0, import_child_process.spawn)("tsc", tscArgs, { stdio: "inherit" });
422
+ yield new Promise((resolve4, reject) => {
423
+ tsc.on("close", (code) => __async(this, null, function* () {
424
+ if (code !== 0) {
425
+ reject(new Error(`tsc process exited with code ${code}`));
426
+ } else {
427
+ resolve4();
428
+ }
429
+ }));
430
+ tsc.on("error", (error) => {
431
+ reject(new Error(`Failed to start tsc process: ${error.message}`));
432
+ });
433
+ });
434
+ } catch (error) {
435
+ console.error(`Failed to compile TypeScript: ${error}`);
436
+ throw error;
437
+ }
438
+ });
439
+ }
440
+ // Transpiles all js files in `outdir` to ES5 with SWC
441
+ transpileToES5() {
442
+ return __async(this, arguments, function* (options = {}) {
443
+ try {
444
+ yield transpileToES5({ outdir: this.config.outdir, options });
445
+ } catch (error) {
446
+ console.error(`Error during transpilation to ES5: ${error}`);
447
+ throw error;
448
+ }
449
+ });
450
+ }
451
+ // Writes index.html file to `outdir` folder and enables hot reload in the serve mode
452
+ writeIndexFile(source, destInOutdir = "index.html", origin = "") {
453
+ return __async(this, null, function* () {
454
+ const dest = path2.resolve(this.config.outdir, destInOutdir);
455
+ try {
456
+ console.info(`Writing index file "${source}" to ${dest}`);
457
+ yield fs2.promises.mkdir(this.config.outdir, { recursive: true });
458
+ if (["watch", "serve"].includes(this.config.mode)) {
459
+ yield addLiveReloading(source, dest, origin);
460
+ } else {
461
+ yield fs2.promises.copyFile(source, dest);
462
+ }
463
+ } catch (error) {
464
+ console.error(`Failed to write index file: ${error}`);
465
+ throw error;
466
+ }
467
+ });
468
+ }
469
+ cleanOutDir() {
470
+ return __async(this, arguments, function* (preservedFiles = [BUNDLED_FILE_NAME, BUNDLED_FILE_NAME + ".map"]) {
471
+ try {
472
+ let files = [];
473
+ if (yield fs2.pathExists(this.config.outdir)) {
474
+ files = yield fs2.readdir(this.config.outdir);
475
+ }
476
+ for (const file of files) {
477
+ if (!preservedFiles.includes(file)) {
478
+ yield fs2.rm(path2.join(this.config.outdir, file), { recursive: true, force: true });
479
+ }
480
+ }
481
+ } catch (error) {
482
+ console.error(`Failed to clean dist folder: ${error}`);
483
+ throw error;
484
+ }
485
+ });
486
+ }
487
+ };
488
+
489
+ // src/html5test/html5TestScript.ts
490
+ var fs3 = __toESM(require("fs"));
491
+ var swc = __toESM(require("@swc/core"));
492
+
493
+ // src/html5test/loadWhichBrowser.ts
494
+ function loadWhichBrowser(cb) {
495
+ var callback = cb;
496
+ var p = [], w = window, d = document, e = f = 0;
497
+ p.push("ua=" + encodeURIComponent(navigator.userAgent));
498
+ e |= w.ActiveXObject ? 1 : 0;
499
+ e |= w.opera ? 2 : 0;
500
+ e |= w.chrome ? 4 : 0;
501
+ e |= "getBoxObjectFor" in d || "mozInnerScreenX" in w ? 8 : 0;
502
+ e |= "WebKitCSSMatrix" in w || "WebKitPoint" in w || "webkitStorageInfo" in w || "webkitURL" in w ? 16 : 0;
503
+ e |= e & 16 && {}.toString.toString().indexOf("\n") === -1 ? 32 : 0;
504
+ p.push("e=" + e);
505
+ f |= "sandbox" in d.createElement("iframe") ? 1 : 0;
506
+ f |= "WebSocket" in w ? 2 : 0;
507
+ f |= w.Worker ? 4 : 0;
508
+ f |= w.applicationCache ? 8 : 0;
509
+ f |= w.history && history.pushState ? 16 : 0;
510
+ f |= d.documentElement.webkitRequestFullScreen ? 32 : 0;
511
+ f |= "FileReader" in w ? 64 : 0;
512
+ p.push("f=" + f);
513
+ p.push("r=" + Math.random().toString(36).substring(7));
514
+ p.push("w=" + screen.width);
515
+ p.push("h=" + screen.height);
516
+ var servers = ["api.whichbrowser.net", "backup.whichbrowser.net"];
517
+ var timeout = null;
518
+ function load() {
519
+ if (typeof WhichBrowser != "undefined") {
520
+ return;
521
+ }
522
+ var server = servers.shift();
523
+ if (server) {
524
+ var script = document.createElement("script");
525
+ script.src = "https://" + server + "/rel/detect.js?" + p.join("&");
526
+ document.getElementsByTagName("head")[0].appendChild(script);
527
+ wait();
528
+ }
529
+ }
530
+ function wait() {
531
+ if (!timeout) {
532
+ timeout = window.setTimeout(load, 3e3);
533
+ }
534
+ if (typeof WhichBrowser == "undefined") {
535
+ window.setTimeout(wait, 100);
536
+ } else {
537
+ window.clearTimeout(timeout);
538
+ callback();
539
+ }
540
+ }
541
+ load();
542
+ }
543
+
544
+ // src/html5test/html5TestScript.ts
545
+ var getHtml5TestScript = (enginePath = "./node_modules/html5test/scripts/9/engine.js") => __async(void 0, null, function* () {
546
+ const engine = yield fs3.promises.readFile(enginePath).then((b) => b.toString());
547
+ const script = `
548
+ (function () {
549
+ var resolve = window.__SOS_HTML5TEST_RESOLVE;
550
+ delete window.__SOS_HTML5TEST_RESOLVE;
551
+
552
+ if(typeof resolve === "function") {
553
+ ${/* This script can't run in strict mode, so this prevent undeclared variables to be assigned to window object */
554
+ ""}
555
+ var f, Test, Test9, passed;
556
+
557
+ ${loadWhichBrowser.toString()}
558
+ ${engine}
559
+
560
+ loadWhichBrowser(function () {
561
+ ${/* WhichBrowser is injected be external script so it need to stay on window */
562
+ ""}
563
+ window.Browsers = new window.WhichBrowser({
564
+ useFeatures: true,
565
+ detectCamouflage: true,
566
+ });
567
+
568
+ new Test(function (result) {
569
+ resolve(result);
570
+ });
571
+ });
572
+ }
573
+ })();
574
+ `;
575
+ const minified = yield swc.transform(script, { minify: false, jsc: { target: "es5" } });
576
+ return Bundler.enc(minified.code);
577
+ });
578
+
579
+ // src/pack.ts
580
+ var fs4 = __toESM(require("fs-extra"));
581
+ var path3 = __toESM(require("path"));
582
+ var import_node_child_process = require("child_process");
583
+ var util = __toESM(require("util"));
584
+ var tmp = __toESM(require("tmp"));
585
+ var tar = __toESM(require("tar"));
586
+ var execPromise = util.promisify(import_node_child_process.exec);
587
+ var packDist = (options) => __async(void 0, null, function* () {
588
+ if (options.environment === "dev") {
589
+ const timestampNumber = (/* @__PURE__ */ new Date()).toISOString().replace(/[^\d]/gi, "").substr(0, 14);
590
+ const devVersion = (options.getVersion ? options.getVersion() : "99.0.0-dev") + "." + timestampNumber;
591
+ const tmpDir = tmp.dirSync().name;
592
+ yield fs4.copy(path3.join(options.rootPath, "dist"), path3.join(tmpDir, "package", "dist"));
593
+ yield fs4.copy(path3.join(options.rootPath, "README.md"), path3.join(tmpDir, "package", "README.md"));
594
+ const configPath = path3.join(options.rootPath, "package.json");
595
+ const configContents = yield fs4.readJson(configPath);
596
+ configContents.version = devVersion;
597
+ yield fs4.writeJson(path3.join(tmpDir, "package", "package.json"), configContents, { spaces: 2 });
598
+ const tarballDir = path3.join(options.packagesPath, options.name, devVersion);
599
+ const tarballFileName = options.name.replace(/^@/, "").replace(/\//g, "-") + "-" + devVersion + ".tgz";
600
+ yield fs4.ensureDir(tarballDir);
601
+ yield tar.c(
602
+ {
603
+ gzip: true,
604
+ file: path3.join(tarballDir, tarballFileName),
605
+ cwd: tmpDir
606
+ },
607
+ ["package"]
608
+ );
609
+ yield packDependencies(options);
610
+ console.info("Tarball release " + tarballFileName);
611
+ }
612
+ });
613
+ function packDependencies(options) {
614
+ return __async(this, null, function* () {
615
+ const configLockPath = path3.join(options.rootPath, "package-lock.json");
616
+ const configLockContents = yield fs4.readJson(configLockPath);
617
+ const dependencies = options.dependencies || [];
618
+ for (const dependency of dependencies) {
619
+ const dependencyVersion = "dependencies" in configLockContents ? (
620
+ // lockfileVersion 0 and 1
621
+ configLockContents.dependencies[dependency].version
622
+ ) : (
623
+ // lockfileVersion 2 and 3
624
+ configLockContents.packages["node_modules/" + dependency].version
625
+ );
626
+ const dependencyVersionPath = path3.join(options.packagesPath, dependency, dependencyVersion);
627
+ if (!(yield fs4.pathExists(dependencyVersionPath))) {
628
+ const { stdout } = yield execPromise(`npm pack ${dependency}@${dependencyVersionPath}`);
629
+ const fileName = stdout.trim();
630
+ yield fs4.ensureDir(dependencyVersionPath);
631
+ yield fs4.move(path3.join(options.rootPath, fileName), path3.join(dependencyVersionPath, fileName));
632
+ }
633
+ }
634
+ });
635
+ }
636
+
637
+ // src/plugins/sass.ts
638
+ var path4 = __toESM(require("path"));
639
+ var fs5 = __toESM(require("fs"));
640
+ var import_sass = require("sass");
641
+ var import_css_tree = require("css-tree");
642
+ var import_crypto = require("crypto");
643
+ var sassPlugin = () => ({
644
+ name: "sass",
645
+ setup(build2) {
646
+ return __async(this, null, function* () {
647
+ build2.onResolve({ filter: /\.sass$/ }, (args) => ({
648
+ path: path4.resolve(args.resolveDir, args.path),
649
+ namespace: "sass"
650
+ }));
651
+ build2.onLoad({ filter: /.*/, namespace: "sass" }, (args) => __async(this, null, function* () {
652
+ const compiled = yield (0, import_sass.compileStringAsync)((yield fs5.promises.readFile(args.path)).toString("utf-8"), {
653
+ syntax: "indented",
654
+ url: new URL("file://" + args.path)
655
+ });
656
+ if (args.path.endsWith(".module.sass")) {
657
+ const ast = (0, import_css_tree.parse)(compiled.css);
658
+ const classMap = /* @__PURE__ */ new Map();
659
+ (0, import_css_tree.walk)(ast, {
660
+ visit: "ClassSelector",
661
+ enter(node) {
662
+ const transformed = `m-${node.name}-${(0, import_crypto.createHash)("md5").update(args.path).digest("hex").slice(0, 10)}`;
663
+ classMap.set(node.name, transformed);
664
+ node.name = transformed;
665
+ }
666
+ });
667
+ return {
668
+ contents: `
669
+ import "data:text/css,${encodeURI((0, import_css_tree.generate)(ast))}";
670
+ const result = ${JSON.stringify(Object.fromEntries([...Array.from(classMap)].map(([k, v]) => [k, v])))};
671
+ export default result;
672
+ `
673
+ };
674
+ } else {
675
+ return {
676
+ contents: compiled.css,
677
+ loader: "css"
678
+ };
679
+ }
680
+ }));
681
+ });
682
+ }
683
+ });
684
+
685
+ // src/plugins/svgr.ts
686
+ var import_core2 = require("@svgr/core");
687
+ var fs6 = __toESM(require("fs"));
688
+ var path5 = __toESM(require("path"));
689
+ var svgrPlugin = () => ({
690
+ name: "svgr",
691
+ setup(build2) {
692
+ return __async(this, null, function* () {
693
+ build2.onResolve({ filter: /\.svg$/ }, (args) => ({
694
+ path: path5.resolve(args.resolveDir, args.path),
695
+ namespace: "svgr"
696
+ }));
697
+ build2.onLoad({ filter: /.*/, namespace: "svgr" }, (args) => __async(this, null, function* () {
698
+ const svg = (yield fs6.promises.readFile(args.path)).toString("utf-8");
699
+ const fileName = path5.basename(args.path, ".svg");
700
+ const componentName = fileName.charAt(0).toUpperCase() + fileName.slice(1);
701
+ const contents = yield (0, import_core2.transform)(svg, { icon: true, plugins: ["@svgr/plugin-jsx"] }, { componentName });
702
+ return {
703
+ contents,
704
+ loader: "jsx",
705
+ resolveDir: process.cwd()
706
+ };
707
+ }));
708
+ });
709
+ }
710
+ });
711
+
712
+ // src/plugins/nodePolyfillPlugin.ts
713
+ var import_module = require("module");
714
+ var resolvePath = (path6) => {
715
+ const require2 = typeof require !== "undefined" ? require : (0, import_module.createRequire)(typeof __filename !== "undefined" ? __filename : process.cwd());
716
+ return require2.resolve(path6);
717
+ };
718
+ var nodePolyfillPlugin = () => ({
719
+ name: "node-polyfill",
720
+ setup: ({ initialOptions }) => {
721
+ var _a;
722
+ const nodeShimPath = resolvePath("@signageos/lib-bundler/shims/node");
723
+ const noopPath = resolvePath("@signageos/lib-bundler/alias/noop");
724
+ initialOptions.inject = [...(_a = initialOptions.inject) != null ? _a : [], nodeShimPath];
725
+ initialOptions.alias = __spreadProps(__spreadValues({}, initialOptions.alias), {
726
+ assert: "assert",
727
+ child_process: noopPath,
728
+ crypto: "crypto-browserify",
729
+ os: "os-browserify/browser",
730
+ path: "path-browserify",
731
+ net: noopPath,
732
+ querystring: "querystring-es3",
733
+ stream: "stream-browserify",
734
+ util: "util",
735
+ events: "events",
736
+ url: "url",
737
+ buffer: "buffer"
738
+ });
739
+ }
740
+ });
741
+
742
+ // src/plugins/globalObjectPlugin.ts
743
+ var globalObjectPlugin = () => ({
744
+ name: "global-object-plugin",
745
+ setup(build2) {
746
+ build2.onResolve({ filter: /^virtual-global-object$/ }, (args) => ({
747
+ path: args.path,
748
+ namespace: "global-object"
749
+ }));
750
+ build2.onLoad({ filter: /.*/, namespace: "global-object" }, () => ({
751
+ contents: `
752
+ export default typeof globalThis !== 'undefined'
753
+ ? globalThis
754
+ : typeof global !== 'undefined'
755
+ ? global
756
+ : typeof window !== 'undefined'
757
+ ? window
758
+ : typeof self !== 'undefined'
759
+ ? self
760
+ : new Function('return this')();
761
+ `,
762
+ loader: "js"
763
+ }));
764
+ build2.initialOptions.inject = build2.initialOptions.inject || [];
765
+ build2.initialOptions.inject.push("virtual-global-object");
766
+ }
767
+ });
768
+
769
+ // src/utils/stopwatch.ts
770
+ function stopwatch(label, cb) {
771
+ return __async(this, null, function* () {
772
+ const timeLabel = "\u{1F3C1} " + label;
773
+ console.info("\u{1F680} " + label);
774
+ console.time(timeLabel);
775
+ const result = Array.isArray(cb) ? yield Promise.all(cb.map((x) => typeof x === "function" ? x() : x)) : yield typeof cb === "function" ? cb() : cb;
776
+ console.timeEnd(timeLabel);
777
+ return result;
778
+ });
779
+ }
780
+
781
+ // src/polyfills/AbortController/AbortController.ts
782
+ var AbortControllerShim = (global) => {
783
+ const SECRET = {};
784
+ class AbortSignal extends global.EventTarget {
785
+ constructor(secret) {
786
+ super();
787
+ __publicField(this, "_reason");
788
+ __publicField(this, "_onabort", null);
789
+ if (secret !== SECRET) {
790
+ throw new global.TypeError("Illegal constructor.");
791
+ }
792
+ }
793
+ get aborted() {
794
+ return this._reason !== void 0;
795
+ }
796
+ get reason() {
797
+ return this._reason;
798
+ }
799
+ set onabort(callback) {
800
+ if (this._onabort) {
801
+ this.removeEventListener("abort", this._onabort);
802
+ }
803
+ this._onabort = callback;
804
+ this.addEventListener("abort", callback, { once: true });
805
+ }
806
+ get onabort() {
807
+ return this._onabort;
808
+ }
809
+ addEventListener(type, callback, options) {
810
+ return super.addEventListener(
811
+ type,
812
+ callback,
813
+ typeof options === "boolean" ? { capture: options, once: true } : __spreadProps(__spreadValues({}, options), { once: true })
814
+ );
815
+ }
816
+ throwIfAborted() {
817
+ if (this._reason !== void 0) {
818
+ throw this._reason;
819
+ }
820
+ }
821
+ __dispatchAbort(reason) {
822
+ if (this._reason) {
823
+ return;
824
+ }
825
+ if (reason === void 0) {
826
+ reason = new global.DOMException("The operation was aborted.", "AbortError");
827
+ }
828
+ this._reason = reason;
829
+ this.dispatchEvent(new global.Event("abort"));
830
+ }
831
+ static abort(reason) {
832
+ const controller = new AbortController();
833
+ controller.abort(reason);
834
+ return controller.signal;
835
+ }
836
+ // This methods is not spec complaint, because it requires WeakSet.
837
+ // https://github.com/zloirock/core-js/issues/445
838
+ static any(signals) {
839
+ const controller = new AbortController();
840
+ for (const s of signals) {
841
+ const onAbort = () => {
842
+ controller.abort(s.reason);
843
+ s.removeEventListener("abort", onAbort);
844
+ };
845
+ s.addEventListener("abort", onAbort, { once: true });
846
+ }
847
+ return controller.signal;
848
+ }
849
+ static timeout(timeoutMs) {
850
+ if (timeoutMs < 0 || timeoutMs > Number.MAX_SAFE_INTEGER) {
851
+ throw new global.TypeError("AbortSignal.timeout: Argument 1 is out of range for unsigned long long.");
852
+ }
853
+ const controller = new AbortController();
854
+ global.setTimeout(() => {
855
+ controller.abort(new global.DOMException("The operation timed out.", "TimeoutError"));
856
+ }, timeoutMs);
857
+ return controller.signal;
858
+ }
859
+ }
860
+ class AbortController {
861
+ constructor() {
862
+ __publicField(this, "signal");
863
+ this.signal = new AbortSignal(SECRET);
864
+ }
865
+ abort(reason) {
866
+ this.signal.__dispatchAbort(reason);
867
+ }
868
+ }
869
+ return { AbortController, AbortSignal };
870
+ };
871
+ // Annotate the CommonJS export names for ESM import in node:
872
+ 0 && (module.exports = {
873
+ AbortControllerShim,
874
+ BUNDLED_FILE_NAME,
875
+ BUNDLER_DIRECTORY_PATH,
876
+ BUNDLER_NAME,
877
+ Bundler,
878
+ ES_6_FOLDER_NAME,
879
+ TEMP_FOLDER_NAME,
880
+ buildPolyfill,
881
+ getHtml5TestScript,
882
+ globalObjectPlugin,
883
+ nodePolyfillPlugin,
884
+ packDist,
885
+ sassPlugin,
886
+ stopwatch,
887
+ svgrPlugin,
888
+ transpileToES5
889
+ });