forked from be5invis/Iosevka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verdafile.mjs
1386 lines (1253 loc) · 44.8 KB
/
verdafile.mjs
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
import * as FS from "fs";
import * as Path from "path";
import * as toml from "@iarna/toml";
import deepEqual from "deep-equal";
import semver from "semver";
import * as uuid from "uuid";
import * as Verda from "verda";
import which from "which";
///////////////////////////////////////////////////////////
export const build = Verda.create();
const { task, file, oracle, computed } = build.ruleTypes;
const { de, fu, sfu, ofu } = build.rules;
const { run, node, cd, cp, rm, fail, echo, silently, absolutelySilently } = build.actions;
const { FileList } = build.predefinedFuncs;
///////////////////////////////////////////////////////////
const BUILD = ".build";
const DIST = "dist";
const IMAGES = "images";
const IMAGE_TASKS = ".build/image-tasks";
const GLYF_TTC = ".build/glyf-ttc";
const SHARED_CACHE = `${BUILD}/cache`;
const DIST_TTC = "dist/.ttc";
const DIST_SUPER_TTC = "dist/.super-ttc";
const ARCHIVE_DIR = "release-archives";
const PATEL_C = ["node", "node_modules/patel/bin/patel-c"];
const MAKE_TTC = ["node", "node_modules/otb-ttc-bundle/bin/otb-ttc-bundle"];
const SEVEN_ZIP = process.env.SEVEN_ZIP_PATH || "7z";
const TTFAUTOHINT = process.env.TTFAUTOHINT_PATH || "ttfautohint";
const defaultWebFontFormats = ["WOFF2", "TTF"];
const webfontFormatsFast = ["TTF"];
const webfontFormatsPages = ["WOFF2"];
const WIDTH_NORMAL = "Normal";
const WEIGHT_NORMAL = "Regular";
const SLOPE_NORMAL = "Upright";
const DEFAULT_SUBFAMILY = "Regular";
const BUILD_PLANS = "build-plans.toml";
const PRIVATE_BUILD_PLANS = "private-build-plans.toml";
// Save journal to build/
build.setJournal(`${BUILD}/.verda-build-journal`);
// Enable self-tracking
build.setSelfTracking();
///////////////////////////////////////////////////////////
////// Oracles //////
///////////////////////////////////////////////////////////
const Version = computed(`env::version`, async target => {
const [pjf] = await target.need(sfu`package.json`);
const pj = JSON.parse(await FS.promises.readFile(pjf.full, "utf-8"));
return pj.version;
});
const CheckTtfAutoHintExists = oracle(`oracle:check-ttfautohint-exists`, async target => {
try {
return await which(TTFAUTOHINT);
} catch (e) {
fail("External dependency <ttfautohint>, needed for building hinted font, does not exist.");
}
});
const Dependencies = computed("env::dependencies", async target => {
const [pjf] = await target.need(sfu`package.json`);
const pj = JSON.parse(await FS.promises.readFile(pjf.full, "utf-8"));
let subGoals = [];
for (const pkgName in pj.dependencies) {
subGoals.push(InstalledVersion(pkgName, pj.dependencies[pkgName]));
}
const [actual] = await target.need(subGoals);
return actual;
});
const InstalledVersion = computed.make(
(pkg, required) => `env::installed-version::${pkg}::${required}`,
async (target, pkg, required) => {
const [pj] = await target.need(sfu(`node_modules/${pkg}/package.json`));
const depPkg = JSON.parse(await FS.promises.readFile(pj.full));
if (!semver.satisfies(depPkg.version, required)) {
fail(
`Package version for ${pkg} is outdated:`,
`Required ${required}, Installed ${depPkg.version}`
);
}
return { name: pkg, actual: depPkg.version, required };
}
);
///////////////////////////////////////////////////////////
////// Plans //////
///////////////////////////////////////////////////////////
const RawPlans = computed(`metadata:raw-plans`, async target => {
await target.need(sfu(BUILD_PLANS), ofu(PRIVATE_BUILD_PLANS), Version);
const bp = await tryParseToml(BUILD_PLANS);
bp.buildOptions = bp.buildOptions || {};
if (FS.existsSync(PRIVATE_BUILD_PLANS)) {
const privateBP = await tryParseToml(PRIVATE_BUILD_PLANS);
Object.assign(bp.buildPlans, privateBP.buildPlans || {});
Object.assign(bp.collectPlans, privateBP.collectPlans || {});
Object.assign(bp.buildOptions, privateBP.buildOptions || {});
}
return bp;
});
async function tryParseToml(str) {
try {
return JSON.parse(JSON.stringify(toml.parse(FS.readFileSync(str, "utf-8"))));
} catch (e) {
throw new Error(
`Failed to parse configuration file ${str}.\n` +
`Please validate whether there's syntax error.\n` +
`${e}`
);
}
}
const BuildPlans = computed("metadata:build-plans", async target => {
const [rp] = await target.need(RawPlans);
const rawBuildPlans = rp.buildPlans;
// Initialize build plans
const returnBuildPlans = {};
for (const prefix in rawBuildPlans) {
const bp = { ...rawBuildPlans[prefix] };
validateBuildPlan(prefix, bp);
bp.webfontFormats = bp.webfontFormats || defaultWebFontFormats;
bp.targets = [];
returnBuildPlans[prefix] = bp;
}
// Resolve WWS, including inheritance and default config
for (const prefix in rawBuildPlans) {
resolveWws(prefix, returnBuildPlans, rp);
}
// Create file name to BP mapping
const fileNameToBpMap = {};
for (const prefix in rawBuildPlans) {
const bp = returnBuildPlans[prefix];
const weights = bp.weights,
slopes = bp.slopes,
widths = bp.widths;
const suffixMapping = getSuffixMapping(weights, slopes, widths);
for (const suffix in suffixMapping) {
const sfi = suffixMapping[suffix];
if (weights && !weights[sfi.weight]) continue;
if (slopes && !slopes[sfi.slope]) continue;
const fileName = makeFileName(prefix, suffix);
bp.targets.push(fileName);
fileNameToBpMap[fileName] = { prefix, suffix };
}
returnBuildPlans[prefix] = bp;
}
linkSpacingDerivableBuildPlans(returnBuildPlans);
return { fileNameToBpMap, buildPlans: returnBuildPlans };
});
function linkSpacingDerivableBuildPlans(bps) {
for (const pfxTo in bps) {
const bpTo = bps[pfxTo];
if (blockSpacingDerivationTo(bpTo)) continue;
if (!isDeriveToSpacing(bpTo.spacing)) continue;
for (const pfxFrom in bps) {
const bpFrom = bps[pfxFrom];
if (!isDeriveFromSpacing(bpFrom.spacing)) continue;
if (!spacingDeriveCompatible(pfxTo, bpTo, pfxFrom, bpFrom)) continue;
bpTo.spacingDeriveFrom = pfxFrom;
}
}
}
function blockSpacingDerivationTo(bp) {
return !!bp.compatibilityLigatures;
}
function isDeriveToSpacing(spacing) {
return spacing === "term" || spacing === "fontconfig-mono" || spacing === "fixed";
}
function isDeriveFromSpacing(spacing) {
return !spacing || spacing === "normal";
}
function spacingDeriveCompatible(pfxTo, bpTo, pfxFrom, bpFrom) {
// If the two build plans are the same, then they are compatible.
return deepEqual(rectifyPlanForSpacingDerive(bpTo), rectifyPlanForSpacingDerive(bpFrom));
}
function rectifyPlanForSpacingDerive(p) {
return {
...p,
family: "#Validation",
desc: "#Validation",
spacing: "#Validation",
buildCharMap: false,
snapshotFamily: null,
snapshotFeature: null,
targets: null
};
}
const BuildPlanOf = computed.group("metadata:build-plan-of", async (target, gid) => {
const [{ buildPlans }] = await target.need(BuildPlans);
const plan = buildPlans[gid];
if (!plan) fail(`Build plan for '${gid}' not found.` + whyBuildPlanIsnNotThere(gid));
return plan;
});
const GroupFontsOf = computed.group("metadata:group-fonts-of", async (target, gid) => {
const [plan] = await target.need(BuildPlanOf(gid));
return plan.targets;
});
const CompositesFromBuildPlan = computed(`metadata:composites-from-build-plan`, async target => {
const [{ buildPlans }] = await target.need(BuildPlans);
let data = {};
for (const bpn in buildPlans) {
let bp = buildPlans[bpn];
if (bp.variants) {
data[bpn] = bp.variants;
}
}
return data;
});
// eslint-disable-next-line complexity
const FontInfoOf = computed.group("metadata:font-info-of", async (target, fileName) => {
const [{ fileNameToBpMap, buildPlans }] = await target.need(BuildPlans);
const [version] = await target.need(Version);
const fi0 = fileNameToBpMap[fileName];
if (!fi0) fail(`Build plan for '${fileName}' not found.` + whyBuildPlanIsnNotThere(fileName));
const bp = buildPlans[fi0.prefix];
if (!bp) fail(`Build plan for '${fileName}' not found.` + whyBuildPlanIsnNotThere(fileName));
const sfm = getSuffixMapping(bp.weights, bp.slopes, bp.widths);
const sfi = sfm[fi0.suffix];
const hintReferenceSuffix = fetchHintReferenceSuffix(sfm);
let spacingDerive = null;
if (bp.spacingDeriveFrom) {
spacingDerive = {
manner: bp.spacing,
prefix: bp.spacingDeriveFrom,
fileName: makeFileName(bp.spacingDeriveFrom, fi0.suffix)
};
}
return {
name: fileName,
variants: bp.variants || null,
derivingVariants: bp.derivingVariants,
buildCharMap: bp.buildCharMap,
featureControl: {
noCvSs: bp.noCvSs || false,
noLigation: bp.noLigation || false,
exportGlyphNames: bp.exportGlyphNames || false,
buildTextureFeature: bp.buildTextureFeature || false
},
// Ligations
ligations: bp.ligations || null,
// Shape
shape: {
serifs: bp.serifs || null,
spacing: bp.spacing || null,
weight: sfi.shapeWeight,
width: sfi.shapeWidth,
slope: sfi.shapeSlope,
slopeAngle: sfi.shapeSlopeAngle
},
// Menu
menu: {
family: bp.family,
version: version,
width: sfi.menuWidth,
slope: sfi.menuSlope,
weight: sfi.menuWeight
},
// CSS
css: {
weight: sfi.cssWeight,
stretch: sfi.cssStretch,
style: sfi.cssStyle
},
// Hinting
hintParams: bp.hintParams || [],
hintReference:
!bp.metricOverride && hintReferenceSuffix !== fi0.suffix
? makeFileName(fi0.prefix, hintReferenceSuffix)
: null,
// Other parameters
compatibilityLigatures: bp.compatibilityLigatures || null,
metricOverride: bp.metricOverride || null,
excludedCharRanges: bp.excludeChars?.ranges,
// Spacing derivation -- creating faster build for spacing variants
spacingDerive
};
});
function fetchHintReferenceSuffix(sfm) {
if (sfm["regular"]) return "regular";
let bestSuffix = null,
bestSfi = null;
for (const [suffix, sfi] of Object.entries(sfm)) {
if (
!bestSfi ||
Math.abs(sfi.shapeWeight - 400) < Math.abs(bestSfi.shapeWeight - 400) ||
(Math.abs(sfi.shapeWeight - 400) === Math.abs(bestSfi.shapeWeight - 400) &&
Math.abs(sfi.shapeSlopeAngle) < Math.abs(bestSfi.shapeSlopeAngle)) ||
(Math.abs(sfi.shapeWeight - 400) === Math.abs(bestSfi.shapeWeight - 400) &&
Math.abs(sfi.shapeSlopeAngle) === Math.abs(bestSfi.shapeSlopeAngle) &&
Math.abs(sfi.shapeWidth - 500) < Math.abs(bestSfi.shapeWidth - 500))
) {
bestSuffix = suffix;
bestSfi = sfi;
}
}
return bestSuffix;
}
function getSuffixMapping(weights, slopes, widths) {
const mapping = {};
for (const w in weights) {
validateRecommendedWeight(w, weights[w].menu, "Menu");
validateRecommendedWeight(w, weights[w].css, "CSS");
for (const s in slopes) {
for (const wd in widths) {
const suffix = makeSuffix(w, wd, s, DEFAULT_SUBFAMILY);
mapping[suffix] = getSuffixMappingItem(weights, w, slopes, s, widths, wd);
}
}
}
return mapping;
}
function getSuffixMappingItem(weights, w, slopes, s, widths, wd) {
const weightDef = wwsDefValidate("Weight definition of " + s, weights[w]);
const widthDef = wwsDefValidate("Width definition of " + s, widths[wd]);
const slopeDef = wwsDefValidate("Slope definition of " + s, slopes[s]);
return {
// Weights
weight: w,
shapeWeight: nValidate("Shape weight of " + w, weightDef.shape, VlShapeWeight),
cssWeight: nValidate("CSS weight of " + w, weightDef.css, VlCssWeight),
menuWeight: nValidate("Menu weight of " + w, weightDef.menu, VlMenuWeight),
// Widths
width: wd,
shapeWidth: nValidate("Shape width of " + wd, widthDef.shape, VlShapeWidth),
cssStretch: sValidate("CSS stretch of " + wd, widthDef.css, VlCssFontStretch),
menuWidth: nValidate("Menu width of " + wd, widthDef.menu, VlMenuWidth),
// Slopes
slope: s,
shapeSlope: sValidate("Shape slope of " + s, slopeDef.shape, VlShapeSlope),
shapeSlopeAngle: nValidate("Angle of " + s, slopeDef.angle, VlSlopeAngle),
cssStyle: sValidate("CSS style of " + s, slopeDef.css, VlCssStyle),
menuSlope: sValidate("Menu slope of " + s, slopeDef.menu, VlShapeSlope)
};
}
function makeFileName(prefix, suffix) {
return prefix + "-" + suffix;
}
function makeSuffix(w, wd, s, fallback) {
return (
(wd === WIDTH_NORMAL ? "" : wd) +
(w === WEIGHT_NORMAL ? "" : w) +
(s === SLOPE_NORMAL ? "" : s) || fallback
);
}
function whyBuildPlanIsnNotThere(gid) {
if (!FS.existsSync(PRIVATE_BUILD_PLANS))
return "\n -- Possible reason: Config file 'private-build-plans.toml' does not exist.";
return "";
}
///////////////////////////////////////////////////////////
////// Font Building //////
///////////////////////////////////////////////////////////
const ageKey = uuid.v4();
const DistUnhintedTTF = file.make(
(gr, fn) => `${DIST}/${gr}/TTF-Unhinted/${fn}.ttf`,
async (target, out, gr, fn) => {
await target.need(Scripts, Parameters, Dependencies, de(out.dir));
const [fi] = await target.need(FontInfoOf(fn));
const charMapPath = file.getPathOf(BuildCM(gr, fn));
const ttfaControlsPath = file.getPathOf(BuildTtfaControls(gr, fn));
if (fi.spacingDerive) {
// The font is a spacing variant, and is derivable form an existing
// normally-spaced variant.
const noGcTtfPath = file.getPathOf(BuildNoGcUnhintedTtfImpl(gr, fn));
const spD = fi.spacingDerive;
const [deriveFrom] = await target.need(
DistUnhintedTTF(spD.prefix, spD.fileName),
de(charMapPath.dir)
);
echo.action(echo.hl.command(`Create TTF`), out.full);
await silently.node(`packages/font/src/derive-spacing.mjs`, {
i: deriveFrom.full,
o: out.full,
paramsDir: Path.resolve("params"),
oNoGc: noGcTtfPath.full,
...fi
});
} else {
// Ab-initio build
const cacheFileName =
`${Math.round(1000 * fi.shape.weight)}-${Math.round(1000 * fi.shape.width)}-` +
`${Math.round(3600 * fi.shape.slopeAngle)}-${fi.shape.slope}`;
const cachePath = `${SHARED_CACHE}/${cacheFileName}.mpz`;
const cacheDiffPath = `${charMapPath.dir}/${fn}.cache.mpz`;
const [comps] = await target.need(
CompositesFromBuildPlan,
de(charMapPath.dir),
de(ttfaControlsPath.dir),
de(SHARED_CACHE)
);
echo.action(echo.hl.command(`Create TTF`), out.full);
const { cacheUpdated } = await silently.node("packages/font/src/index.mjs", {
o: out.full,
...(fi.buildCharMap ? { oCharMap: charMapPath.full } : {}),
paramsDir: Path.resolve("params"),
oTtfaControls: ttfaControlsPath.full,
cacheFreshAgeKey: ageKey,
iCache: cachePath,
oCache: cacheDiffPath,
compositesFromBuildPlan: comps,
...fi
});
if (cacheUpdated) {
const lock = build.locks.alloc(cacheFileName);
await lock.acquire();
await silently.node(`packages/font/src/merge-cache.mjs`, {
base: cachePath,
diff: cacheDiffPath,
version: fi.menu.version,
freshAgeKey: ageKey
});
lock.release();
}
}
}
);
const BuildCM = file.make(
(gr, f) => `${BUILD}/TTF/${gr}/${f}.charmap.mpz`,
async (target, output, gr, f) => {
await target.need(DistUnhintedTTF(gr, f));
}
);
const BuildTtfaControls = file.make(
(gr, f) => `${BUILD}/TTF/${gr}/${f}.ttfa.txt`,
async (target, output, gr, f) => {
await target.need(DistUnhintedTTF(gr, f));
}
);
const BuildNoGcUnhintedTtfImpl = file.make(
(gr, f) => `${BUILD}/TTF/${gr}/${f}.no-gc.ttf`,
async (target, output, gr, f) => {
await target.need(DistUnhintedTTF(gr, f));
}
);
const BuildNoGcTtfImpl = file.make(
(gr, f) => `${BUILD}/TTF/${gr}/${f}.no-gc.hinted.ttf`,
async (target, output, gr, f) => {
await target.need(DistHintedTTF(gr, f));
}
);
const DistHintedTTF = file.make(
(gr, fn) => `${DIST}/${gr}/TTF/${fn}.ttf`,
async (target, out, gr, fn) => {
const [fi, hint] = await target.need(
FontInfoOf(fn),
CheckTtfAutoHintExists,
de`${out.dir}`
);
if (fi.spacingDerive) {
// The font is a spacing variant, and is derivable form an existing
// normally-spaced variant.
const spD = fi.spacingDerive;
const noGcTtfPath = file.getPathOf(BuildNoGcTtfImpl(gr, fn));
const [deriveFrom] = await target.need(
DistHintedTTF(spD.prefix, spD.fileName),
de(noGcTtfPath.dir)
);
echo.action(echo.hl.command(`Hint TTF`), out.full);
await silently.node(`packages/font/src/derive-spacing.mjs`, {
i: deriveFrom.full,
oNoGc: noGcTtfPath.full,
o: out.full,
paramsDir: Path.resolve("params"),
...fi
});
} else {
const [from, ttfaControls] = await target.need(
DistUnhintedTTF(gr, fn),
BuildTtfaControls(gr, fn)
);
echo.action(echo.hl.command(`Hint TTF`), out.full, echo.hl.operator("<-"), from.full);
await silently.run(hint, fi.hintParams, "-m", ttfaControls.full, from.full, out.full);
}
}
);
const BuildNoGcTtf = task.make(
(gr, fn) => `BuildNoGcTtf::${gr}/${fn}`,
async (target, gr, fn) => {
const [fi] = await target.need(FontInfoOf(fn));
if (fi.spacingDerive) {
const [noGc] = await target.need(BuildNoGcTtfImpl(gr, fn));
return noGc;
} else {
const [distUnhinted] = await target.need(DistHintedTTF(gr, fn));
return distUnhinted;
}
}
);
function formatSuffix(fmt, unhinted) {
return fmt + (unhinted ? "-Unhinted" : "");
}
const DistWoff2 = file.make(
(gr, fn, unhinted) => `${DIST}/${gr}/${formatSuffix("WOFF2", unhinted)}/${fn}.woff2`,
async (target, out, group, f, unhinted) => {
const Ctor = unhinted ? DistUnhintedTTF : DistHintedTTF;
const [from] = await target.need(Ctor(group, f), de`${out.dir}`);
echo.action(echo.hl.command("Create WOFF2"), out.full, echo.hl.operator("<-"), from.full);
await silently.node(`tools/misc/src/ttf-to-woff2.mjs`, from.full, out.full);
}
);
///////////////////////////////////////////////////////////
////// Font Distribution //////
///////////////////////////////////////////////////////////
// Group-level entry points
const Entry_GroupContents = task.group("contents", async (target, gr) => {
await target.need(Entry_GroupFonts(gr), Entry_GroupUnhintedFonts(gr));
return gr;
});
const Entry_GroupTTFs = task.group("ttf", async (target, gr) => {
await target.need(GroupTtfsImpl(gr, false));
});
const Entry_GroupUnhintedTTFs = task.group("ttf-unhinted", async (target, gr) => {
await target.need(GroupTtfsImpl(gr, true));
});
const Entry_GroupWoff2s = task.group("woff2", async (target, gr) => {
await target.need(GroupWoff2Impl(gr, false));
});
const Entry_GroupUnhintedWoff2s = task.group("woff2-unhinted", async (target, gr) => {
await target.need(GroupWoff2Impl(gr, true));
});
const Entry_GroupWebFonts = task.group("webfont", async (target, gr) => {
await target.need(GroupWebFontsImpl(gr, false));
});
const Entry_GroupUnhintedWebFonts = task.group("webfont-unhinted", async (target, gr) => {
await target.need(GroupWebFontsImpl(gr, true));
});
const Entry_GroupFonts = task.group("fonts", async (target, gr) => {
await target.need(GroupTtfsImpl(gr, false), GroupWebFontsImpl(gr, false));
});
const Entry_GroupUnhintedFonts = task.group("fonts-unhinted", async (target, gr) => {
await target.need(GroupTtfsImpl(gr, true), GroupWebFontsImpl(gr, true));
});
// Webfont CSS
const DistWebFontCSS = file.make(
(gr, unhinted) => `${DIST}/${gr}/${formatSuffix(gr, unhinted)}.css`,
async (target, out, gr, unhinted) => {
const [plan] = await target.need(BuildPlanOf(gr));
await target.need(de(out.dir));
await createWebFontCssImpl(target, out.full, gr, plan.webfontFormats, unhinted);
}
);
async function createWebFontCssImpl(target, output, gr, formats, unhinted) {
const [bp, ts] = await target.need(BuildPlanOf(gr), GroupFontsOf(gr));
const hs = await target.need(...ts.map(FontInfoOf));
echo.action(echo.hl.command(`Create WebFont CSS`), output, echo.hl.operator("<-"), gr);
await silently.node(
"tools/misc/src/make-webfont-css.mjs",
output,
bp.family,
hs,
formats,
unhinted
);
}
// Content files
const GroupTtfsImpl = task.make(
(gr, unhinted) => `group-${formatSuffix("TTFImpl", unhinted)}::${gr}`,
async (target, gr, unhinted) => {
const Ctor = unhinted ? DistUnhintedTTF : DistHintedTTF;
const [ts] = await target.need(GroupFontsOf(gr));
await target.need(ts.map(tn => Ctor(gr, tn)));
return gr;
}
);
const GroupWoff2Impl = task.make(
(gr, unhinted) => `group-${formatSuffix("WOFF2Impl", unhinted)}::${gr}`,
async (target, gr, unhinted) => {
const [ts] = await target.need(GroupFontsOf(gr));
await target.need(ts.map(tn => DistWoff2(gr, tn, unhinted)));
return gr;
}
);
const GroupWebFontsImpl = task.make(
(gr, unhinted) => `group-${formatSuffix("WebFontImpl", unhinted)}::${gr}`,
async (target, gr, unhinted) => {
const [bp] = await target.need(BuildPlanOf(gr));
const groupsNeeded = [];
for (const ext of bp.webfontFormats) {
switch (ext) {
case "TTF":
groupsNeeded.push(GroupTtfsImpl(gr, unhinted));
break;
case "WOFF2":
groupsNeeded.push(GroupWoff2Impl(gr, unhinted));
break;
}
}
await target.need(groupsNeeded, DistWebFontCSS(gr, unhinted));
return gr;
}
);
///////////////////////////////////////////////////////////
////// Font Collection Plans //////
///////////////////////////////////////////////////////////
const CollectPlans = computed(`metadata:collect-plans`, async target => {
const [rawPlans] = await target.need(RawPlans);
return await getCollectPlans(target, rawPlans.collectPlans);
});
// eslint-disable-next-line complexity
async function getCollectPlans(target, rawCollectPlans) {
const plans = {};
let allCollectableGroups = new Set();
for (const collectPrefix in rawCollectPlans) {
const collect = rawCollectPlans[collectPrefix];
if (!collect.release) continue;
for (const gr of collect.from) allCollectableGroups.add(gr);
}
const amendedRawCollectPlans = { ...rawCollectPlans };
out: for (const gr of allCollectableGroups) {
for (const [k, cp] of Object.entries(rawCollectPlans)) {
if (cp.from.length === 1 && cp.from[0] === gr) continue out;
}
amendedRawCollectPlans[`SGr-` + gr] = { release: true, isAmended: true, from: [gr] };
}
for (const collectPrefix in amendedRawCollectPlans) {
const glyfTtcComposition = {};
const ttcComposition = {};
const collect = amendedRawCollectPlans[collectPrefix];
if (!collect || !collect.from || !collect.from.length) continue;
for (const prefix of collect.from) {
const [gri] = await target.need(BuildPlanOf(prefix));
const ttfFileNameSet = new Set(gri.targets);
const suffixMap = getSuffixMapping(gri.weights, gri.slopes, gri.widths);
for (const suffix in suffixMap) {
const sfi = suffixMap[suffix];
const ttfTargetName = makeFileName(prefix, suffix);
if (!ttfFileNameSet.has(ttfTargetName)) continue;
const glyfTtcFileName = fnStandardTtc(true, collectPrefix, suffixMap, sfi);
if (!glyfTtcComposition[glyfTtcFileName]) glyfTtcComposition[glyfTtcFileName] = [];
glyfTtcComposition[glyfTtcFileName].push({ dir: prefix, file: ttfTargetName });
const ttcFileName = fnStandardTtc(false, collectPrefix, suffixMap, sfi);
if (!ttcComposition[ttcFileName]) ttcComposition[ttcFileName] = [];
ttcComposition[ttcFileName].push(glyfTtcFileName);
}
}
plans[collectPrefix] = {
glyfTtcComposition,
ttcComposition,
groupDecomposition: [...collect.from],
inRelease: !!collect.release,
isAmended: !!collect.isAmended
};
}
return plans;
}
function fnStandardTtc(fIsGlyfTtc, prefix, suffixMapping, sfi) {
let optimalSfi = null,
maxScore = 0;
for (const ttcSuffix in suffixMapping) {
const sfiT = suffixMapping[ttcSuffix];
if (sfi.shapeWeight !== sfiT.shapeWeight) continue;
if (fIsGlyfTtc && sfi.shapeWidth !== sfiT.shapeWidth) continue;
if (fIsGlyfTtc && sfi.shapeSlopeAngle !== sfiT.shapeSlopeAngle) continue;
const score =
(sfiT.weight === WEIGHT_NORMAL ? 1 : 0) +
(sfiT.width === WIDTH_NORMAL ? 1 : 0) +
(sfiT.slope === SLOPE_NORMAL ? 1 : 0);
if (!optimalSfi || score > maxScore) {
maxScore = score;
optimalSfi = sfiT;
}
}
if (!optimalSfi) throw new Error("Unreachable: TTC name decision");
return `${prefix}-${makeSuffix(
optimalSfi.weight,
optimalSfi.width,
optimalSfi.slope,
DEFAULT_SUBFAMILY
)}`;
}
///////////////////////////////////////////////////////////
////// Font Collection //////
///////////////////////////////////////////////////////////
const SpecificTtc = task.group(`ttc`, async (target, cgr) => {
const [cPlan] = await target.need(CollectPlans);
const ttcFiles = Array.from(Object.keys(cPlan[cgr].ttcComposition));
await target.need(ttcFiles.map(pt => CollectedTtcFile(cgr, pt)));
});
const SpecificSuperTtc = task.group(`super-ttc`, async (target, cgr) => {
await target.need(CollectedSuperTtcFile(cgr));
});
const CollectedSuperTtcFile = file.make(
cgr => `${DIST_SUPER_TTC}/${cgr}.ttc`,
async (target, out, cgr) => {
const [cp] = await target.need(CollectPlans, de(out.dir));
const parts = Array.from(Object.keys(cp[cgr].glyfTtcComposition));
const [inputs] = await target.need(parts.map(pt => GlyfTtc(cgr, pt)));
await buildCompositeTtc(out, inputs);
}
);
const CollectedTtcFile = file.make(
(cgr, f) => `${DIST_TTC}/${cgr}/${f}.ttc`,
async (target, out, cgr, f) => {
const [cp] = await target.need(CollectPlans, de`${out.dir}`);
const parts = Array.from(new Set(cp[cgr].ttcComposition[f]));
const [inputs] = await target.need(parts.map(pt => GlyfTtc(cgr, pt)));
await buildCompositeTtc(out, inputs);
}
);
const GlyfTtc = file.make(
(cgr, f) => `${GLYF_TTC}/${cgr}/${f}.ttc`,
async (target, out, cgr, f) => {
const [cp] = await target.need(CollectPlans);
const parts = cp[cgr].glyfTtcComposition[f];
await buildGlyphSharingTtc(target, parts, out);
}
);
async function buildCompositeTtc(out, inputs) {
const inputPaths = inputs.map(f => f.full);
echo.action(echo.hl.command(`Create TTC`), out.full, echo.hl.operator("<-"), inputPaths);
await absolutelySilently.run(MAKE_TTC, ["-o", out.full], inputPaths);
}
async function buildGlyphSharingTtc(target, parts, out) {
await target.need(de`${out.dir}`);
const [ttfInputs] = await target.need(parts.map(part => BuildNoGcTtf(part.dir, part.file)));
const ttfInputPaths = ttfInputs.map(p => p.full);
echo.action(echo.hl.command(`Create TTC`), out.full, echo.hl.operator("<-"), ttfInputPaths);
await silently.run(MAKE_TTC, "-u", ["-o", out.full], ttfInputPaths);
}
///////////////////////////////////////////////////////////
////// Archives //////
///////////////////////////////////////////////////////////
// Collection Archives
const TtcZip = file.make(
(cgr, version) => `${ARCHIVE_DIR}/PkgTTC-${cgr}-${version}.zip`,
async (target, out, cgr) => {
const [cPlan] = await target.need(CollectPlans, de`${out.dir}`);
const ttcFiles = Array.from(Object.keys(cPlan[cgr].ttcComposition));
await target.need(ttcFiles.map(pt => CollectedTtcFile(cgr, pt)));
await CreateGroupArchiveFile(`${DIST_TTC}/${cgr}`, out, `*.ttc`);
}
);
const SuperTtcZip = file.make(
(cgr, version) => `${ARCHIVE_DIR}/SuperTTC-${cgr}-${version}.zip`,
async (target, out, cgr) => {
await target.need(de`${out.dir}`, CollectedSuperTtcFile(cgr));
await CreateGroupArchiveFile(DIST_SUPER_TTC, out, `${cgr}.ttc`);
}
);
// Single-group Archives
const GroupTtfZip = file.make(
(gr, version, unhinted) =>
`${ARCHIVE_DIR}/${formatSuffix("PkgTTF", unhinted)}-${gr}-${version}.zip`,
async (target, out, gr, _version_, unhinted) => {
await target.need(de`${out.dir}`);
await target.need(GroupTtfsImpl(gr, unhinted));
await CreateGroupArchiveFile(
`${DIST}/${gr}/${formatSuffix("TTF", unhinted)}`,
out,
"*.ttf"
);
}
);
const GroupWebZip = file.make(
(gr, version, unhinted) =>
`${ARCHIVE_DIR}/${formatSuffix("PkgWebFont", unhinted)}-${gr}-${version}.zip`,
async (target, out, gr, _version_, unhinted) => {
const [plan] = await target.need(BuildPlanOf(gr));
await target.need(de`${out.dir}`);
await target.need(GroupWebFontsImpl(gr, unhinted));
await CreateGroupArchiveFile(
`${DIST}/${gr}`,
out,
`${formatSuffix(gr, unhinted)}.css`,
...plan.webfontFormats.map(format => formatSuffix(format, unhinted))
);
}
);
async function CreateGroupArchiveFile(dir, out, ...files) {
const relOut = Path.relative(dir, out.full);
await rm(out.full);
echo.action(echo.hl.command("Create Archive"), out.full);
await cd(dir).silently.run(
[SEVEN_ZIP, "a"],
["-tzip", "-r", "-mx=9", "-mmt=off"],
relOut,
...files
);
}
///////////////////////////////////////////////////////////
////// Exports //////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
// Sample Images
const Pages = task(`pages`, async t => {
await t.need(
PagesDataExport,
PagesFontExport`Iosevka`,
PagesFontExport`IosevkaSlab`,
PagesFontExport`IosevkaAile`,
PagesFontExport`IosevkaEtoile`,
PagesFontExport`IosevkaQp`,
PagesFontExport`IosevkaQpSlab`,
PagesFontExport`IosevkaQpe`,
PagesFontExport`IosevkaQpeSlab`
);
});
const PagesDir = oracle(`pages-dir-path`, async t => {
const [rp] = await t.need(RawPlans);
if (!rp.buildOptions || !rp.buildOptions.__pagesDir) fail("Pages directory not found");
return rp.buildOptions.__pagesDir;
});
const PagesDataExport = task(`pages:data-export`, async t => {
const [version] = await t.need(Version);
const [pagesDir] = await t.need(PagesDir, Version, Parameters, UtilScripts);
const [cm, cmi, cmo] = await t.need(
BuildCM("Iosevka", "Iosevka-Regular"),
BuildCM("Iosevka", "Iosevka-Italic"),
BuildCM("Iosevka", "Iosevka-Oblique")
);
await node(`tools/generate-samples/src/tokenized-sample-code.mjs`, {
output: Path.resolve(pagesDir, "shared/tokenized-sample-code/alphabet.txt.json")
});
await node(`tools/data-export/src/index.mjs`, {
version,
paramsDir: Path.resolve("params"),
charMapPath: cm.full,
charMapItalicPath: cmi.full,
charMapObliquePath: cmo.full,
exportPathMeta: Path.resolve(pagesDir, "shared/data-import/raw/metadata.json"),
exportPathCov: Path.resolve(pagesDir, "shared/data-import/raw/coverage.json")
});
});
const PagesFontExport = task.group(`pages:font-export`, async (target, gr) => {
target.is.volatile();
const [pagesDir] = await target.need(PagesDir);
if (!pagesDir) return;
const outDir = Path.resolve(pagesDir, "shared/fonts/imports", gr);
await target.need(GroupWebFontsImpl(gr, false), de(outDir));
await cp(`${DIST}/${gr}/WOFF2`, Path.resolve(outDir, "WOFF2"));
await createWebFontCssImpl(target, Path.resolve(outDir, `${gr}.css`), gr, webfontFormatsPages);
await rm(Path.resolve(outDir, "TTF"));
});
const PagesFastFontExport = task.group(`pages:fast-font-export`, async (target, gr) => {
target.is.volatile();
const [pagesDir] = await target.need(PagesDir);
if (!pagesDir) return;
const outDir = Path.resolve(pagesDir, "shared/fonts/imports", gr);
await target.need(GroupTtfsImpl(gr, true), de(outDir));
// Next.js 12 has some problem about refreshing fonts, so write an empty CSS first
await createWebFontCssImpl(target, Path.resolve(outDir, `${gr}.css`), gr, null);
await Delay(2000);
// Then do the copy
await cp(`${DIST}/${gr}/TTF-Unhinted`, Path.resolve(outDir, "TTF"));
await createWebFontCssImpl(target, Path.resolve(outDir, `${gr}.css`), gr, webfontFormatsFast);
await rm(Path.resolve(outDir, "WOFF2"));
});
///////////////////////////////////////////////////////////
// README
const AmendReadme = task("amend-readme", async target => {
await target.need(
AmendReadmeFor("README.md"),
AmendReadmeFor("doc/stylistic-sets.md"),
AmendReadmeFor("doc/character-variants.md"),
AmendReadmeFor("doc/custom-build.md"),
AmendReadmeFor("doc/language-specific-ligation-sets.md"),
AmendReadmeFor("doc/cv-influences.md"),
AmendReadmeFor("doc/PACKAGE-LIST.md"),
AmendLicenseYear
);
});
const AmendReadmeFor = task.make(
f => `amend-readme::for::${f}`,
async (target, f) => {
const [version] = await target.need(Version, Parameters, UtilScripts);
const [rpFiles] = await target.need(ReleaseNotePackagesFile);
const [cm, cmi, cmo] = await target.need(
BuildCM("Iosevka", "Iosevka-Regular"),
BuildCM("Iosevka", "Iosevka-Italic"),
BuildCM("Iosevka", "Iosevka-Oblique")
);
return node(`tools/amend-readme/src/index.mjs`, {
version,
projectRoot: Path.resolve("."),
paramsDir: Path.resolve("params"),
mdFilePath: f,
releasePackagesJsonPath: rpFiles.full,
charMapPath: cm.full,
charMapItalicPath: cmi.full,
charMapObliquePath: cmo.full
});
}
);
const ReleaseNotePackagesFile = file(`${BUILD}/release-packages.json`, async (t, out) => {
const [cp] = await t.need(CollectPlans);
const [{ buildPlans }] = await t.need(BuildPlans);
let releaseNoteGroups = {};
for (const [k, plan] of Object.entries(cp)) {
if (!plan.inRelease || plan.isAmended) continue;
const primePlan = buildPlans[plan.groupDecomposition[0]];
let subGroups = {};
for (const gr of plan.groupDecomposition) {
const bp = buildPlans[gr];
subGroups[gr] = {
family: bp.family,
desc: bp.desc,
spacing: buildPlans[gr].spacing || "type"
};
}
releaseNoteGroups[k] = {
subGroups,
slab: primePlan.serifs === "slab",
quasiProportional: primePlan.spacing === "quasi-proportional"
};
}
await FS.promises.writeFile(out.full, JSON.stringify(releaseNoteGroups, null, " "));
});
const AmendLicenseYear = task("amend-readme:license-year", async target => {
return node(`tools/amend-readme/src/license-year.mjs`, {