forked from live-codes/livecodes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
82 lines (74 loc) · 2.24 KB
/
Copy pathutils.ts
File metadata and controls
82 lines (74 loc) · 2.24 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
/// <reference path="../node_modules/@cloudflare/workers-types/index.d.ts" />
import { decompress } from './vendors/compression.js';
import { starterTemplates } from './vendors/templates.js';
type Env = Record<'API_TOKEN', string>;
type Data = Record<string, unknown>;
export type PgFunction = PagesFunction<Env, 'id', Data>;
export type Context = EventContext<Env, 'id', Data>;
interface ProjectInfo {
title?: string;
description?: string;
}
const isCompressedCode = (url: string) => url.startsWith('code/');
const importCompressedCode = (url: string) => {
const code = url.slice(5);
let config: ProjectInfo;
try {
config = JSON.parse(decompress(code) || '{}');
} catch (error) {
config = {};
}
return config;
};
const isProjectId = (url: string) => url.startsWith('id/');
const importProject = async (url: string): Promise<ProjectInfo> => {
const id = url.slice(3);
const apiUrl =
id.length < 11
? 'https://dpaste.com/' + id + '.txt' // for backward compatibility
: 'https://api2.livecodes.io/share?id=' + id;
try {
const res = await fetch(apiUrl);
if (!res.ok) return {};
return JSON.parse(await res.text());
} catch (error) {
return {};
}
};
export const getProjectInfo = async (url: URL): Promise<ProjectInfo> => {
const title = url.searchParams.get('title');
const description = url.searchParams.get('description');
if (title || description) {
return {
title: title || '',
description: description || '',
};
}
const imports = url.searchParams.get('x') || url.hash.slice(1);
if (isCompressedCode(imports)) {
const config = importCompressedCode(imports);
return {
title: config.title || '',
description: config.description || '',
};
}
if (isProjectId(imports)) {
const config = await importProject(imports);
return {
title: config.title || '',
description: config.description || '',
};
}
const template = url.searchParams.get('template');
const templateName = template ? starterTemplates.find((t) => t.name === template)?.title : '';
if (templateName) {
return {
title: templateName,
description: templateName + ' Template on LiveCodes',
};
}
return {
title: '',
description: '',
};
};