-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutil.ts
More file actions
1369 lines (1279 loc) · 37 KB
/
util.ts
File metadata and controls
1369 lines (1279 loc) · 37 KB
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 {
camelCase,
DateTimeFormatter,
DigestClient,
fs,
kebabCase,
mustache,
path,
posixPath,
S3Bucket,
slug as slugFn,
YAML,
} from "./deps.ts";
import { NotFound } from "./error.ts";
import { DEV_MODE_HANDLED_ITEMS, ROOT_DOMAIN } from "./constant.ts";
import log from "./log.ts";
import {
Config,
FilteredFile,
Language,
Link,
PageMeta,
ParsedArchiveUrl,
ParsedFilename,
ParsedFilenameWithTime,
Rule,
SiteConfig,
Source,
SourceAPIConfig,
UrlInfo,
Version,
WeekOfYear,
} from "./interface.ts";
export const SECOND = 1e3;
export const MINUTE = SECOND * 60;
export const HOUR = MINUTE * 60;
export const DAY = HOUR * 24;
export const WEEK = DAY * 7;
const DAYS_PER_WEEK = 7;
enum Day {
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat,
}
export async function request(url: string, init: RequestInit = {}) {
const c = new AbortController();
const id = setTimeout(() => c.abort(), 30000);
const headers = new Headers(init.headers);
headers.set(
"User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.48",
);
headers.set(
"accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
);
headers.set("accept-language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
headers.set("cache-control", "no-cache");
// set cookie if host is news.google.com
const urlObj = new URL(url);
const _hostParams = urlObj.searchParams.get("_host");
if (urlObj.hostname === "news.google.com" || _hostParams) {
const GOOGLE_COOKIE = Deno.env.get("GOOGLE_COOKIE") as string;
if (GOOGLE_COOKIE) {
console.log("yes, detect GOOGLE_COOKIE");
}
// GOOGLE_COOKIE
headers.set("cookie", GOOGLE_COOKIE);
}
const params = {
...init,
signal: c.signal,
headers,
};
const r = await fetch(url, params);
clearTimeout(id);
if (!r.ok) {
throw new Error(`Request failed: ${url}, ${r.status}`);
}
return r;
}
export const get = (obj: unknown, path: string, defaultValue = undefined) => {
const travel = (regexp: RegExp) =>
String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce(
(res, key) =>
res !== null && res !== undefined
? (res as Record<string, string>)[key]
: res,
obj,
);
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
return result === undefined || result === obj ? defaultValue : result;
};
export const isDev = () => {
return Deno.env.get("PROD") !== "1";
};
export const isMock = () => {
if (isDev()) {
return Deno.env.get("MOCK") !== "0";
} else {
return false;
}
};
export const isDebug = () => {
return Deno.env.get("DEBUG") === "1";
};
export const getDataPath = () => {
const dataPath = isDev() ? "current" : "prod-current";
return dataPath;
};
export const getRecentlySiteStatPath = () => {
const recentlySitesPath = path.join(getDataPath(), "recently-sites.json");
return recentlySitesPath;
};
export const getRecentlySourcesStatPath = () => {
const recentlySitesPath = path.join(getDataPath(), "recently-sources.json");
return recentlySitesPath;
};
export const getFeedSiteIdentifiers = (config: Config) => {
const sitesMap = config.sites;
const keys = Object.keys(sitesMap);
const siteIdentifiers = keys.filter((key) => {
const site = sitesMap[key];
return !site.dev && !site.standalone;
});
return siteIdentifiers;
};
export const getArchivePath = () => {
const dataPath = isDev() ? "archive" : "prod-archive";
return dataPath;
};
export const getProdArchivePath = () => {
return "prod-archive";
};
export const getDistPath = () => {
const dataPath = isDev() ? "public" : "prod-public";
return dataPath;
};
// this directory is used to store processing files
// like formated, translated, etc.
// most time this will not be store files
// only when failed at some step, we will store the processed files here
export const getCachePath = () => {
const dataPath = isDev() ? "cache" : "prod-cache";
return dataPath;
};
// this directory will not be load when build
export const getTempPath = () => {
const dataPath = isDev() ? "temp" : "prod-temp";
return dataPath;
};
export const getChangedSitePaths = () => {
return path.join(getTempPath(), "changed-sites.json");
};
export const getSiteIdentifierDistPath = (siteIdentifier: string) => {
return `${getDistPath()}/${siteIdentifierToPath(siteIdentifier)}`;
};
export const getDistFilePath = (siteIdentifier: string, file: string) => {
return path.join(getDistPath(), siteIdentifierToPath(siteIdentifier), file);
};
export const getDataRawPath = () => {
return `${getCachePath()}/1-raw`;
};
export const tryGetSiteByFolderPath = (folderPath: string): string | null => {
const basename = path.basename(folderPath);
if (basename.startsWith("site_")) {
return basename.substring(5);
} else {
return null;
}
};
export const getDataFormatedPath = () => {
return `${getCachePath()}/2-formated`;
};
export const getDataTranslatedPath = () => {
return `${getCachePath()}/3-translated`;
};
export const getDataCurrentItemsPath = () => {
return `${getDataPath()}/items`;
};
export const getDataStatsDirPath = () => {
return path.join(getDataPath(), "stats");
};
export const getDataStatsPath = (year: number) => {
return path.join(getDataStatsDirPath(), `${year}.json`);
};
export const getDevDataCurrentItemsPath = () => {
return `current/items`;
};
export const getMigratedIssueMapPath = () => {
if (isDev()) {
return `./migrations/issue-map.json`;
} else {
return `./migrations/prod-issue-map.json`;
}
};
export const getCurrentItemsFilePath = (siteIdentifier: string) => {
return `${getDataCurrentItemsPath()}/${siteIdentifierToPath(
siteIdentifier,
)}/items.json`;
};
export const getCurrentKeysFilePath = (siteIdentifier: string) => {
return `${getDataCurrentItemsPath()}/${siteIdentifierToPath(
siteIdentifier,
)}/keys.json`;
};
export const getCurrentToBeArchivedItemsFilePath = (siteIdentifier: string) => {
return `${getDataCurrentItemsPath()}/${siteIdentifierToPath(
siteIdentifier,
)}/to-be-archived-items.json`;
};
export const readJSONFile = async (path: string) => {
const file = await Deno.readTextFile(path);
return JSON.parse(file);
};
export const writeTextFile = async (filePath: string, text: string) => {
// ensure dir exists
const dir = path.dirname(filePath);
await fs.ensureDir(dir);
await Deno.writeTextFile(filePath, text);
};
export const writeJSONFile = async (filePath: string, data: unknown) => {
const file = JSON.stringify(data, null, 2);
// ensure dir exists
const dir = path.dirname(filePath);
await fs.ensureDir(dir);
await Deno.writeTextFile(filePath, file + "\n");
};
export const getFullYear = (date: Date): string => {
return date.getUTCFullYear().toString();
};
export const getFullMonth = (date: Date): string => {
const month = date.getUTCMonth() + 1;
return month < 10 ? `0${month}` : month.toString();
};
export const getFullDay = (date: Date): string => {
const day = date.getUTCDate();
return day < 10 ? `0${day}` : day.toString();
};
export const getConfig = async function (): Promise<Config> {
const config = YAML.parse(await Deno.readTextFile("config.yml")) as Config;
return config;
};
export const getGenConfig = async function (): Promise<Config> {
const config = (await readJSONFile("./config.gen.json")) as Config;
return config;
};
export const formatIsoDate = (date: Date): string => {
const beijingDate = new Date(date.getTime() + 8 * 60 * 60 * 1000);
return beijingDate.toISOString().replace("Z", "+08:00");
};
export const formatBeijing = (date: Date, formatString: string) => {
date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
const formatter = new DateTimeFormatter(formatString);
return formatter.format(date, {
timeZone: "UTC",
});
};
export const getBeijingDay = (date: Date): string => {
date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
const formatter = new DateTimeFormatter("MM-dd");
return formatter.format(date, {
timeZone: "UTC",
});
};
export const formatHumanTime = (date: Date) => {
const now = new Date();
const nowDate = formatBeijing(now, "yyyy-MM-dd");
const dateDate = formatBeijing(date, "yyyy-MM-dd");
const isToday = nowDate === dateDate;
const nowYear = formatBeijing(now, "yyyy");
const dateYear = formatBeijing(date, "yyyy");
const isThisYear = nowYear === dateYear;
if (isToday) {
return formatBeijing(date, "HH:mm");
} else if (isThisYear) {
return formatBeijing(date, "MM-dd");
} else {
return formatBeijing(date, "yy-MM-dd");
}
};
export const getArchivedFilePath = function (
siteIdentifier: string,
relativePath: string,
): string {
let filePath = getArchivePath() + "/" + siteIdentifierToPath(siteIdentifier);
// remove relative path slashes
if (relativePath.startsWith("/")) {
relativePath = relativePath.substring(1);
}
filePath += "/" + relativePath;
return filePath;
};
export const siteIdentifierToPath = (siteIdentifier: string) => {
// return siteIdentifier.replace(/\./g, "_");
//
return siteIdentifier;
};
export const siteIdentifierToDomain = (
siteIdentifier: string,
site?: SiteConfig,
) => {
if (site && site.domain) {
return site.domain;
}
if (siteIdentifier.includes(".")) {
return siteIdentifier;
}
return `${siteIdentifier}.${ROOT_DOMAIN}`;
};
export const urlToSiteIdentifier = (url: string, config: Config) => {
const urlObj = new URL(url);
if (urlObj.hostname === "localhost") {
for (const siteDdentifier in config.sites) {
const siteConfig = config.sites[siteDdentifier];
if (Number(siteConfig.port) === Number(urlObj.port)) {
return siteDdentifier;
}
}
throw new Error("Cannot find siteIdentifier for " + url);
} else {
let hostname = urlObj.hostname;
if (urlObj.hostname.startsWith("dev-")) {
hostname = hostname.substring(4);
}
// check if any site has a custom domain matching this hostname
for (const siteId in config.sites) {
if (config.sites[siteId].domain === hostname) {
return siteId;
}
}
return hostname.replace(`.${ROOT_DOMAIN}`, "");
}
};
export const siteIdentifierToUrl = (
siteIdentifier: string,
pathname: string,
config: Config,
): string => {
let port: number;
const siteConfig = config.sites[siteIdentifier];
port = siteConfig.port || 8000;
// pathname add start slash
if (!pathname.startsWith("/")) {
pathname = "/" + pathname;
}
const isWorkersDev = Deno.env.get("WORKERS_DEV") === "1";
if (isWorkersDev) {
return `https://dev-${siteIdentifierToDomain(
siteIdentifier,
config.sites[siteIdentifier],
)}${pathname}`;
} else if (isDev()) {
return `http://localhost:${port}${pathname}`;
} else {
return `https://${siteIdentifierToDomain(
siteIdentifier,
config.sites[siteIdentifier],
)}${pathname}`;
}
};
export const feedjsonUrlToRssUrl = (url: string) => {
return url.replace("/feed.json", "/feed.xml");
};
export const urlToLanguageUrl = (
url: string,
languagePrefix: string,
versions: Version[],
languages: Language[],
) => {
const urlInfo = parsePageUrl(url, versions, languages);
const urlObj = new URL(url);
// check if url has a prefix
urlObj.pathname = `/${languagePrefix}${urlInfo.version.prefix}${urlInfo.pathname.slice(
1,
)}`;
return urlObj.toString();
};
export const urlToVersionUrl = (
url: string,
versionPrefix: string,
versions: Version[],
languages: Language[],
) => {
const urlInfo = parsePageUrl(url, versions, languages);
const urlObj = new URL(url);
// check if url has a prefix
urlObj.pathname = `/${urlInfo.language.prefix}${versionPrefix}${urlInfo.pathname.slice(
1,
)}`;
return urlObj.toString();
};
export const parsePageUrl = (
url: string,
versions: Version[],
lanuguages: Language[],
): UrlInfo => {
const urlObj = new URL(url);
// get language code
const langField = urlObj.pathname.split("/")[1];
// check if language code is valid
let language = lanuguages[0];
let pathname = urlObj.pathname;
for (const targetLang of lanuguages) {
let prefix = targetLang.prefix;
// remove trailing slash
if (prefix.endsWith("/")) {
prefix = prefix.slice(0, -1);
}
if (prefix === langField) {
language = targetLang;
pathname = urlObj.pathname.slice(targetLang.prefix.length);
break;
}
}
const versionField = pathname.split("/")[1];
// check if language code is valid
let version = versions[0];
for (const targetVersion of versions) {
let prefix = targetVersion.prefix;
// remove trailing slash
if (prefix.endsWith("/")) {
prefix = prefix.slice(0, -1);
}
if (prefix === versionField) {
version = targetVersion;
pathname = pathname.slice(targetVersion.prefix.length);
break;
}
}
urlObj.pathname = pathname;
const newUrl = urlObj.toString();
return {
language,
version,
pathname,
url: newUrl,
};
};
export const pathToSiteIdentifier = (path: string) => {
return path;
};
export const arrayToObj = <T>(arr: T[], key = "id"): Record<string, T> => {
const obj: Record<string, T> = {};
for (const item of arr) {
obj[(item as unknown as Record<string, string>)[key]] = item;
}
return obj;
};
export const getItemTranslations = function (
translations: Record<string, Record<string, string>>,
languageCode: string,
originalLanguageCode: string,
): Record<string, string> {
return translations[languageCode] || translations[originalLanguageCode] || {};
};
// item.json -> /
// tags/show-hn/item.json -> /tags/show-hn/
export const itemsPathToURLPath = function (itemsPath: string) {
const removedPath = itemsPath.replace(/items\.json$/, "");
if (!removedPath.endsWith("/")) {
return removedPath + "/";
}
if (!removedPath.startsWith("/")) {
return "/" + removedPath;
}
return removedPath;
};
export const getPageMeta = (itemsRelativePath: string): PageMeta => {
const pathArr = itemsRelativePath.split("/");
let pageType = "index";
let meta: Record<string, string> = {};
if (pathArr.length >= 2) {
const rootField = pathArr[2];
if (rootField === "tags") {
pageType = "tag";
meta = {
tagIdentifier: pathArr[2],
};
} else if (rootField === "archive") {
pageType = "archive";
meta = {
year: pathArr[3],
week: pathArr[4],
};
} else if (rootField === "issues") {
pageType = "issues";
meta = {
year: pathArr[3],
week: pathArr[4],
};
} else if (rootField === "posts") {
pageType = "posts";
meta = {
year: pathArr[3],
week: pathArr[4],
id: pathArr[5],
};
}
}
return {
type: pageType,
meta: meta,
};
};
export const urlToFilePath = (url: string): string => {
const urlObj = new URL(url);
const pathname = urlObj.pathname;
let filepath = pathname;
if (pathname === "/") {
filepath = "index.html";
} else {
filepath = pathname.slice(1);
}
if (filepath.endsWith("/")) {
filepath += "index.html";
} else {
// check is has extension
const basename = path.basename(filepath);
if (!basename.includes(".")) {
if (filepath.endsWith("/")) {
filepath += "index.html";
} else {
filepath += "/index.html";
}
}
}
return filepath;
};
export const getArchiveS3Bucket = (bucket: string): S3Bucket => {
const params = {
accessKeyID: Deno.env.get("AWS_ACCESS_KEY_ID")!,
secretKey: Deno.env.get("AWS_SECRET_ACCESS_KEY")!,
bucket: bucket,
region: Deno.env.get("AWS_DEFAULT_REGION")!,
endpointURL: Deno.env.get("AWS_ENDPOINT")!,
};
const s3Bucket = new S3Bucket(params);
return s3Bucket;
};
export const getCurrentDataS3Bucket = (bucket: string): S3Bucket => {
const s3Bucket = new S3Bucket({
accessKeyID: Deno.env.get("AWS_ACCESS_KEY_ID")!,
secretKey: Deno.env.get("AWS_SECRET_ACCESS_KEY")!,
bucket: bucket,
region: Deno.env.get("AWS_DEFAULT_REGION")!,
endpointURL: Deno.env.get("AWS_ENDPOINT")!,
});
return s3Bucket;
};
export const loadS3ArchiveFile = async (fileRelativePath: string) => {
const AWS_BUCKET = getArchivedBucketName();
const s3Bucket = getArchiveS3Bucket(AWS_BUCKET);
const object = await s3Bucket.headObject(fileRelativePath);
if (object && object.etag) {
const getObject = await s3Bucket.getObject(fileRelativePath);
if (getObject) {
const { body } = getObject;
const data = await new Response(body).text();
await writeTextFile(fileRelativePath, data);
} else {
throw new Error(`loadS3ArchiveFile: getObject is null`);
}
}
};
export function getCurrentBucketName() {
return "feed";
}
export function getArchivedBucketName() {
return "feed";
}
export function getArchiveSitePrefix(config: Config) {
if (isDev()) {
return `http://localhost:${config.sites.i.port}`;
} else {
return `https://i.${ROOT_DOMAIN}`;
}
}
export const getCurrentTranslations = function (
siteIdentifier: string,
languageCode: string,
config: Config,
): Record<string, string> {
let currentTranslations: Record<string, string> = {};
const sitesMap = config.sites;
const siteConfig = sitesMap[siteIdentifier];
// merge site translations
const generalTranslations = getGeneralTranslations(languageCode, config);
let siteTranslations = {};
if (siteConfig.translations) {
siteTranslations =
siteConfig.translations[languageCode] ??
siteConfig.translations["zh-Hans"] ??
{};
}
currentTranslations = {
...generalTranslations,
...siteTranslations,
};
return currentTranslations;
};
export const getGeneralTranslations = function (
languageCode: string,
config: Config,
) {
let currentTranslations: Record<string, string> = {};
const translations = config.translations;
// merge site translations
const generalTranslations = translations[languageCode] ?? {};
const defaultTranslations = translations["zh-Hans"] ?? {};
currentTranslations = {
...defaultTranslations,
...generalTranslations,
};
return currentTranslations;
};
export function resortSites(
siteIdentifier: string,
siteIdentifiers: string[],
config: Config,
) {
const relatedSites = config.sites[siteIdentifier].related ?? [];
// by priority
// lower is more priority
const sitesMap = config.sites;
const sortedSites = siteIdentifiers.sort((a, b) => {
if (relatedSites.includes(a) && relatedSites.includes(b)) {
const aPriority = sitesMap[a].priority ?? 50;
const bPriority = sitesMap[b].priority ?? 50;
return aPriority - bPriority;
} else if (relatedSites.includes(a)) {
return -1;
} else if (relatedSites.includes(b)) {
return 1;
} else {
const aPriority = sitesMap[a].priority ?? 50;
const bPriority = sitesMap[b].priority ?? 50;
return aPriority - bPriority;
}
});
return sortedSites;
}
export const resortArchiveKeys = function (currentArchive: string[]): string[] {
// write currentArchive file
// resort currentArchive by time
currentArchive = currentArchive.sort((a, b) => {
const splited = a.split("/");
const aYear = splited[0];
const aWeek = addZero(Number(splited[1]));
const aNum = Number("" + aYear + aWeek);
const splited2 = b.split("/");
const bYear = splited2[0];
const bWeek = addZero(Number(splited2[1]));
const bNum = Number("" + bYear + bWeek);
return bNum - aNum;
});
return currentArchive;
};
export const addZero = function (num: number): string {
if (num < 10) {
return "0" + num;
} else {
return "" + num;
}
};
export function weekOfYear(date: Date): WeekOfYear {
const workingDate = new Date(
Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()),
);
const day = workingDate.getUTCDay();
const nearestThursday =
workingDate.getUTCDate() +
Day.Thu -
(day === Day.Sun ? DAYS_PER_WEEK : day);
workingDate.setUTCDate(nearestThursday);
// Get first day of year
const yearStart = new Date(Date.UTC(workingDate.getUTCFullYear(), 0, 1));
const weekYear = workingDate.getUTCFullYear();
// return the calculated full weeks to nearest Thursday
const week = Math.ceil(
(workingDate.getTime() - yearStart.getTime() + DAY) / WEEK,
);
return {
year: weekYear,
week: week,
path: `${workingDate.getUTCFullYear()}/${week}`,
number: Number(`${weekYear}${addZero(week)}`),
};
}
export const isWeekBiggerThan = function (aDate: Date, bDate: Date): boolean {
const weekOfA = weekOfYear(aDate);
const weekOfB = weekOfYear(bDate);
if (weekOfA.number > weekOfB.number) {
return true;
}
return false;
};
export const slug = function (tag: string): string {
// @ts-ignore: npm module
return slugFn(kebabCase(tag));
};
export const tagToPascalCase = function (tag: string): string {
// @ts-ignore: npm module
const slugStr = slug(tag);
const splited = slugStr.split("-");
if (splited.length > 1) {
// @ts-ignore: npm module
const camel = camelCase(slugStr);
if (camel) {
// upper first letter
return camel.charAt(0).toUpperCase() + camel.slice(1);
} else {
return "";
}
} else {
return slugStr;
}
};
export async function sha1(message: string) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await crypto.subtle.digest("SHA-1", data);
const hashArray = Array.from(new Uint8Array(hash)); // convert buffer to byte array
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join(""); // convert bytes to hex string
return hashHex;
}
export function callWithTimeout<T>(func: unknown, timeout: number): Promise<T> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("timeout")), timeout);
// @ts-ignore: hard to type
func()
.then(
// @ts-ignore: hard to type
(response) => resolve(response),
// @ts-ignore: hard to type
(err) => {
const newerr = new Error(err);
// add stack
newerr.stack = err.stack;
return reject(newerr);
},
)
.finally(() => clearTimeout(timer));
});
}
export function tagToUrl(
tag: string,
siteIdentifier: string,
language: Language,
version: Version,
config: Config,
): string {
return `${getArchiveSitePrefix(
config,
)}/${language.prefix}${version.prefix}${siteIdentifier}/tags/${
// @ts-ignore: npm module
slug(tag)
}/`;
}
export function archiveToUrl(
archiveKey: string,
siteIdentifier: string,
language: Language,
version: Version,
config: Config,
): string {
return `${getArchiveSitePrefix(
config,
)}/${language.prefix}${version.prefix}${siteIdentifier}/archive/${archiveKey}/`;
}
export function issueToUrl(
issue: string,
siteIdentifier: string,
language: Language,
version: Version,
config: Config,
): string {
return `${getArchiveSitePrefix(
config,
)}/${language.prefix}${version.prefix}${siteIdentifier}/issues/${issue}/`;
}
export function postToUrl(
id: string,
siteIdentifier: string,
language: Language,
version: Version,
config: Config,
): string {
const parsed = parseItemIdentifier(id);
const utcDate = new Date(
Date.UTC(Number(parsed.year), Number(parsed.month) - 1, Number(parsed.day)),
);
const week = weekOfYear(utcDate);
return `${getArchiveSitePrefix(
config,
)}/${language.prefix}${version.prefix}${siteIdentifier}/posts/${week.path}/${id}/`;
}
export const formatNumber = (num: number): string => {
const formatter = Intl.NumberFormat("en", { notation: "compact" });
return formatter.format(num);
};
export const uploadFileToDufs = async (
client: DigestClient,
filepath: string,
) => {
// use fetch to put file
// const formData = new FormData();
// formData.append("file", new Blob([]));
const url = Deno.env.get("DUFS_URL")!;
if (!url) {
throw new Error("DUFS_URL is not set");
}
const response = await client.fetch(url + "/" + filepath, {
method: "PUT",
body: await Deno.readTextFile(filepath),
});
if (response.status === 201) {
return response;
} else {
throw new Error("upload failed " + filepath + " " + response.status);
}
};
export const getDufsClient = (): DigestClient => {
const secrets = Deno.env.get("DUFS_SECRETS");
const secretsArr = secrets?.split(":");
const username = secretsArr?.[0];
const password = secretsArr?.[1];
if (!username || !password) {
throw new Error("DUFS_SECRETS is not set");
}
const client = new DigestClient(username!, password!);
return client;
};
export function getTargetSiteIdentifiersByFilePath(filePath: string): string[] {
const targetSiteIdentifiers = path
.basename(path.dirname(filePath))
.split("_");
return targetSiteIdentifiers;
}
export async function getFilesByTargetSiteIdentifiers(
dirPath: string,
targetSiteIdentifiers: string[],
): Promise<FilteredFile> {
const sites = targetSiteIdentifiers || [];
const groups: Record<string, string[]> = {};
let files: string[] = [];
const siteTotalFiles: Record<string, number> = {};
const filteredSites: string[] = [];
for await (const entry of fs.walk(dirPath)) {
if (entry.isFile && entry.name.endsWith(".json")) {
// get siteIdentifiers
const dirname = path.dirname(entry.path);
const siteIdentifiers = path.basename(dirname).split("_");
for (const siteIdentifier of siteIdentifiers) {
if (sites.includes(siteIdentifier)) {
if (siteTotalFiles[siteIdentifier] === undefined) {
siteTotalFiles[siteIdentifier] = 0;
}
if (isDev()) {
if (siteTotalFiles[siteIdentifier] >= DEV_MODE_HANDLED_ITEMS) {
// log.info(`dev mode, only take ${DEV_MODE_HANDLED_ITEMS} files`);
break;
}
}
siteTotalFiles[siteIdentifier]++;
if (!filteredSites.includes(siteIdentifier)) {
filteredSites.push(siteIdentifier);
}
if (!groups[siteIdentifier]) {
groups[siteIdentifier] = [];
}
groups[siteIdentifier].push(entry.path);
files.push(entry.path);
}
}
}
}
// files need to unique
files = Array.from(new Set(files));
return {
files: files,
targetSiteIdentifiers: filteredSites,
groups,
};
}
export function parseItemIdentifier(fileBasename: string): ParsedFilename {
// remove extension
let filename = fileBasename;
if (filename.endsWith(".json")) {
filename = filename.slice(0, -5);
}
const parts = filename.split("__");
// first will be safe part, other will be the id parts
const safePart = parts[0];
const symParts = safePart.split("_");
const language = symParts[0];
const type = symParts[1];
const year = symParts[2];
const month = symParts[3];
const day = symParts[4];
const idParts = parts.slice(1);
const id = idParts.join("__");
return {
id,
language,
type,
year,
month,
day,
};
}
export function parseItemIdentifierWithTime(
fileBasename: string,
): ParsedFilenameWithTime {
// remove extension
let filename = fileBasename;
if (filename.endsWith(".json")) {
filename = filename.slice(0, -5);
}
const parts = filename.split("__");
// first will be safe part, other will be the id parts
const safePart = parts[0];
const symParts = safePart.split("_");
const language = symParts[0];
const type = symParts[1];
const year = symParts[2];
const month = symParts[3];
const day = symParts[4];
const hour = symParts[5];