-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathcopy-template.ts
More file actions
268 lines (232 loc) · 8.39 KB
/
Copy pathcopy-template.ts
File metadata and controls
268 lines (232 loc) · 8.39 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
import { existsSync } from 'node:fs';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { logger } from '@elizaos/core';
import { isQuietMode } from './spinner-utils';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* Copies a directory recursively from source to destination, excluding specified files and directories.
*/
export async function copyDir(src: string, dest: string, exclude: string[] = []) {
// Ensure paths are properly resolved as absolute paths
const resolvedSrc = path.resolve(src);
const resolvedDest = path.resolve(dest);
// Create destination directory if it doesn't exist
await fs.mkdir(resolvedDest, { recursive: true });
// Read source directory
const entries = await fs.readdir(resolvedSrc, { withFileTypes: true });
// Separate files and directories for different processing strategies
const files: typeof entries = [];
const directories: typeof entries = [];
for (const entry of entries) {
// Skip excluded directories/files
if (exclude.includes(entry.name)) {
continue;
}
// Skip node_modules, .git directories and other build artifacts
if (
entry.name === 'node_modules' ||
entry.name === '.git' ||
entry.name === 'cache' ||
entry.name === 'data' ||
entry.name === 'generatedImages' ||
entry.name === '.turbo'
) {
continue;
}
if (entry.isDirectory()) {
directories.push(entry);
} else {
files.push(entry);
}
}
// Process files in parallel (up to 10 concurrent operations)
const MAX_CONCURRENT_FILES = 10;
const filePromises: Promise<void>[] = [];
for (let i = 0; i < files.length; i += MAX_CONCURRENT_FILES) {
const batch = files.slice(i, i + MAX_CONCURRENT_FILES);
const batchPromises = batch.map(async (entry) => {
const srcPath = path.join(resolvedSrc, entry.name);
const destPath = path.join(resolvedDest, entry.name);
await fs.copyFile(srcPath, destPath);
});
filePromises.push(...batchPromises);
}
// Wait for all file copies to complete
await Promise.all(filePromises);
// Process directories sequentially to avoid too much recursion depth
// but still get benefits from parallel file copying within each directory
for (const entry of directories) {
const srcPath = path.join(resolvedSrc, entry.name);
const destPath = path.join(resolvedDest, entry.name);
await copyDir(srcPath, destPath, exclude);
}
}
/**
* Map template types to actual package names
*/
function getPackageName(templateType: string): string {
switch (templateType) {
case 'project-tee-starter':
return 'project-tee-starter';
case 'plugin':
return 'plugin-starter';
case 'plugin-quick':
return 'plugin-quick-starter';
case 'project':
case 'project-starter':
default:
return 'project-starter';
}
}
/**
* Copy a project or plugin template to target directory
*/
export async function copyTemplate(
templateType: 'project' | 'project-starter' | 'project-tee-starter' | 'plugin' | 'plugin-quick',
targetDir: string
) {
const packageName = getPackageName(templateType);
// Try multiple locations to find templates, handling different runtime environments
const possibleTemplatePaths = [
path.resolve(__dirname, '../../templates', packageName),
path.resolve(__dirname, '../templates', packageName),
path.resolve(__dirname, '../../../templates', packageName),
path.resolve(__dirname, 'templates', packageName),
path.resolve(__dirname, '../../../..', packageName),
path.resolve(__dirname, '../../../../packages', packageName),
];
let templateDir: string | null = null;
for (const possiblePath of possibleTemplatePaths) {
if (existsSync(possiblePath)) {
templateDir = possiblePath;
break;
}
}
if (!templateDir) {
throw new Error(
`Template '${packageName}' not found. Searched in:\n${possibleTemplatePaths.join('\n')}`
);
}
logger.debug(
{ src: 'cli', util: 'copy-template', templateType, templateDir, targetDir },
'Copying template'
);
// Copy template files as-is
await copyDir(templateDir, targetDir);
// For plugin templates, replace hardcoded "plugin-starter" strings in source files
if (templateType === 'plugin' || templateType === 'plugin-quick') {
const pluginNameFromPath = path.basename(targetDir);
await replacePluginNameInFiles(targetDir, pluginNameFromPath);
}
// Update package.json with dependency versions only (leave placeholders intact)
const packageJsonPath = path.join(targetDir, 'package.json');
try {
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));
// Remove private field from template package.json since templates should be usable by users
if (packageJson.private) {
delete packageJson.private;
logger.debug(
{ src: 'cli', util: 'copy-template' },
'Removed private field from template package.json'
);
}
// Set @elizaos dependencies to 'latest' for npm installability
// For local development testing, use `elizaos create --local` which links packages after creation
const normalizeElizaDeps = (deps: Record<string, string>, isDevDeps = false): void => {
for (const depName of Object.keys(deps)) {
if (depName.startsWith('@elizaos/') && deps[depName] !== 'latest') {
if (!isQuietMode()) {
logger.info(
{ src: 'cli', util: 'copy-template', depName, version: 'latest' },
isDevDeps ? 'Setting dev dependency version' : 'Setting dependency version'
);
}
deps[depName] = 'latest';
}
}
};
if (packageJson.dependencies) {
normalizeElizaDeps(packageJson.dependencies);
}
if (packageJson.devDependencies) {
normalizeElizaDeps(packageJson.devDependencies, true);
}
// Update the package name to use the actual name provided by the user
const projectNameFromPath = path.basename(targetDir);
if (packageJson.name !== projectNameFromPath) {
packageJson.name = projectNameFromPath;
if (!isQuietMode()) {
logger.info(
{ src: 'cli', util: 'copy-template', packageName: projectNameFromPath },
'Setting package name'
);
}
}
// Write the updated package.json (dependency versions and plugin name changed)
await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));
logger.debug(
{ src: 'cli', util: 'copy-template' },
'Updated package.json with latest dependency versions'
);
} catch (error) {
logger.error(
{
src: 'cli',
util: 'copy-template',
error: error instanceof Error ? error.message : String(error),
},
'Error updating package.json'
);
throw error;
}
logger.debug({ src: 'cli', util: 'copy-template', templateType }, 'Template copied successfully');
}
/**
* Replace hardcoded "plugin-starter" or "plugin-quick-starter" strings in source files with the actual plugin name
*/
async function replacePluginNameInFiles(targetDir: string, pluginName: string): Promise<void> {
const filesToProcess = [
'src/index.ts',
'src/plugin.ts',
'src/__tests__/plugin.test.ts',
'__tests__/plugin.test.ts',
'e2e/starter-plugin.test.ts',
'README.md',
// package.json name is handled by the publish command
];
// Process files in parallel
const promises = filesToProcess.map(async (filePath) => {
const fullPath = path.join(targetDir, filePath);
try {
if (
await fs
.access(fullPath)
.then(() => true)
.catch(() => false)
) {
let content = await fs.readFile(fullPath, 'utf8');
// Replace both plugin-starter and plugin-quick-starter with the actual plugin name
content = content.replace(/plugin-starter/g, pluginName);
content = content.replace(/plugin-quick-starter/g, pluginName);
await fs.writeFile(fullPath, content, 'utf8');
logger.debug(
{ src: 'cli', util: 'copy-template', filePath },
'Updated plugin name in file'
);
}
} catch (error) {
logger.warn(
{
src: 'cli',
util: 'copy-template',
filePath,
error: error instanceof Error ? error.message : String(error),
},
'Could not update file'
);
}
});
await Promise.all(promises);
}