forked from mozilla/pdf.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
2454 lines (2205 loc) · 68.3 KB
/
gulpfile.js
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2016 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-env node */
"use strict";
const autoprefixer = require("autoprefixer");
const postcssDirPseudoClass = require("postcss-dir-pseudo-class");
const fs = require("fs");
const gulp = require("gulp");
const postcss = require("gulp-postcss");
const rename = require("gulp-rename");
const replace = require("gulp-replace");
const { mkdirp } = require("mkdirp");
const path = require("path");
const rimraf = require("rimraf");
const stream = require("stream");
const exec = require("child_process").exec;
const spawn = require("child_process").spawn;
const spawnSync = require("child_process").spawnSync;
const streamqueue = require("streamqueue");
const merge = require("merge-stream");
const zip = require("gulp-zip");
const webpack2 = require("webpack");
const webpackStream = require("webpack-stream");
const Vinyl = require("vinyl");
const vfs = require("vinyl-fs");
const through = require("through2");
const BUILD_DIR = "build/";
const L10N_DIR = "l10n/";
const TEST_DIR = "test/";
const EXTENSION_SRC_DIR = "extensions/";
const BASELINE_DIR = BUILD_DIR + "baseline/";
const MOZCENTRAL_BASELINE_DIR = BUILD_DIR + "mozcentral.baseline/";
const GENERIC_DIR = BUILD_DIR + "generic/";
const GENERIC_LEGACY_DIR = BUILD_DIR + "generic-legacy/";
const COMPONENTS_DIR = BUILD_DIR + "components/";
const COMPONENTS_LEGACY_DIR = BUILD_DIR + "components-legacy/";
const IMAGE_DECODERS_DIR = BUILD_DIR + "image_decoders/";
const IMAGE_DECODERS_LEGACY_DIR = BUILD_DIR + "image_decoders-legacy/";
const DEFAULT_PREFERENCES_DIR = BUILD_DIR + "default_preferences/";
const MINIFIED_DIR = BUILD_DIR + "minified/";
const MINIFIED_LEGACY_DIR = BUILD_DIR + "minified-legacy/";
const JSDOC_BUILD_DIR = BUILD_DIR + "jsdoc/";
const GH_PAGES_DIR = BUILD_DIR + "gh-pages/";
const SRC_DIR = "src/";
const DIST_DIR = BUILD_DIR + "dist/";
const TYPES_DIR = BUILD_DIR + "types/";
const TMP_DIR = BUILD_DIR + "tmp/";
const TYPESTEST_DIR = BUILD_DIR + "typestest/";
const COMMON_WEB_FILES = [
"web/images/*.{png,svg,gif}",
"web/debugger.{css,js}",
];
const MOZCENTRAL_DIFF_FILE = "mozcentral.diff";
const DIST_REPO_URL = "https://github.com/mozilla/pdfjs-dist";
const builder = require("./external/builder/builder.js");
const CONFIG_FILE = "pdfjs.config";
const config = JSON.parse(fs.readFileSync(CONFIG_FILE).toString());
const ENV_TARGETS = [
"last 2 versions",
"Chrome >= 88",
"Firefox ESR",
"Safari >= 14.1",
"Node >= 16",
"> 1%",
"not IE > 0",
"not dead",
];
// Default Autoprefixer config used for generic, components, minified-pre
const AUTOPREFIXER_CONFIG = {
overrideBrowserslist: ENV_TARGETS,
};
// Default Babel targets used for generic, components, minified-pre
const BABEL_TARGETS = ENV_TARGETS.join(", ");
const DEFINES = Object.freeze({
SKIP_BABEL: true,
TESTING: undefined,
// The main build targets:
GENERIC: false,
MOZCENTRAL: false,
GECKOVIEW: false,
CHROME: false,
MINIFIED: false,
COMPONENTS: false,
LIB: false,
IMAGE_DECODERS: false,
});
function transform(charEncoding, transformFunction) {
return through.obj(function (vinylFile, enc, done) {
const transformedFile = vinylFile.clone();
transformedFile.contents = Buffer.from(
transformFunction(transformedFile.contents),
charEncoding
);
done(null, transformedFile);
});
}
function safeSpawnSync(command, parameters, options) {
// Execute all commands in a shell.
options = options || {};
options.shell = true;
// `options.shell = true` requires parameters to be quoted.
parameters = parameters.map(param => {
if (!/[\s`~!#$*(){[|\\;'"<>?]/.test(param)) {
return param;
}
return '"' + param.replaceAll(/([$\\"`])/g, "\\$1") + '"';
});
const result = spawnSync(command, parameters, options);
if (result.status !== 0) {
console.log(
'Error: command "' +
command +
'" with parameters "' +
parameters +
'" exited with code ' +
result.status
);
process.exit(result.status);
}
return result;
}
function startNode(args, options) {
// Node.js decreased the maximum header size from 80 KB to 8 KB in newer
// releases, which is not sufficient for some of our reference test files
// (such as `issue6360.pdf`), so we need to restore this value. Note that
// this argument needs to be before all other arguments as it needs to be
// passed to the Node.js process itself and not to the script that it runs.
args.unshift("--max-http-header-size=80000");
return spawn("node", args, options);
}
function createStringSource(filename, content) {
const source = stream.Readable({ objectMode: true });
source._read = function () {
this.push(
new Vinyl({
path: filename,
contents: Buffer.from(content),
})
);
this.push(null);
};
return source;
}
function createWebpackConfig(
defines,
output,
{
disableVersionInfo = false,
disableSourceMaps = false,
disableLicenseHeader = false,
defaultPreferencesDir = null,
} = {}
) {
const versionInfo = !disableVersionInfo
? getVersionJSON()
: { version: 0, commit: 0 };
const bundleDefines = builder.merge(defines, {
BUNDLE_VERSION: versionInfo.version,
BUNDLE_BUILD: versionInfo.commit,
TESTING:
defines.TESTING !== undefined
? defines.TESTING
: process.env.TESTING === "true",
DEFAULT_PREFERENCES: defaultPreferencesDir
? getDefaultPreferences(defaultPreferencesDir)
: {},
DIALOG_POLYFILL_CSS:
defines.GENERIC && !defines.SKIP_BABEL ? getDialogPolyfillCSS() : "",
});
const licenseHeaderLibre = fs
.readFileSync("./src/license_header_libre.js")
.toString();
const enableSourceMaps =
!bundleDefines.MOZCENTRAL &&
!bundleDefines.CHROME &&
!bundleDefines.LIB &&
!bundleDefines.TESTING &&
!disableSourceMaps;
const skipBabel = bundleDefines.SKIP_BABEL;
// `core-js` (see https://github.com/zloirock/core-js/issues/514), and
// `src/core/{glyphlist,unicode}.js` (Babel is too slow for those when
// source-maps are enabled) should be excluded from processing.
const babelExcludes = ["node_modules[\\\\\\/]core-js"];
if (enableSourceMaps) {
babelExcludes.push("src[\\\\\\/]core[\\\\\\/](glyphlist|unicode)");
}
const babelExcludeRegExp = new RegExp(`(${babelExcludes.join("|")})`);
const babelPlugins = ["@babel/plugin-transform-modules-commonjs"];
const plugins = [];
if (!disableLicenseHeader) {
plugins.push(
new webpack2.BannerPlugin({ banner: licenseHeaderLibre, raw: true })
);
}
const experiments =
output.library?.type === "module" ? { outputModule: true } : undefined;
// Required to expose e.g., the `window` object.
output.globalObject = "globalThis";
const basicAlias = {
pdfjs: "src",
"pdfjs-web": "web",
"pdfjs-lib": "web/pdfjs",
"pdfjs-fitCurve": "src/display/editor/fit_curve",
};
const viewerAlias = {
"web-annotation_editor_params": "web/annotation_editor_params.js",
"web-com": "",
"web-pdf_attachment_viewer": "web/pdf_attachment_viewer.js",
"web-pdf_cursor_tools": "web/pdf_cursor_tools.js",
"web-pdf_document_properties": "web/pdf_document_properties.js",
"web-pdf_find_bar": "web/pdf_find_bar.js",
"web-pdf_layer_viewer": "web/pdf_layer_viewer.js",
"web-pdf_outline_viewer": "web/pdf_outline_viewer.js",
"web-pdf_presentation_mode": "web/pdf_presentation_mode.js",
"web-pdf_sidebar": "web/pdf_sidebar.js",
"web-pdf_sidebar_resizer": "web/pdf_sidebar_resizer.js",
"web-pdf_thumbnail_viewer": "web/pdf_thumbnail_viewer.js",
"web-print_service": "",
"web-secondary_toolbar": "web/secondary_toolbar.js",
"web-toolbar": "web/toolbar.js",
};
if (bundleDefines.CHROME) {
viewerAlias["web-com"] = "web/chromecom.js";
viewerAlias["web-print_service"] = "web/pdf_print_service.js";
} else if (bundleDefines.GENERIC) {
viewerAlias["web-com"] = "web/genericcom.js";
viewerAlias["web-print_service"] = "web/pdf_print_service.js";
} else if (bundleDefines.MOZCENTRAL) {
if (bundleDefines.GECKOVIEW) {
const gvAlias = {
"web-toolbar": "web/toolbar-geckoview.js",
};
for (const key in viewerAlias) {
viewerAlias[key] = gvAlias[key] || "web/stubs-geckoview.js";
}
} else {
viewerAlias["web-print_service"] = "web/firefox_print_service.js";
}
viewerAlias["web-com"] = "web/firefoxcom.js";
}
const alias = { ...basicAlias, ...viewerAlias };
for (const key in alias) {
alias[key] = path.join(__dirname, alias[key]);
}
return {
mode: "none",
experiments,
output,
performance: {
hints: false, // Disable messages about larger file sizes.
},
plugins,
resolve: {
alias,
},
devtool: enableSourceMaps ? "source-map" : undefined,
module: {
rules: [
{
loader: "babel-loader",
exclude: babelExcludeRegExp,
options: {
presets: skipBabel ? undefined : ["@babel/preset-env"],
plugins: babelPlugins,
targets: BABEL_TARGETS,
},
},
{
loader: path.join(__dirname, "external/webpack/pdfjsdev-loader.js"),
options: {
rootPath: __dirname,
saveComments: false,
defines: bundleDefines,
},
},
],
},
// Avoid shadowing actual Node.js variables with polyfills, by disabling
// polyfills/mocks - https://webpack.js.org/configuration/node/
node: false,
};
}
function webpack2Stream(webpackConfig) {
// Replacing webpack1 to webpack2 in the webpack-stream.
return webpackStream(webpackConfig, webpack2);
}
function getVersionJSON() {
return JSON.parse(fs.readFileSync(BUILD_DIR + "version.json").toString());
}
function checkChromePreferencesFile(chromePrefsPath, webPrefs) {
const chromePrefs = JSON.parse(fs.readFileSync(chromePrefsPath).toString());
const chromePrefsKeys = Object.keys(chromePrefs.properties).filter(key => {
const description = chromePrefs.properties[key].description;
// Deprecated keys are allowed in the managed preferences file.
// The code maintained is responsible for adding migration logic to
// extensions/chromium/options/migration.js and web/chromecom.js .
return !description || !description.startsWith("DEPRECATED.");
});
chromePrefsKeys.sort();
const webPrefsKeys = Object.keys(webPrefs);
webPrefsKeys.sort();
if (webPrefsKeys.length !== chromePrefsKeys.length) {
console.log("Warning: Pref objects doesn't have the same length.");
return false;
}
let ret = true;
for (let i = 0, ii = webPrefsKeys.length; i < ii; i++) {
const value = webPrefsKeys[i];
if (chromePrefsKeys[i] !== value) {
ret = false;
console.log(
`Warning: not the same keys: ${chromePrefsKeys[i]} !== ${value}`
);
} else if (chromePrefs.properties[value].default !== webPrefs[value]) {
ret = false;
console.log(
`Warning: not the same values (for "${value}"): ` +
`${chromePrefs.properties[value].default} !== ${webPrefs[value]}`
);
}
}
return ret;
}
function replaceWebpackRequire() {
// Produced bundles can be rebundled again, avoid collisions (e.g. in api.js)
// by renaming __webpack_require__ to something else.
return replace("__webpack_require__", "__w_pdfjs_require__");
}
function replaceNonWebpackImport() {
return replace("__non_webpack_import__", "import");
}
function replaceJSRootName(amdName, jsName) {
// Saving old-style JS module name.
return replace(
'root["' + amdName + '"] = factory()',
'root["' + amdName + '"] = root.' + jsName + " = factory()"
);
}
function createMainBundle(defines) {
const mainAMDName = "pdfjs-dist/build/pdf";
const mainOutputName = "pdf.js";
const mainFileConfig = createWebpackConfig(defines, {
filename: mainOutputName,
library: mainAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
});
return gulp
.src("./src/pdf.js")
.pipe(webpack2Stream(mainFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(replaceJSRootName(mainAMDName, "pdfjsLib"));
}
function createScriptingBundle(defines, extraOptions = undefined) {
const scriptingAMDName = "pdfjs-dist/build/pdf.scripting";
const scriptingOutputName = "pdf.scripting.js";
const scriptingFileConfig = createWebpackConfig(
defines,
{
filename: scriptingOutputName,
library: scriptingAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
},
extraOptions
);
return gulp
.src("./src/pdf.scripting.js")
.pipe(webpack2Stream(scriptingFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(
replace(
'root["' + scriptingAMDName + '"] = factory()',
"root.pdfjsScripting = factory()"
)
);
}
function createSandboxExternal(defines) {
const preprocessor2 = require("./external/builder/preprocessor2.js");
const licenseHeader = fs.readFileSync("./src/license_header.js").toString();
const ctx = {
saveComments: false,
defines,
};
return gulp
.src("./src/pdf.sandbox.external.js")
.pipe(rename("pdf.sandbox.external.sys.mjs"))
.pipe(
transform("utf8", content => {
content = preprocessor2.preprocessPDFJSCode(ctx, content);
return `${licenseHeader}\n${content}`;
})
);
}
function createTemporaryScriptingBundle(defines, extraOptions = undefined) {
return createScriptingBundle(defines, {
disableVersionInfo: !!(extraOptions && extraOptions.disableVersionInfo),
disableSourceMaps: true,
disableLicenseHeader: true,
}).pipe(gulp.dest(TMP_DIR));
}
function createSandboxBundle(defines, extraOptions = undefined) {
const sandboxAMDName = "pdfjs-dist/build/pdf.sandbox";
const sandboxOutputName = "pdf.sandbox.js";
const scriptingPath = TMP_DIR + "pdf.scripting.js";
// Insert the source as a string to be `eval`-ed in the sandbox.
const sandboxDefines = builder.merge(defines, {
PDF_SCRIPTING_JS_SOURCE: fs.readFileSync(scriptingPath).toString(),
});
fs.unlinkSync(scriptingPath);
const sandboxFileConfig = createWebpackConfig(
sandboxDefines,
{
filename: sandboxOutputName,
library: sandboxAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
},
extraOptions
);
return gulp
.src("./src/pdf.sandbox.js")
.pipe(webpack2Stream(sandboxFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(replaceJSRootName(sandboxAMDName, "pdfjsSandbox"));
}
function createWorkerBundle(defines) {
const workerAMDName = "pdfjs-dist/build/pdf.worker";
const workerOutputName = "pdf.worker.js";
const workerFileConfig = createWebpackConfig(defines, {
filename: workerOutputName,
library: workerAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
});
return gulp
.src("./src/pdf.worker.js")
.pipe(webpack2Stream(workerFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(replaceJSRootName(workerAMDName, "pdfjsWorker"));
}
function createWebBundle(defines, options) {
const viewerOutputName = "viewer.js";
const viewerFileConfig = createWebpackConfig(
defines,
{
filename: viewerOutputName,
},
{
defaultPreferencesDir: options.defaultPreferencesDir,
}
);
return gulp
.src("./web/viewer.js")
.pipe(webpack2Stream(viewerFileConfig))
.pipe(replaceNonWebpackImport());
}
function createGVWebBundle(defines, options) {
const viewerOutputName = "viewer-geckoview.js";
defines = builder.merge(defines, { GECKOVIEW: true });
const viewerFileConfig = createWebpackConfig(
defines,
{
filename: viewerOutputName,
},
{
defaultPreferencesDir: options.defaultPreferencesDir,
}
);
return gulp
.src("./web/viewer-geckoview.js")
.pipe(webpack2Stream(viewerFileConfig))
.pipe(replaceNonWebpackImport());
}
function createComponentsBundle(defines) {
const componentsAMDName = "pdfjs-dist/web/pdf_viewer";
const componentsOutputName = "pdf_viewer.js";
const componentsFileConfig = createWebpackConfig(defines, {
filename: componentsOutputName,
library: componentsAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
});
return gulp
.src("./web/pdf_viewer.component.js")
.pipe(webpack2Stream(componentsFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(replaceJSRootName(componentsAMDName, "pdfjsViewer"));
}
function createImageDecodersBundle(defines) {
const imageDecodersAMDName = "pdfjs-dist/image_decoders/pdf.image_decoders";
const imageDecodersOutputName = "pdf.image_decoders.js";
const componentsFileConfig = createWebpackConfig(defines, {
filename: imageDecodersOutputName,
library: imageDecodersAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
});
return gulp
.src("./src/pdf.image_decoders.js")
.pipe(webpack2Stream(componentsFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(replaceJSRootName(imageDecodersAMDName, "pdfjsImageDecoders"));
}
function createFitCurveBundle(defines) {
const fitCurveOutputName = "fit_curve.js";
const fitCurveFileConfig = createWebpackConfig(
defines,
{
filename: fitCurveOutputName,
library: {
type: "module",
},
},
{
disableVersionInfo: true,
}
);
return gulp
.src("src/display/editor/fit_curve.js")
.pipe(webpack2Stream(fitCurveFileConfig));
}
function createCMapBundle() {
return gulp.src(["external/bcmaps/*.bcmap", "external/bcmaps/LICENSE"], {
base: "external/bcmaps",
});
}
function createStandardFontBundle() {
return gulp.src(
[
"external/standard_fonts/*.pfb",
"external/standard_fonts/*.ttf",
"external/standard_fonts/LICENSE_FOXIT",
"external/standard_fonts/LICENSE_LIBERATION",
],
{
base: "external/standard_fonts",
}
);
}
function checkFile(filePath) {
try {
const stat = fs.lstatSync(filePath);
return stat.isFile();
} catch (e) {
return false;
}
}
function checkDir(dirPath) {
try {
const stat = fs.lstatSync(dirPath);
return stat.isDirectory();
} catch (e) {
return false;
}
}
function replaceInFile(filePath, find, replacement) {
let content = fs.readFileSync(filePath).toString();
content = content.replace(find, replacement);
fs.writeFileSync(filePath, content);
}
function getTempFile(prefix, suffix) {
mkdirp.sync(BUILD_DIR + "tmp/");
const bytes = require("crypto").randomBytes(6).toString("hex");
const filePath = BUILD_DIR + "tmp/" + prefix + bytes + suffix;
fs.writeFileSync(filePath, "");
return filePath;
}
function createTestSource(testsName, { bot = false, xfaOnly = false } = {}) {
const source = stream.Readable({ objectMode: true });
source._read = function () {
console.log();
console.log("### Running " + testsName + " tests");
const PDF_TEST = process.env.PDF_TEST || "test_manifest.json";
let forceNoChrome = false;
const args = ["test.js"];
switch (testsName) {
case "browser":
if (!bot) {
args.push("--reftest");
} else {
const os = process.env.OS;
if (/windows/i.test(os)) {
// The browser-tests are too slow in Google Chrome on the Windows
// bot, causing a timeout, hence disabling them for now.
forceNoChrome = true;
}
}
if (xfaOnly) {
args.push("--xfaOnly");
}
args.push("--manifestFile=" + PDF_TEST);
break;
case "unit":
args.push("--unitTest");
break;
case "font":
args.push("--fontTest");
break;
case "integration":
args.push("--integration");
break;
default:
this.emit("error", new Error("Unknown name: " + testsName));
return null;
}
if (bot) {
args.push("--strictVerify");
}
if (process.argv.includes("--noChrome") || forceNoChrome) {
args.push("--noChrome");
}
const testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" });
testProcess.on("close", function (code) {
source.push(null);
});
return undefined;
};
return source;
}
function makeRef(done, bot) {
console.log();
console.log("### Creating reference images");
let forceNoChrome = false;
const args = ["test.js", "--masterMode"];
if (bot) {
const os = process.env.OS;
if (/windows/i.test(os)) {
// The browser-tests are too slow in Google Chrome on the Windows
// bot, causing a timeout, hence disabling them for now.
forceNoChrome = true;
}
args.push("--noPrompts", "--strictVerify");
}
if (process.argv.includes("--noChrome") || forceNoChrome) {
args.push("--noChrome");
}
const testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" });
testProcess.on("close", function (code) {
done();
});
}
gulp.task("default", function (done) {
console.log("Available tasks:");
const tasks = Object.keys(gulp.registry().tasks());
for (const taskName of tasks.sort()) {
if (taskName.endsWith("-pre")) {
continue;
}
console.log(" " + taskName);
}
done();
});
function createBuildNumber(done) {
console.log();
console.log("### Getting extension build number");
exec(
"git log --format=oneline " + config.baseVersion + "..",
function (err, stdout, stderr) {
let buildNumber = 0;
if (!err) {
// Build number is the number of commits since base version
buildNumber = stdout ? stdout.match(/\n/g).length : 0;
} else {
console.log(
"This is not a Git repository; using default build number."
);
}
console.log("Extension build number: " + buildNumber);
const version = config.versionPrefix + buildNumber;
exec('git log --format="%h" -n 1', function (err2, stdout2, stderr2) {
let buildCommit = "";
if (!err2) {
buildCommit = stdout2.replace("\n", "");
}
createStringSource(
"version.json",
JSON.stringify(
{
version,
build: buildNumber,
commit: buildCommit,
},
null,
2
)
)
.pipe(gulp.dest(BUILD_DIR))
.on("end", done);
});
}
);
}
function buildDefaultPreferences(defines, dir) {
console.log();
console.log("### Building default preferences");
const bundleDefines = builder.merge(defines, {
LIB: true,
SKIP_BABEL: false,
BUNDLE_VERSION: 0, // Dummy version
BUNDLE_BUILD: 0, // Dummy build
TESTING:
defines.TESTING !== undefined
? defines.TESTING
: process.env.TESTING === "true",
});
const inputStream = merge([
gulp.src(["web/app_options.js"], {
base: ".",
}),
]);
return buildLibHelper(
bundleDefines,
inputStream,
DEFAULT_PREFERENCES_DIR + dir
);
}
function getDefaultPreferences(dir) {
const { AppOptions, OptionKind } = require("./" +
DEFAULT_PREFERENCES_DIR +
dir +
"web/app_options.js");
return AppOptions.getAll(OptionKind.PREFERENCE);
}
function getDialogPolyfillCSS() {
return fs
.readFileSync("node_modules/dialog-polyfill/dist/dialog-polyfill.css")
.toString();
}
gulp.task("locale", function () {
const VIEWER_LOCALE_OUTPUT = "web/locale/";
console.log();
console.log("### Building localization files");
rimraf.sync(VIEWER_LOCALE_OUTPUT);
mkdirp.sync(VIEWER_LOCALE_OUTPUT);
const subfolders = fs.readdirSync(L10N_DIR);
subfolders.sort();
let viewerOutput = "";
const locales = [];
for (const locale of subfolders) {
const dirPath = L10N_DIR + locale;
if (!checkDir(dirPath)) {
continue;
}
if (!/^[a-z][a-z]([a-z])?(-[A-Z][A-Z])?$/.test(locale)) {
console.log("Skipping invalid locale: " + locale);
continue;
}
mkdirp.sync(VIEWER_LOCALE_OUTPUT + "/" + locale);
locales.push(locale);
if (checkFile(dirPath + "/viewer.properties")) {
viewerOutput +=
"[" +
locale +
"]\n" +
"@import url(" +
locale +
"/viewer.properties)\n\n";
}
}
return merge([
createStringSource("locale.properties", viewerOutput).pipe(
gulp.dest(VIEWER_LOCALE_OUTPUT)
),
gulp
.src(L10N_DIR + "/{" + locales.join(",") + "}/viewer.properties", {
base: L10N_DIR,
})
.pipe(gulp.dest(VIEWER_LOCALE_OUTPUT)),
]);
});
gulp.task("cmaps", function (done) {
const CMAP_INPUT = "external/cmaps";
const VIEWER_CMAP_OUTPUT = "external/bcmaps";
console.log();
console.log("### Building cmaps");
// Testing a file that usually present.
if (!checkFile(CMAP_INPUT + "/UniJIS-UCS2-H")) {
console.log("./external/cmaps has no cmap files, download them from:");
console.log(" https://github.com/adobe-type-tools/cmap-resources");
throw new Error("cmap files were not found");
}
// Remove old bcmap files.
fs.readdirSync(VIEWER_CMAP_OUTPUT).forEach(function (file) {
if (/\.bcmap$/i.test(file)) {
fs.unlinkSync(VIEWER_CMAP_OUTPUT + "/" + file);
}
});
const compressCmaps =
require("./external/cmapscompress/compress.js").compressCmaps;
compressCmaps(CMAP_INPUT, VIEWER_CMAP_OUTPUT, true);
done();
});
function preprocessCSS(source, defines) {
const outName = getTempFile("~preprocess", ".css");
builder.preprocess(source, outName, defines);
let out = fs.readFileSync(outName).toString();
fs.unlinkSync(outName);
// Strip out all license headers in the middle.
const reg = /\n\/\* Copyright(.|\n)*?Mozilla Foundation(.|\n)*?\*\//g;
out = out.replaceAll(reg, "");
const i = source.lastIndexOf("/");
return createStringSource(source.substr(i + 1), out);
}
function preprocessHTML(source, defines) {
const outName = getTempFile("~preprocess", ".html");
builder.preprocess(source, outName, defines);
const out = fs.readFileSync(outName).toString();
fs.unlinkSync(outName);
const i = source.lastIndexOf("/");
return createStringSource(source.substr(i + 1), `${out.trimEnd()}\n`);
}
function buildGeneric(defines, dir) {
rimraf.sync(dir);
return merge([
createMainBundle(defines).pipe(gulp.dest(dir + "build")),
createWorkerBundle(defines).pipe(gulp.dest(dir + "build")),
createSandboxBundle(defines).pipe(gulp.dest(dir + "build")),
createWebBundle(defines, {
defaultPreferencesDir: defines.SKIP_BABEL
? "generic/"
: "generic-legacy/",
}).pipe(gulp.dest(dir + "web")),
gulp.src(COMMON_WEB_FILES, { base: "web/" }).pipe(gulp.dest(dir + "web")),
gulp.src("LICENSE").pipe(gulp.dest(dir)),
gulp
.src(["web/locale/*/viewer.properties", "web/locale/locale.properties"], {
base: "web/",
})
.pipe(gulp.dest(dir + "web")),
createCMapBundle().pipe(gulp.dest(dir + "web/cmaps")),
createStandardFontBundle().pipe(gulp.dest(dir + "web/standard_fonts")),
preprocessHTML("web/viewer.html", defines).pipe(gulp.dest(dir + "web")),
preprocessCSS("web/viewer.css", defines)
.pipe(
postcss([postcssDirPseudoClass(), autoprefixer(AUTOPREFIXER_CONFIG)])
)
.pipe(gulp.dest(dir + "web")),
gulp
.src("web/compressed.tracemonkey-pldi-09.pdf")
.pipe(gulp.dest(dir + "web")),
]);
}
// Builds the generic production viewer that is only compatible with up-to-date
// HTML5 browsers, which implement modern ECMAScript features.
gulp.task(
"generic",
gulp.series(
createBuildNumber,
"locale",
function scriptingGeneric() {
const defines = builder.merge(DEFINES, { GENERIC: true });
return merge([
buildDefaultPreferences(defines, "generic/"),
createTemporaryScriptingBundle(defines),
]);
},
function createGeneric() {
console.log();
console.log("### Creating generic viewer");
const defines = builder.merge(DEFINES, { GENERIC: true });
return buildGeneric(defines, GENERIC_DIR);
}
)
);
// Builds the generic production viewer that should be compatible with most
// older HTML5 browsers.
gulp.task(
"generic-legacy",
gulp.series(
createBuildNumber,
"locale",
function scriptingGenericLegacy() {
const defines = builder.merge(DEFINES, {
GENERIC: true,
SKIP_BABEL: false,