This repository has been archived by the owner on Sep 17, 2024. It is now read-only.
forked from mozilla/pdf.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
2306 lines (2065 loc) · 64.6 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 */
/* globals target */
"use strict";
const autoprefixer = require("autoprefixer");
const calc = require("postcss-calc");
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 LIB_DIR = BUILD_DIR + "lib/";
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,cur}", "web/debugger.js"];
const MOZCENTRAL_DIFF_FILE = "mozcentral.diff";
const REPO = "git@github.com:mozilla/pdf.js.git";
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());
// Default Autoprefixer config used for generic, components, minified-pre
const AUTOPREFIXER_CONFIG = {
overrideBrowserslist: [
"last 2 versions",
"Chrome >= 49", // Last supported on Windows XP
"Firefox >= 52", // Last supported on Windows XP
"Firefox ESR",
"Safari >= 10",
"> 0.5%",
"not IE > 0",
"not dead",
],
};
const DEFINES = Object.freeze({
PRODUCTION: true,
SKIP_BABEL: true,
TESTING: false,
// The main build targets:
GENERIC: false,
MOZCENTRAL: 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.replace(/([$\\"`])/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 || process.env.TESTING === "true",
DEFAULT_PREFERENCES: defaultPreferencesDir
? getDefaultPreferences(defaultPreferencesDir)
: {},
});
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),
// `web-streams-polyfill` (already using a transpiled file), 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",
"node_modules[\\\\\\/]web-streams-polyfill",
];
if (enableSourceMaps) {
babelExcludes.push("src[\\\\\\/]core[\\\\\\/](glyphlist|unicode)");
}
const babelExcludeRegExp = new RegExp(`(${babelExcludes.join("|")})`);
// Since logical assignment operators is a fairly new ECMAScript feature,
// for now we translate these regardless of the `SKIP_BABEL` value (with the
// exception of `MOZCENTRAL`/`TESTING`-builds where this isn't an issue).
const babelPlugins = [
"@babel/plugin-transform-modules-commonjs",
[
"@babel/plugin-transform-runtime",
{
helpers: false,
regenerator: true,
},
],
];
if (!bundleDefines.MOZCENTRAL && !bundleDefines.TESTING) {
babelPlugins.push("@babel/plugin-proposal-logical-assignment-operators");
}
const plugins = [];
if (!disableLicenseHeader) {
plugins.push(
new webpack2.BannerPlugin({ banner: licenseHeaderLibre, raw: true })
);
}
// Required to expose e.g., the `window` object.
output.globalObject = "this";
return {
mode: "none",
output,
performance: {
hints: false, // Disable messages about larger file sizes.
},
plugins,
resolve: {
alias: {
pdfjs: path.join(__dirname, "src"),
"pdfjs-web": path.join(__dirname, "web"),
"pdfjs-lib": path.join(__dirname, "web/pdfjs"),
},
},
devtool: enableSourceMaps ? "source-map" : undefined,
module: {
rules: [
{
loader: "babel-loader",
exclude: babelExcludeRegExp,
options: {
presets: skipBabel ? undefined : ["@babel/preset-env"],
plugins: babelPlugins,
},
},
{
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 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(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(
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(
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(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(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));
}
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(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(replaceJSRootName(imageDecodersAMDName, "pdfjsImageDecoders"));
}
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) {
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";
const args = ["test.js"];
switch (testsName) {
case "browser":
args.push("--reftest", "--manifestFile=" + PDF_TEST);
break;
case "browser (no reftest)":
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")) {
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");
const args = ["test.js", "--masterMode"];
if (bot) {
args.push("--noPrompts", "--strictVerify");
}
if (process.argv.includes("--noChrome")) {
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());
tasks.sort();
tasks.forEach(function (taskName) {
console.log(" " + taskName);
});
done();
});
gulp.task("buildnumber", function (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 || process.env.TESTING === "true",
});
const inputStream = merge([
gulp.src(["web/{app_options,viewer_compatibility}.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);
}
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 (let i = 0; i < subfolders.length; i++) {
const locale = subfolders[i];
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, mode, defines, cleanup) {
const outName = getTempFile("~preprocess", ".css");
builder.preprocessCSS(mode, source, outName);
let out = fs.readFileSync(outName).toString();
fs.unlinkSync(outName);
if (cleanup) {
// Strip out all license headers in the middle.
const reg = /\n\/\* Copyright(.|\n)*?Mozilla Foundation(.|\n)*?\*\//g;
out = out.replace(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")),
gulp
.src(["external/bcmaps/*.bcmap", "external/bcmaps/LICENSE"], {
base: "external/bcmaps",
})
.pipe(gulp.dest(dir + "web/cmaps")),
preprocessHTML("web/viewer.html", defines).pipe(gulp.dest(dir + "web")),
preprocessCSS("web/viewer.css", "generic", defines, true)
.pipe(postcss([calc(), 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(
"buildnumber",
"locale",
function scripting() {
const defines = builder.merge(DEFINES, { GENERIC: true });
return merge([
buildDefaultPreferences(defines, "generic/"),
createTemporaryScriptingBundle(defines),
]);
},
function () {
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(
"buildnumber",
"locale",
function scripting() {
const defines = builder.merge(DEFINES, {
GENERIC: true,
SKIP_BABEL: false,
});
return merge([
buildDefaultPreferences(defines, "generic-legacy/"),
createTemporaryScriptingBundle(defines),
]);
},
function () {
console.log();
console.log("### Creating generic (legacy) viewer");
const defines = builder.merge(DEFINES, {
GENERIC: true,
SKIP_BABEL: false,
});
return buildGeneric(defines, GENERIC_LEGACY_DIR);
}
)
);
function buildComponents(defines, dir) {
rimraf.sync(dir);
const COMPONENTS_IMAGES = [
"web/images/annotation-*.svg",
"web/images/loading-icon.gif",
"web/images/shadow.png",
];
return merge([
createComponentsBundle(defines).pipe(gulp.dest(dir)),
gulp.src(COMPONENTS_IMAGES).pipe(gulp.dest(dir + "images")),
preprocessCSS("web/pdf_viewer.css", "components", defines, true)
.pipe(postcss([calc(), autoprefixer(AUTOPREFIXER_CONFIG)]))
.pipe(gulp.dest(dir)),
]);
}
gulp.task(
"components",
gulp.series("buildnumber", function () {
console.log();
console.log("### Creating generic components");
const defines = builder.merge(DEFINES, { COMPONENTS: true, GENERIC: true });
return buildComponents(defines, COMPONENTS_DIR);
})
);
gulp.task(
"components-legacy",
gulp.series("buildnumber", function () {
console.log();
console.log("### Creating generic (legacy) components");
const defines = builder.merge(DEFINES, {
COMPONENTS: true,
GENERIC: true,
SKIP_BABEL: false,
});
return buildComponents(defines, COMPONENTS_LEGACY_DIR);
})
);
gulp.task(
"image_decoders",
gulp.series("buildnumber", function () {
console.log();
console.log("### Creating image decoders");
const defines = builder.merge(DEFINES, {
GENERIC: true,
IMAGE_DECODERS: true,
});
return createImageDecodersBundle(defines).pipe(
gulp.dest(IMAGE_DECODERS_DIR)
);
})
);
gulp.task(
"image_decoders-legacy",
gulp.series("buildnumber", function () {
console.log();
console.log("### Creating (legacy) image decoders");
const defines = builder.merge(DEFINES, {
GENERIC: true,
IMAGE_DECODERS: true,
SKIP_BABEL: false,
});
return createImageDecodersBundle(defines).pipe(
gulp.dest(IMAGE_DECODERS_LEGACY_DIR)
);
})
);
function buildMinified(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
? "minified/"
: "minified-legacy/",
}).pipe(gulp.dest(dir + "web")),
createImageDecodersBundle(
builder.merge(defines, { IMAGE_DECODERS: true })
).pipe(gulp.dest(dir + "image_decoders")),
gulp.src(COMMON_WEB_FILES, { base: "web/" }).pipe(gulp.dest(dir + "web")),
gulp
.src(["web/locale/*/viewer.properties", "web/locale/locale.properties"], {
base: "web/",
})
.pipe(gulp.dest(dir + "web")),
gulp
.src(["external/bcmaps/*.bcmap", "external/bcmaps/LICENSE"], {
base: "external/bcmaps",
})
.pipe(gulp.dest(dir + "web/cmaps")),
preprocessHTML("web/viewer.html", defines).pipe(gulp.dest(dir + "web")),
preprocessCSS("web/viewer.css", "minified", defines, true)
.pipe(postcss([calc(), autoprefixer(AUTOPREFIXER_CONFIG)]))
.pipe(gulp.dest(dir + "web")),
gulp
.src("web/compressed.tracemonkey-pldi-09.pdf")
.pipe(gulp.dest(dir + "web")),
]);
}
gulp.task(
"minified-pre",
gulp.series(
"buildnumber",
"locale",
function scripting() {