This repository has been archived by the owner on Sep 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.ts
77 lines (59 loc) · 1.8 KB
/
build.ts
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
import { readFile, writeFile } from 'fs/promises';
import { build } from 'tsup';
import prettier from 'prettier';
const warnings = ['\nWarnings:'];
const lightonMuseFile = './node_modules/lighton-muse/dist/index.js';
// Patch `lighton-muse` dependency to avoid bundling `node-fetch`.
const lightonMuseContent = await readFile(lightonMuseFile, 'utf-8');
try {
await writeFile(
lightonMuseFile,
lightonMuseContent.replace(/import .* from "node-fetch";\n/gu, '')
);
warnings.push('⚠️ Patched lighton-muse to avoid bundling node-fetch.');
warnings.push('⚠️ You cannot use the exported `MuseRequest` class.');
} catch (err) {
console.error(err);
}
// First build the files
await build({
entry: ['src/index.ts'],
format: 'iife',
target: 'es2019',
outExtension() {
return {
js: '.js',
};
},
});
// Retrieve the prettier config
const prettierConfig = await prettier.resolveConfig('.prettierrc.json');
if (!prettierConfig) {
throw new Error('No prettier config found');
}
// Get the generated JS bundle
const bundleContent = await readFile('./dist/index.js', 'utf8');
// Extract the banner ('use strict';) and the IIFE (Immediately Invoked Function Expression) body
const result = bundleContent.match(
/(?<banner>.*)\n\(\(\) => \{\n(?<body>(.*?\n)*)\}\)\(\);/muy
);
if (!result) {
throw new Error('Could not find code to transform');
}
const output = `\
/* Code generated with \`tsup\` and a custom tool from LightOn */
${result.groups?.banner}
${result.groups?.body.replace(/\n {4}/gu, '\n')}
`;
// Format the output using prettier
const formattedFile = prettier.format(output, {
parser: 'babel',
...prettierConfig,
});
// Writes the output for Clasp in index.gs
try {
await writeFile('./index.gs', formattedFile);
} catch (err) {
console.error(err);
}
warnings.forEach((warn) => console.log(warn));