-
-
Notifications
You must be signed in to change notification settings - Fork 653
Expand file tree
/
Copy pathbuild.ts
More file actions
194 lines (168 loc) · 6.09 KB
/
Copy pathbuild.ts
File metadata and controls
194 lines (168 loc) · 6.09 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
import fs from 'fs';
import path from 'path';
import glob from 'fast-glob';
import { fileURLToPath } from 'url';
import minimist from 'minimist';
import ts from "typescript";
import micromatch from 'micromatch';
import esbuild from "esbuild";
// we need to change up how __dirname is used for ES6 purposes
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* Get a list of the non-private sorted packages
*/
function getAllPackages(scope?: string | string[], ignore?: string | string[]) {
// Read workspace globs from pnpm-workspace.yaml
const content = fs.readFileSync(path.join(__dirname, 'pnpm-workspace.yaml'), 'utf-8');
const workspaceGlobs: string[] = [];
let inPackages = false;
for (const line of content.split('\n')) {
if (line.trim() === 'packages:') { inPackages = true; continue; }
if (inPackages) {
const match = line.match(/^\s+-\s+(.+)/);
if (match) {
workspaceGlobs.push(match[1].trim().replace(/['"]/g, ''));
} else if (line.trim() && !line.startsWith(' ') && !line.startsWith('\t')) {
break;
}
}
}
// Discover all package.json files matching workspace globs
const patterns = workspaceGlobs.map(g => `${g}/package.json`);
const packageJsonPaths = glob.sync(patterns, {
cwd: __dirname,
absolute: true,
ignore: ['**/node_modules/**'],
});
// Parse packages, filter out private ones
let packages = packageJsonPaths.map(pkgPath => {
const pkgJSON = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
return { name: pkgJSON.name as string, location: path.dirname(pkgPath), toJSON: () => pkgJSON };
}).filter(pkg => !pkg.toJSON().private);
// Apply --scope / --ignore filtering
if (scope || ignore) {
const names = packages.map(p => p.name);
const patterns: string[] = [];
if (scope) {
patterns.push(...(Array.isArray(scope) ? scope : [scope]));
} else {
patterns.push('**');
}
if (ignore) {
const excludes = Array.isArray(ignore) ? ignore : [ignore];
patterns.push(...excludes.map(p => `!${p}`));
}
const matched = new Set(micromatch(names, patterns));
packages = packages.filter(p => matched.has(p.name));
}
return packages;
}
async function main() {
// Support --scope and --ignore globs if passed in via commandline
const argv = minimist(process.argv.slice(2).filter(arg => arg !== '--'));
const packages = getAllPackages(argv.scope, argv.ignore);
packages.map(pkg => {
// Absolute path to package directory
const basePath = path.relative(__dirname, pkg.location);
// "main" field from package.json file.
const pkgJSON = pkg.toJSON();
// Skip rollup build if package has "build" configured.
if (pkgJSON.scripts?.build) {
console.log(pkgJSON.name, "has custom build! skipping default build.");
return;
}
// Copy README.md and LICENSE into child package folder.
if (!fs.existsSync(path.join(basePath, "README.md"))) {
fs.copyFileSync(path.resolve(__dirname, "README.md"), path.join(basePath, "README.md"));
fs.copyFileSync(path.resolve(__dirname, "LICENSE"), path.join(basePath, "LICENSE"));
}
// Get all .ts as input files
const entrypoints = glob.sync(path.resolve(basePath, "src", "**", "**.ts")
.replace(/\\/g, '/')); // windows support
const outdir = path.join(basePath, 'build');
// Emit only .d.ts files
const emitTSDeclaration = () => {
console.log("Generating .d.ts files for...", pkgJSON.name);
const program = ts.createProgram(entrypoints, {
rootDir: path.join(basePath, "src"),
declaration: true,
emitDeclarationOnly: true,
resolveJsonModule: true,
skipLibCheck: true,
// module: ts.ModuleKind.CommonJS,
module: ts.ModuleKind.NodeNext,
moduleResolution: ts.ModuleResolutionKind.NodeNext,
target: ts.ScriptTarget.ESNext,
lib: ["lib.esnext.d.ts", "lib.dom.d.ts"],
outDir: outdir,
downlevelIteration: true, // (redis-driver)
esModuleInterop: true,
experimentalDecorators: true,
allowImportingTsExtensions: true,
customConditions: ["@source"],
});
const emitResult = program.emit();
const allDiagnostics = ts
.getPreEmitDiagnostics(program)
.concat(emitResult.diagnostics);
allDiagnostics.forEach(diagnostic => {
if (diagnostic.file) {
const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
} else {
console.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
}
});
}
// CommonJS output
esbuild.build({
entryPoints: entrypoints,
outdir,
format: "cjs",
bundle: true,
sourcemap: "external",
platform: "node",
outExtension: { '.js': '.cjs', },
plugins: [{
name: 'add-cjs',
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => {
if (args.importer) {
if (args.path.startsWith('.')) {
return { path: args.path.replace(/\.[jt]sx?$/, '.cjs'), external: true }
}
return { path: args.path, external: true }
}
})
},
}],
});
// ESM output
esbuild.build({
entryPoints: entrypoints,
outdir,
format: "esm",
bundle: true,
sourcemap: "external",
platform: "node",
outExtension: { '.js': '.mjs', },
plugins: [{
name: 'add-mjs',
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => {
if (args.importer) {
if (args.path.startsWith('.')) {
return { path: args.path.replace(/\.[jt]sx?$/, '.mjs'), external: true }
}
return { path: args.path, external: true }
}
})
},
}],
});
// emit .d.ts files
emitTSDeclaration();
});
}
export default await main();