-
Notifications
You must be signed in to change notification settings - Fork 1
/
gulpfile.js
2292 lines (2037 loc) · 65.9 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
/*eslint-env node*/
import { writeFileSync, copyFileSync, readFileSync, existsSync } from "fs";
import { readFile, writeFile } from "fs/promises";
import { join, basename, resolve, posix, dirname } from "path";
import { exec, execSync } from "child_process";
import { createHash } from "crypto";
import { gzipSync } from "zlib";
import { createInterface } from "readline";
import fetch from "node-fetch";
import { createRequire } from "module";
import gulp from "gulp";
import gulpTap from "gulp-tap";
import gulpZip from "gulp-zip";
import gulpRename from "gulp-rename";
import gulpReplace from "gulp-replace";
import { globby } from "globby";
import open from "open";
import { rimraf } from "rimraf";
import { mkdirp } from "mkdirp";
import mergeStream from "merge-stream";
import streamToPromise from "stream-to-promise";
import karma from "karma";
import yargs from "yargs";
import {
S3Client,
DeleteObjectsCommand,
HeadObjectCommand,
ListObjectsCommand,
PutObjectCommand,
} from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";
import mime from "mime";
import typeScript from "typescript";
import { build as esbuild } from "esbuild";
import { createInstrumenter } from "istanbul-lib-instrument";
import pLimit from "p-limit";
import download from "download";
import decompress from "decompress";
import {
buildCesium,
buildEngine,
buildWidgets,
bundleWorkers,
glslToJavaScript,
createCombinedSpecList,
createJsHintOptions,
defaultESBuildOptions,
bundleCombinedWorkers,
} from "./build.js";
// Determines the scope of the workspace packages. If the scope is set to cesium, the workspaces should be @cesium/engine.
// This should match the scope of the dependencies of the root level package.json.
const scope = "cesium";
const require = createRequire(import.meta.url);
const packageJson = require("./package.json");
let version = packageJson.version;
if (/\.0$/.test(version)) {
version = version.substring(0, version.length - 2);
}
const karmaConfigFile = resolve("./Specs/karma.conf.cjs");
const travisDeployUrl =
"http://cesium-dev.s3-website-us-east-1.amazonaws.com/cesium/";
const isProduction = process.env.TRAVIS_BRANCH === "cesium.com";
//Gulp doesn't seem to have a way to get the currently running tasks for setting
//per-task variables. We use the command line argument here to detect which task is being run.
const taskName = process.argv[2];
const noDevelopmentGallery =
taskName === "release" ||
taskName === "makeZip" ||
taskName === "websiteRelease";
const argv = yargs(process.argv).argv;
const verbose = argv.verbose;
const sourceFiles = [
"packages/engine/Source/**/*.js",
"!packages/engine/Source/*.js",
"packages/widgets/Source/**/*.js",
"!packages/widgets/Source/*.js",
"!packages/engine/Source/Shaders/**",
"!packages/engine/Source/Workers/**",
"!packages/engine/Source/WorkersES6/**",
"packages/engine/Source/WorkersES6/createTaskProcessorWorker.js",
"!packages/engine/Source/ThirdParty/Workers/**",
"!packages/engine/Source/ThirdParty/google-earth-dbroot-parser.js",
"!packages/engine/Source/ThirdParty/_*",
];
const workerSourceFiles = ["packages/engine/Source/WorkersES6/**"];
const watchedSpecFiles = [
"packages/engine/Specs/**/*Spec.js",
"!packages/engine/Specs/SpecList.js",
"packages/widgets/Specs/**/*Spec.js",
"!packages/widgets/Specs/SpecList.js",
"Specs/*.js",
"!Specs/SpecList.js",
"Specs/TestWorkers/*.js",
];
const shaderFiles = [
"packages/engine/Source/Shaders/**/*.glsl",
"packages/engine/Source/ThirdParty/Shaders/*.glsl",
];
// Print an esbuild warning
function printBuildWarning({ location, text }) {
const { column, file, line, lineText, suggestion } = location;
let message = `\n
> ${file}:${line}:${column}: warning: ${text}
${lineText}
`;
if (suggestion && suggestion !== "") {
message += `\n${suggestion}`;
}
console.log(message);
}
// Ignore `eval` warnings in third-party code we don't have control over
function handleBuildWarnings(result) {
for (const warning of result.warnings) {
if (
!warning.location.file.includes("protobufjs.js") &&
!warning.location.file.includes("Build/Cesium")
) {
printBuildWarning(warning);
}
}
}
export async function build() {
// Configure build options from command line arguments.
const minify = argv.minify ?? false;
const removePragmas = argv.pragmas ?? false;
const sourcemap = argv.sourcemap ?? true;
const node = argv.node ?? true;
const buildOptions = {
development: !noDevelopmentGallery,
iife: true,
minify: minify,
removePragmas: removePragmas,
sourcemap: sourcemap,
node: node,
};
// Configure build target.
const workspace = argv.workspace ? argv.workspace : undefined;
if (workspace === `@${scope}/engine`) {
return buildEngine(buildOptions);
} else if (workspace === `@${scope}/widgets`) {
return buildWidgets(buildOptions);
}
await buildEngine(buildOptions);
await buildWidgets(buildOptions);
await buildCesium(buildOptions);
}
export default build;
export const buildWatch = gulp.series(build, async function () {
const minify = argv.minify ? argv.minify : false;
const removePragmas = argv.pragmas ? argv.pragmas : false;
const sourcemap = argv.sourcemap ? argv.sourcemap : true;
const outputDirectory = join("Build", `Cesium${!minify ? "Unminified" : ""}`);
const bundles = await buildCesium({
minify: minify,
path: outputDirectory,
removePragmas: removePragmas,
sourcemap: sourcemap,
incremental: true,
});
const esm = bundles.esm;
const cjs = bundles.node;
const iife = bundles.iife;
const specs = bundles.specs;
gulp.watch(shaderFiles, async () => {
glslToJavaScript(minify, "Build/minifyShaders.state", "engine");
await esm.rebuild();
if (iife) {
await iife.rebuild();
}
if (cjs) {
await cjs.rebuild();
}
});
gulp.watch(
[
...sourceFiles,
// Shader results are generated in the previous watch task; no need to rebuild twice
"!Source/Shaders/**",
],
async () => {
createJsHintOptions();
await esm.rebuild();
if (iife) {
await iife.rebuild();
}
if (cjs) {
await cjs.rebuild();
}
}
);
gulp.watch(
watchedSpecFiles,
{
events: ["add", "unlink"],
},
async () => {
createCombinedSpecList();
await specs.rebuild();
}
);
gulp.watch(
watchedSpecFiles,
{
events: ["change"],
},
async () => {
await specs.rebuild();
}
);
gulp.watch(workerSourceFiles, () => {
return bundleCombinedWorkers({
minify: minify,
path: outputDirectory,
removePragmas: removePragmas,
sourcemap: sourcemap,
});
});
process.on("SIGINT", () => {
// Free up resources
esm.dispose();
if (iife) {
iife.dispose();
}
if (cjs) {
cjs.dispose();
}
specs.dispose();
process.exit(0);
});
});
export async function buildTs() {
let workspaces;
if (argv.workspace && !Array.isArray(argv.workspace)) {
workspaces = [argv.workspace];
} else if (argv.workspace) {
workspaces = argv.workspace;
} else {
workspaces = packageJson.workspaces;
}
// Generate types for passed packages in order.
const importModules = {};
for (const workspace of workspaces) {
const directory = workspace
.replace(`@${scope}/`, "")
.replace(`packages/`, "");
const workspaceModules = await generateTypeScriptDefinitions(
directory,
`packages/${directory}/index.d.ts`,
`packages/${directory}/tsd-conf.json`,
// The engine package needs additional processing for its enum strings
directory === "engine" ? processEngineSource : undefined,
// Handle engine's module naming exceptions
directory === "engine" ? processEngineModules : undefined,
importModules
);
importModules[directory] = workspaceModules;
}
if (argv.workspace) {
return;
}
// Generate types for CesiumJS.
await createTypeScriptDefinitions();
}
export function buildApps() {
return Promise.all([buildCesiumViewer(), buildSandcastle()]);
}
const filesToClean = [
"Source/Cesium.js",
"Source/Shaders/**/*.js",
"Source/Workers/**",
"!Source/Workers/cesiumWorkerBootstrapper.js",
"!Source/Workers/transferTypedArrayTest.js",
"!Source/Workers/package.json",
"Source/ThirdParty/Shaders/*.js",
"Source/**/*.d.ts",
"Specs/SpecList.js",
"Specs/jasmine/**",
"Apps/Sandcastle/jsHintOptions.js",
"Apps/Sandcastle/gallery/gallery-index.js",
"Apps/Sandcastle/templates/bucket.css",
"Cesium-*.zip",
"cesium-*.tgz",
"packages/**/*.tgz",
];
export async function clean() {
await rimraf("Build");
const files = await globby(filesToClean);
return Promise.all(files.map((file) => rimraf(file)));
}
async function clocSource() {
let cmdLine;
//Run cloc on primary Source files only
const source = new Promise(function (resolve, reject) {
cmdLine =
"npx cloc" +
" --quiet --progress-rate=0" +
" packages/engine/Source/ packages/widgets/Source --exclude-dir=Assets,ThirdParty,Workers";
exec(cmdLine, function (error, stdout, stderr) {
if (error) {
console.log(stderr);
return reject(error);
}
console.log("Source:");
console.log(stdout);
resolve();
});
});
//If running cloc on source succeeded, also run it on the tests.
await source;
return new Promise(function (resolve, reject) {
cmdLine =
"npx cloc" +
" --quiet --progress-rate=0" +
" Specs/ packages/engine/Specs packages/widget/Specs --exclude-dir=Data --not-match-f=SpecList.js --not-match-f=.eslintrc.json";
exec(cmdLine, function (error, stdout, stderr) {
if (error) {
console.log(stderr);
return reject(error);
}
console.log("Specs:");
console.log(stdout);
resolve();
});
});
}
export async function prepare() {
// Copy Draco3D files from node_modules into Source
copyFileSync(
"node_modules/draco3d/draco_decoder_nodejs.js",
"packages/engine/Source/ThirdParty/Workers/draco_decoder_nodejs.js"
);
copyFileSync(
"node_modules/draco3d/draco_decoder.wasm",
"packages/engine/Source/ThirdParty/draco_decoder.wasm"
);
// Copy pako and zip.js worker files to Source/ThirdParty
copyFileSync(
"node_modules/pako/dist/pako_inflate.min.js",
"packages/engine/Source/ThirdParty/Workers/pako_inflate.min.js"
);
copyFileSync(
"node_modules/pako/dist/pako_deflate.min.js",
"packages/engine/Source/ThirdParty/Workers/pako_deflate.min.js"
);
copyFileSync(
"node_modules/@zip.js/zip.js/dist/z-worker-pako.js",
"packages/engine/Source/ThirdParty/Workers/z-worker-pako.js"
);
// Copy prism.js and prism.css files into Tools
copyFileSync(
"node_modules/prismjs/prism.js",
"Tools/jsdoc/cesium_template/static/javascript/prism.js"
);
copyFileSync(
"node_modules/prismjs/themes/prism.min.css",
"Tools/jsdoc/cesium_template/static/styles/prism.css"
);
// Copy jasmine runner files into Specs
const files = await globby([
"node_modules/jasmine-core/lib/jasmine-core",
"!node_modules/jasmine-core/lib/jasmine-core/example",
]);
const stream = gulp.src(files).pipe(gulp.dest("Specs/jasmine"));
return streamToPromise(stream);
}
export const cloc = gulp.series(clean, clocSource);
//Builds the documentation
export function buildDocs() {
const generatePrivateDocumentation = argv.private ? "--private" : "";
execSync(
`npx jsdoc --configure Tools/jsdoc/conf.json --pedantic ${generatePrivateDocumentation}`,
{
stdio: "inherit",
env: Object.assign({}, process.env, {
CESIUM_VERSION: version,
CESIUM_PACKAGES: packageJson.workspaces,
}),
}
);
const stream = gulp
.src("Documentation/Images/**")
.pipe(gulp.dest("Build/Documentation/Images"));
return streamToPromise(stream);
}
export async function buildDocsWatch() {
await buildDocs();
console.log("Listening for changes in documentation...");
return gulp.watch(sourceFiles, buildDocs);
}
function combineForSandcastle() {
const outputDirectory = join("Build", "Sandcastle", "CesiumUnminified");
return buildCesium({
development: false,
minify: false,
removePragmas: false,
node: false,
outputDirectory: outputDirectory,
});
}
export const websiteRelease = gulp.series(
function () {
return buildCesium({
development: false,
minify: false,
removePragmas: false,
node: false,
});
},
combineForSandcastle,
buildDocs
);
export const buildRelease = gulp.series(
buildEngine,
buildWidgets,
// Generate Build/CesiumUnminified
function () {
return buildCesium({
minify: false,
removePragmas: false,
node: true,
sourcemap: false,
});
},
// Generate Build/Cesium
function () {
return buildCesium({
development: false,
minify: true,
removePragmas: true,
node: true,
sourcemap: false,
});
}
);
export const release = gulp.series(
buildRelease,
gulp.parallel(buildTs, buildDocs)
);
/**
* Removes scripts from package.json files to ensure that
* they still work when run from within the ZIP file.
*
* @param {string} packageJsonPath The path to the package.json.
* @returns {WritableStream} A stream that writes to the updated package.json file.
*/
async function pruneScriptsForZip(packageJsonPath) {
// Read the contents of the file.
const contents = await readFile(packageJsonPath);
const contentsJson = JSON.parse(contents);
const scripts = contentsJson.scripts;
// Remove prepare step from package.json to avoid running "prepare" an extra time.
delete scripts.prepare;
// Remove build and transform tasks since they do not function as intended from within the release zip
delete scripts.build;
delete scripts["build-release"];
delete scripts["build-watch"];
delete scripts["build-ts"];
delete scripts["build-third-party"];
delete scripts["build-apps"];
delete scripts.clean;
delete scripts.cloc;
delete scripts["build-docs"];
delete scripts["build-docs-watch"];
delete scripts["make-zip"];
delete scripts.release;
delete scripts.prettier;
// Remove deploy tasks
delete scripts["deploy-s3"];
delete scripts["deploy-status"];
delete scripts["deploy-set-version"];
delete scripts["website-release"];
// Set server tasks to use production flag
scripts["start"] = "node server.js --production";
scripts["start-public"] = "node server.js --public --production";
scripts["start-public"] = "node server.js --public --production";
scripts["test"] = "gulp test --production";
scripts["test-all"] = "gulp test --all --production";
scripts["test-webgl"] = "gulp test --include WebGL --production";
scripts["test-non-webgl"] = "gulp test --exclude WebGL --production";
scripts["test-webgl-validation"] = "gulp test --webglValidation --production";
scripts["test-webgl-stub"] = "gulp test --webglStub --production";
scripts["test-release"] = "gulp test --release --production";
// Write to a temporary package.json file.
const noPreparePackageJson = join(
dirname(packageJsonPath),
"Build/package.noprepare.json"
);
await writeFile(noPreparePackageJson, JSON.stringify(contentsJson, null, 2));
return gulp.src(noPreparePackageJson).pipe(gulpRename(packageJsonPath));
}
export const postversion = async function () {
const workspace = argv.workspace;
if (!workspace) {
return;
}
const directory = workspace.replaceAll(`@${scope}/`, ``);
const workspacePackageJson = require(`./packages/${directory}/package.json`);
const version = workspacePackageJson.version;
// Iterate through all package JSONs that may depend on the updated package and
// update the version of the updated workspace.
const packageJsons = await globby([
"./package.json",
"./packages/*/package.json",
]);
const promises = packageJsons.map(async (packageJsonPath) => {
// Ensure that we don't check the updated workspace itself.
if (basename(dirname(packageJsonPath)) === directory) {
return;
}
// Ensure that we only update workspaces where the dependency to the updated workspace already exists.
const packageJson = require(packageJsonPath);
if (!Object.hasOwn(packageJson.dependencies, workspace)) {
console.log(
`Skipping update for ${workspace} as it is not a dependency.`
);
return;
}
// Update the version for the updated workspace.
packageJson.dependencies[workspace] = `^${version}`;
await writeFile(packageJsonPath, JSON.stringify(packageJson, undefined, 2));
});
return Promise.all(promises);
};
export const makeZip = gulp.series(release, async function () {
//For now we regenerate the JS glsl to force it to be unminified in the release zip
//See https://github.com/CesiumGS/cesium/pull/3106#discussion_r42793558 for discussion.
await glslToJavaScript(false, "Build/minifyShaders.state", "engine");
const packageJsonSrc = await pruneScriptsForZip("package.json");
const enginePackageJsonSrc = await pruneScriptsForZip(
"packages/engine/package.json"
);
const widgetsPackageJsonSrc = await pruneScriptsForZip(
"packages/widgets/package.json"
);
const builtSrc = gulp.src(
[
"Build/Cesium/**",
"Build/CesiumUnminified/**",
"Build/Documentation/**",
"Build/Specs/**",
"!Build/Specs/e2e/**",
"Build/package.json",
"packages/engine/Build/**",
"packages/widgets/Build/**",
"!packages/engine/Build/Specs/**",
"!packages/widgets/Build/Specs/**",
"!packages/engine/Build/minifyShaders.state",
"!packages/engine/Build/package.noprepare.json",
"!packages/widgets/Build/package.noprepare.json",
],
{
base: ".",
}
);
const staticSrc = gulp.src(
[
"Apps/**",
"Apps/**/.eslintrc.json",
"Apps/Sandcastle/.jshintrc",
"!Apps/Sandcastle/gallery/development/**",
"packages/engine/index.js",
"packages/engine/index.d.ts",
"packages/engine/LICENSE.md",
"packages/engine/README.md",
"packages/engine/Source/**",
"!packages/engine/.gitignore",
"packages/widgets/index.js",
"packages/widgets/index.d.ts",
"packages/widgets/LICENSE.md",
"packages/widgets/README.md",
"packages/widgets/Source/**",
"!packages/widgets/.gitignore",
"Source/**",
"Source/**/.eslintrc.json",
"Specs/**",
"!Specs/e2e/*-snapshots/**",
"Specs/**/.eslintrc.json",
"ThirdParty/**",
"favicon.ico",
".eslintignore",
".eslintrc.json",
".prettierignore",
"build.js",
"gulpfile.js",
"server.js",
"index.cjs",
"LICENSE.md",
"CHANGES.md",
"README.md",
"web.config",
],
{
base: ".",
}
);
const indexSrc = gulp
.src("index.release.html")
.pipe(gulpRename("index.html"));
return streamToPromise(
mergeStream(
packageJsonSrc,
enginePackageJsonSrc,
widgetsPackageJsonSrc,
builtSrc,
staticSrc,
indexSrc
)
.pipe(
gulpTap(function (file) {
// Work around an issue with gulp-zip where archives generated on Windows do
// not properly have their directory executable mode set.
// see https://github.com/sindresorhus/gulp-zip/issues/64#issuecomment-205324031
if (file.isDirectory()) {
file.stat.mode = parseInt("40777", 8);
}
})
)
.pipe(gulpZip(`Cesium-${version}.zip`))
.pipe(gulp.dest("."))
.on("finish", function () {
rimraf.sync("./Build/package.noprepare.json");
rimraf.sync("./packages/engine/Build/package.noprepare.json");
rimraf.sync("./packages/widgets/Build/package.noprepare.json");
})
);
});
function isTravisPullRequest() {
return (
process.env.TRAVIS_PULL_REQUEST !== undefined &&
process.env.TRAVIS_PULL_REQUEST !== "false"
);
}
export async function deployS3() {
if (isTravisPullRequest()) {
console.log("Skipping deployment for non-pull request.");
return;
}
const argv = yargs(process.argv)
.usage("Usage: deploy-s3 -b [Bucket Name] -d [Upload Directory]")
.options({
bucket: {
alias: "b",
description: "Bucket name.",
type: "string",
demandOption: true,
},
directory: {
alias: "d",
description: "Upload directory.",
type: "string",
},
"cache-control": {
alias: "c",
description:
"The cache control option set on the objects uploaded to S3.",
type: "string",
default: "max-age=3600",
},
"dry-run": {
description: "Only print file paths and S3 keys.",
type: "boolean",
default: false,
},
confirm: {
description: "Skip confirmation step, useful for CI.",
type: "boolean",
default: false,
},
}).argv;
const uploadDirectory = argv.directory;
const bucketName = argv.bucket;
const dryRun = argv.dryRun;
const cacheControl = argv.cacheControl ? argv.cacheControl : "max-age=3600";
if (argv.confirm) {
return deployCesium(bucketName, uploadDirectory, cacheControl, dryRun);
}
const iface = createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
// prompt for confirmation
iface.question(
`Files from your computer will be published to the ${bucketName} bucket. Continue? [y/n] `,
function (answer) {
iface.close();
if (answer === "y") {
resolve(
deployCesium(bucketName, uploadDirectory, cacheControl, dryRun)
);
} else {
console.log("Deploy aborted by user.");
resolve();
}
}
);
});
}
// Deploy cesium to s3
async function deployCesium(bucketName, uploadDirectory, cacheControl, dryRun) {
// Limit promise concurrency since we are reading many
// files off disk in parallel
const limit = pLimit(2000);
const refDocPrefix = "cesiumjs/ref-doc/";
const sandcastlePrefix = "sandcastle/";
const cesiumViewerPrefix = "cesiumjs/cesium-viewer/";
const s3Client = new S3Client({
region: "us-east-1",
maxRetries: 10,
retryDelayOptions: {
base: 500,
},
});
const existingBlobs = [];
let totalFiles = 0;
let uploaded = 0;
let skipped = 0;
const errors = [];
if (!isProduction) {
await listAll(s3Client, bucketName, `${uploadDirectory}/`, existingBlobs);
}
async function getContents(file, blobName) {
const mimeLookup = getMimeType(blobName);
const contentType = mimeLookup.type;
const compress = mimeLookup.compress;
const contentEncoding = compress ? "gzip" : undefined;
totalFiles++;
let content = await readFile(file);
if (compress) {
const alreadyCompressed = content[0] === 0x1f && content[1] === 0x8b;
if (alreadyCompressed) {
if (verbose) {
console.log(`Skipping compressing already compressed file: ${file}`);
}
} else {
content = gzipSync(content);
}
}
const computeEtag = (content) => {
return createHash("md5").update(content).digest("base64");
};
const index = existingBlobs.indexOf(blobName);
if (index <= -1) {
return {
content,
etag: computeEtag(content),
contentType,
contentEncoding,
};
}
// remove files from the list to clean later
// as we find them on disk
existingBlobs.splice(index, 1);
// get file info
const headObjectCommand = new HeadObjectCommand({
Bucket: bucketName,
Key: blobName,
});
const data = await s3Client.send(headObjectCommand);
const hash = createHash("md5").update(content).digest("hex");
if (
data.ETag !== `"${hash}"` ||
data.CacheControl !== cacheControl ||
data.ContentType !== contentType ||
data.ContentEncoding !== contentEncoding
) {
return {
content,
etag: computeEtag(content),
contentType,
contentEncoding,
};
}
// We don't need to upload this file again
skipped++;
}
async function readAndUpload(prefix, existingPrefix, file) {
const blobName = `${prefix}${file.replace(existingPrefix, "")}`;
let fileContents;
try {
fileContents = await getContents(file, blobName);
} catch (e) {
errors.push(e);
}
if (!fileContents) {
return;
}
const content = fileContents.content;
const etag = fileContents.etag;
const contentType = fileContents.contentType;
const contentEncoding = fileContents.contentEncoding;
if (verbose) {
console.log(`Uploading ${blobName}...`);
}
const params = {
Bucket: bucketName,
Key: blobName,
Body: content,
ContentMD5: etag,
ContentType: contentType,
ContentEncoding: contentEncoding,
CacheControl: cacheControl,
};
const putObjectCommand = new PutObjectCommand(params);
if (dryRun) {
uploaded++;
return;
}
try {
await s3Client.send(putObjectCommand);
uploaded++;
} catch (e) {
errors.push(e);
}
}
let uploads;
if (isProduction) {
const uploadSandcastle = async () => {
const files = await globby(["Build/Sandcastle/**"]);
return Promise.all(
files.map((file) => {
return limit(() =>
readAndUpload(sandcastlePrefix, "Build/Sandcastle/", file)
);
})
);
};
const uploadRefDoc = async () => {
const files = await globby(["Build/Documentation/**"]);
return Promise.all(
files.map((file) => {
return limit(() =>
readAndUpload(refDocPrefix, "Build/Documentation/", file)
);
})
);
};
const uploadCesiumViewer = async () => {
const files = await globby(["Build/CesiumViewer/**"]);
return Promise.all(
files.map((file) => {
return limit(() =>
readAndUpload(cesiumViewerPrefix, "Build/CesiumViewer/", file)
);
})
);
};
uploads = [
uploadSandcastle(),
uploadRefDoc(),
uploadCesiumViewer(),
deployCesiumRelease(bucketName, s3Client, errors),
];
} else {
const files = await globby(
[
"Apps/**",
"Build/**",
"!Build/CesiumDev/**",
"packages/**",
"Source/**",
"Specs/**",
"ThirdParty/**",
"*.md",
"favicon.ico",
"gulpfile.js",
"index.html",
"package.json",
"server.js",
"web.config",
"*.zip",
"*.tgz",
],
{
dot: true, // include hidden files
}
);
uploads = files.map((file) => {
return limit(() => readAndUpload(`${uploadDirectory}/`, "", file));
});
}
await Promise.all(uploads);
console.log(
`Skipped ${skipped} files and successfully uploaded ${uploaded} files of ${
totalFiles - skipped