@9of9solutions/replikator 1.0.18 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +74 -74
  2. package/main.js +446 -437
  3. package/package.json +30 -32
package/README.md CHANGED
@@ -1,74 +1,74 @@
1
- # Replikator
2
-
3
- Replikator is a command-line tool designed to share and synchronize code between multiple applications in a monorepo. It enables you to maintain shared code in a single source directory and automatically replicate it to multiple target applications, keeping everything in sync.
4
-
5
- ## Features
6
-
7
- - **Code Sharing**: Maintain shared TypeScript/JavaScript code in one location and replicate it to multiple applications.
8
- - **Real-time Synchronization**: Automatically sync changes to shared code across all target applications.
9
- - **File Watching**: Continuously monitor source files and instantly propagate changes to all targets.
10
- - **Selective Inclusion**: Specify which directories and files should be replicated to each target application.
11
- - **Read-only Protection**: Replicated files are marked as read-only with clear headers indicating their source.
12
- - **Monorepo Support**: Works seamlessly with monorepos and includes special support for Turborepo.
13
-
14
- ## Installation
15
-
16
- To install Replikator, ensure you have Node.js installed, then run:
17
-
18
- ```bash
19
- npm install -g @9of9solutions/replikator
20
- ```
21
-
22
- ## Usage
23
-
24
- Replikator provides the following commands:
25
-
26
- - **rpk init**: Initialize Replikator configuration for your project.
27
- - **rpk run**: Start the file watcher and synchronization process.
28
- - **rpk include**: Specify which directories should be included in the replication.
29
- - **rpk update**: Update the Replikator tool.
30
-
31
- To set up Replikator:
32
-
33
- ```bash
34
- # Initialize configuration
35
- rpk init
36
-
37
- # Select files to include
38
- rpk include
39
-
40
- # Start synchronization
41
- rpk run
42
- ```
43
-
44
- ## Development
45
-
46
- For development purposes, you can use the following script in target applications:
47
-
48
- ```bash
49
- npm run dev
50
- ```
51
-
52
- This will navigate to the parent directory and execute the `rpk run` command.
53
-
54
- ## Dependencies
55
-
56
- Replikator relies on several key dependencies:
57
-
58
- - **commander**: For command-line interfaces.
59
- - **chokidar**: For file watching and event handling.
60
- - **fs-extra**: For enhanced file system operations.
61
- - **inquirer**: For interactive command-line prompts.
62
-
63
- ## Contributing
64
-
65
- Contributions are welcome! Please fork the repository and submit a pull request for any improvements or bug fixes.
66
-
67
- ## License
68
-
69
- This project is licensed under the ISC License.
70
-
71
- ## Author
72
-
73
- Germain LESPINGAL
74
-
1
+ # Replikator
2
+
3
+ Replikator is a command-line tool designed to share and synchronize code between multiple applications in a monorepo. It enables you to maintain shared code in a single source directory and automatically replicate it to multiple target applications, keeping everything in sync.
4
+
5
+ ## Features
6
+
7
+ - **Code Sharing**: Maintain shared TypeScript/JavaScript code in one location and replicate it to multiple applications.
8
+ - **Real-time Synchronization**: Automatically sync changes to shared code across all target applications.
9
+ - **File Watching**: Continuously monitor source files and instantly propagate changes to all targets.
10
+ - **Selective Inclusion**: Specify which directories and files should be replicated to each target application.
11
+ - **Read-only Protection**: Replicated files are marked as read-only with clear headers indicating their source.
12
+ - **Monorepo Support**: Works seamlessly with monorepos and includes special support for Turborepo.
13
+
14
+ ## Installation
15
+
16
+ To install Replikator, ensure you have Node.js installed, then run:
17
+
18
+ ```bash
19
+ npm install -g @9of9solutions/replikator
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ Replikator provides the following commands:
25
+
26
+ - **rpk init**: Initialize Replikator configuration for your project.
27
+ - **rpk run**: Start the file watcher and synchronization process.
28
+ - **rpk include**: Specify which directories should be included in the replication.
29
+ - **rpk update**: Update the Replikator tool.
30
+
31
+ To set up Replikator:
32
+
33
+ ```bash
34
+ # Initialize configuration
35
+ rpk init
36
+
37
+ # Select files to include
38
+ rpk include
39
+
40
+ # Start synchronization
41
+ rpk run
42
+ ```
43
+
44
+ ## Development
45
+
46
+ For development purposes, you can use the following script in target applications:
47
+
48
+ ```bash
49
+ npm run dev
50
+ ```
51
+
52
+ This will navigate to the parent directory and execute the `rpk run` command.
53
+
54
+ ## Dependencies
55
+
56
+ Replikator relies on several key dependencies:
57
+
58
+ - **commander**: For command-line interfaces.
59
+ - **chokidar**: For file watching and event handling.
60
+ - **fs-extra**: For enhanced file system operations.
61
+ - **inquirer**: For interactive command-line prompts.
62
+
63
+ ## Contributing
64
+
65
+ Contributions are welcome! Please fork the repository and submit a pull request for any improvements or bug fixes.
66
+
67
+ ## License
68
+
69
+ This project is licensed under the ISC License.
70
+
71
+ ## Author
72
+
73
+ Germain LESPINGAL
74
+
package/main.js CHANGED
@@ -1,438 +1,447 @@
1
- #!/usr/bin/env node
2
- import path from 'path';
3
- import fs from 'fs-extra';
4
- import chokidar from 'chokidar';
5
- import inquirer from 'inquirer';
6
- import url from 'url';
7
- import { execa } from 'execa';
8
- const projectRoot = process.cwd();
9
- const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
10
- const pkgPath = path.join(__dirname, 'package.json');
11
-
12
- async function getVersion() {
13
- const pkg = await fs.readJson(pkgPath, 'utf8');
14
- return pkg.version;
15
- }
16
-
17
- async function getReplicatedFileHeader(path) {
18
- return `/******************************************************
19
- * RPK / Replikator CLI tool / version ${await getVersion()}
20
- *
21
- * File replicated by Replicator
22
- * DO NOT EDIT
23
- *
24
- * Edit at '${path}'
25
- *
26
- ******************************************************/\n`
27
-
28
- }
29
-
30
- //We save configuration in root package.json
31
- const PACKAGE_JSON_ROOT_PATH = path.resolve(projectRoot, 'package.json');
32
- const SHARED_PATH = 'shared';
33
- /**
34
- * Recursively searches for folders that contain both
35
- * a `src` subfolder and a `package.json` file, starting from `root`.
36
- * Returns an array of objects: { name, src }.
37
- */
38
- async function findApplications(root) {
39
- const applications = [];
40
- async function recurse(dir) {
41
- for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
42
- if (!entry.isDirectory()) continue;
43
- if (entry.name == "node_modules") continue;
44
- const fullPath = path.join(dir, entry.name);
45
- const srcDir = path.join(fullPath, 'src');
46
- const pkgFile = path.join(fullPath, 'package.json');
47
- let hasSrcAndPkg = false;
48
- try {
49
- const [srcStat, pkgStat] = await Promise.all([
50
- fs.stat(srcDir),
51
- fs.stat(pkgFile)
52
- ]);
53
- hasSrcAndPkg = srcStat.isDirectory() && pkgStat.isFile();
54
- } catch {
55
- // either src or package.json doesn't exist, skip
56
- }
57
- if (hasSrcAndPkg) {
58
- // read package.json to get the "name" field
59
- let appName = entry.name;
60
- try {
61
- const pkg = JSON.parse(await fs.readFile(pkgFile, 'utf8'));
62
- if (pkg.name) appName = pkg.name;
63
- } catch {
64
- // if JSON parse fails, stick with folder name
65
- }
66
- applications.push({ name: appName, src: srcDir, appPath: dir, fullPath: fullPath });
67
- }
68
- // dive deeper
69
- await recurse(fullPath);
70
- }
71
- }
72
- await recurse(root);
73
- return applications;
74
- }
75
-
76
-
77
- /**
78
- * Loads the config if it exists, or creates it via prompt.
79
- * The stored config contains paths relative to process.cwd().
80
- * Returns an object { src, targets, include } where src/targets are absolute paths.
81
- */
82
- async function loadConfigOrPrompt(prompt) {
83
- if (await fs.pathExists(PACKAGE_JSON_ROOT_PATH)) {
84
- if (!prompt) {
85
- const raw = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
86
- if (raw.replikator && raw.replikator.src && raw.replikator.targets && raw.replikator.include) {
87
- return {
88
- src: path.resolve(projectRoot, raw.replikator.src),
89
- targets: raw.replikator.targets.map(rel => path.resolve(projectRoot, rel)),
90
- include: raw.replikator.include
91
- };
92
- }
93
- }
94
- } else {
95
- throw new Error(`Unable to find root package.json`);
96
- }
97
-
98
- const applications = await findApplications(projectRoot);
99
- const answers = await inquirer.prompt([
100
- {
101
- name: 'src',
102
- type: 'input',
103
- message: 'Path to the directory to replicate:',
104
- default: 'packages/shared',
105
- validate: i => fs.pathExistsSync(path.resolve(projectRoot, i)) || 'The folder does not exist'
106
- },
107
- {
108
- name: 'targets',
109
- type: 'checkbox',
110
- message: 'Select the targeted applications:',
111
- choices: applications.map(a => { return { name: a.name, value: { src: a.src, appPath: a.appPath, fullPath: a.fullPath } } }),
112
- validate(ans) {
113
- if (ans.length < 1) {
114
- return 'You must choose at least one application.';
115
- }
116
- return true;
117
- }
118
- },
119
- {
120
- name: 'turbo',
121
- type: 'list',
122
- message: 'Would you like to configure for Turbo?',
123
- choices: [{ name: 'Yes', value: true }, { name: 'No', value: false }],
124
- default: true
125
- }
126
- ]);
127
-
128
- const absSrc = path.resolve(projectRoot, answers.src);
129
- const absTargets = await Promise.all(answers.targets.map(async t => path.join(t.src, SHARED_PATH)));
130
- const relSrc = path.relative(projectRoot, absSrc);
131
- const relTargets = absTargets.map(abs => path.relative(projectRoot, abs));
132
-
133
- if (answers.turbo) {
134
- const appPaths = new Set(answers.targets.map(t => t.appPath))
135
- for (const appPath of appPaths) {
136
- const replikatorPath = path.join(appPath, 'replikator')
137
- const replikatorPackagePath = path.join(replikatorPath, 'package.json')
138
- await fs.ensureDir(replikatorPath);
139
- if (await fs.pathExists(replikatorPackagePath)) {
140
- const replikatorPackageJson = await fs.readJson(replikatorPackagePath);
141
- const config = { ...replikatorPackageJson, scripts: { dev: `cd ${path.relative(replikatorPath, projectRoot)} && rpk run` } };
142
- fs.writeJson(replikatorPackagePath, config, { spaces: 2 });
143
- } else {
144
- const config = { name: 'replikator', scripts: { dev: `cd ${path.relative(replikatorPath, projectRoot)} && rpk run` } };
145
- fs.writeJson(replikatorPackagePath, config, { spaces: 2 });
146
- }
147
- }
148
- }
149
-
150
- for (const app of answers.targets) {
151
- const fullPath = app.fullPath
152
- const tsconfigPath = path.join(fullPath, 'tsconfig.json')
153
- if (await fs.pathExists(tsconfigPath)) {
154
- const tsconfigJson = await fs.readJson(tsconfigPath);
155
- const config = { ...tsconfigJson, compilerOptions: { ...tsconfigJson?.compilerOptions, paths: { ...tsconfigJson?.compilerOptions?.paths, "shared/*": [path.join(path.relative(fullPath, absSrc), '*')] } } };
156
- fs.writeJson(tsconfigPath, config, { spaces: 2 });
157
- } else {
158
- const config = { compilerOptions: { paths: { "shared/*": [path.join(path.relative(fullPath, absSrc), '*')] } } };
159
- fs.writeJson(tsconfigPath, config, { spaces: 2 });
160
- }
161
- const aliasLine = `'shared': path.resolve(__dirname, 'src/shared'),`;
162
- const viteConfigPath = path.join(fullPath, 'vite.config.ts')
163
- if (await fs.pathExists(viteConfigPath)) {
164
- let code = await fs.readFile(viteConfigPath, 'utf-8');
165
- if (!code.includes(aliasLine)) {
166
- const aliasBlockRe = /(resolve\s*:\s*{[^}]*alias\s*:\s*{)([^}]*)(\})/m;
167
- if (aliasBlockRe.test(code)) {
168
- code = code.replace(aliasBlockRe, (_, start, inner, end) =>
169
- `${start}${inner.trim()}\n ${aliasLine}\n ${end}`
170
- );
171
-
172
- } else if (/resolve\s*:\s*{/.test(code)) {
173
- code = code.replace(
174
- /resolve\s*:\s*{([^}]*)}/m,
175
- (_, inner) => `resolve: {\n alias: {\n ${aliasLine}\n },\n ${inner.trim()}\n }`
176
- );
177
- } else {
178
- code = code.replace(
179
- /defineConfig\(\s*{([\s\S]*?)}\s*\)/m,
180
- (_, inner) => `defineConfig({\n resolve: {\n alias: {\n ${aliasLine}\n }\n },\n${inner.trim()}\n})`
181
- );
182
- }
183
- await fs.writeFile(viteConfigPath, code, 'utf-8');
184
- }
185
- } else {
186
- await fs.ensureDir(path.dirname(viteConfigPath))
187
- const tpl = `import { defineConfig } from 'vite';
188
- import path from 'path';
189
-
190
- export default defineConfig({
191
- resolve: {
192
- alias: {
193
- ${aliasLine}
194
- }
195
- }
196
- });
197
- `;
198
- await fs.writeFile(viteConfigPath, tpl, 'utf-8')
199
- }
200
- }
201
-
202
-
203
-
204
-
205
- const package_json = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
206
- const config = { ...package_json, replikator: { src: relSrc, targets: relTargets, include: {} } };
207
- await fs.writeJson(PACKAGE_JSON_ROOT_PATH, config, { spaces: 2 });
208
- console.log(`Configuration saved in ${path.relative(projectRoot, PACKAGE_JSON_ROOT_PATH)}`);
209
-
210
- return { src: absSrc, targets: absTargets, include: [] };
211
- }
212
-
213
- /**
214
- * Replikator run command
215
- * @param {*} prompt - Should init config or no
216
- */
217
- async function run(prompt) {
218
- const { src, targets, include } = await loadConfigOrPrompt(prompt);
219
- await Promise.all(
220
- targets.map(async dest => {
221
- await fs.remove(dest)
222
- await fs.ensureDir(dest);
223
- const relDest = path.relative(projectRoot, dest);
224
- const patterns = include?.[relDest] || [];
225
-
226
- const filterFn = srcFile => {
227
- const rel = path.relative(src, srcFile);
228
- console.log(rel)
229
- return patterns.filter(p => rel.startsWith(p)).length > 0;
230
- };
231
-
232
- console.log(dest)
233
- await fs.copy(src, dest, { overwrite: true, filter: filterFn });
234
-
235
- if ((await fs.lstat(src)).isFile() && !src.endsWith('.svg') && !src.endsWith('.png') && !src.endsWith('.jpg') && !src.endsWith('.jpeg') && !src.endsWith('.gif')) {
236
- const data = await fs.readFile(src);
237
- const fd = await fs.open(dest, 'w+');
238
- const header = Buffer.from(await getReplicatedFileHeader(src));
239
- await fs.write(fd, header, 0, header.length, 0);
240
- await fs.write(fd, data, 0, data.length, header.length);
241
- await fs.chmod(dest, 0o444);
242
- }
243
- })
244
- );
245
-
246
- console.log('Initial copy completed.');
247
-
248
- const watcher = chokidar.watch(src, { persistent: true });
249
- watcher
250
- .on('add', p => syncFile('add', p, src, targets, include))
251
- .on('change', p => syncFile('change', p, src, targets, include))
252
- .on('unlink', p => syncFile('unlink', p, src, targets, include))
253
- .on('error', e => console.error('Watcher error:', e));
254
- }
255
-
256
- /**
257
- * Show infos of replikator
258
- */
259
- async function showInfo() {
260
- console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
261
- console.log("");
262
- console.log("Usage: rpk [command]");
263
- console.log("");
264
- console.log("Commands:");
265
- console.log(" init Command used to init replikator configuration.");
266
- console.log(" run Command used to run replikator.");
267
- console.log(" update Command used to update replikator.");
268
- console.log(" include Command used to include files for selected apps.");
269
- process.exit(0);
270
- }
271
-
272
- /**
273
- * Starts the initial copy and then sets up the watcher.
274
- */
275
- async function main() {
276
- if (process.argv.length > 2) {
277
- switch (process.argv[2]) {
278
- case "init":
279
- await run(true);
280
- break;
281
- case "run":
282
- await run(false);
283
- break;
284
- case "update":
285
- await updateRpk();
286
- break;
287
- case "include":
288
- await includeRpk();
289
- break;
290
- default:
291
- await showInfo();
292
- break
293
- }
294
- } else {
295
- await showInfo();
296
- }
297
-
298
-
299
- }
300
-
301
- /**
302
- * Update the CLI to the last available version.
303
- */
304
- async function updateRpk() {
305
- const ua = process.env.npm_config_user_agent || '';
306
- let cmd, args;
307
-
308
- if (ua.startsWith('pnpm')) {
309
- cmd = 'pnpm';
310
- args = ['add', '-g', '@9of9solutions/replikator@latest', '-w'];
311
- } else if (ua.startsWith('yarn')) {
312
- cmd = 'yarn';
313
- args = ['global', 'add', '@9of9solutions/replikator@latest'];
314
- } else {
315
- cmd = 'npm';
316
- args = ['install', '-g', '@9of9solutions/replikator@latest'];
317
- }
318
-
319
- try {
320
- await execa(cmd, args, { stdio: 'inherit' });
321
- const newVersion = await getVersion();
322
- console.log(green(`RPK CLI updated to version ${newVersion}`));
323
- } catch (err) {
324
- console.log(red(`Failed to update RPK CLI: ${err.message}`));
325
- process.exit(1);
326
- }
327
- }
328
-
329
- const green = txt => `\x1b[32m${txt}\x1b[0m`;
330
- const red = txt => `\x1b[31m${txt}\x1b[0m`;
331
-
332
- /**
333
- * Syncs a file that was added/modified/deleted to all targets.
334
- */
335
- async function syncFile(event, filePath, srcDir, targets, include) {
336
- const rel = path.relative(srcDir, filePath);
337
- await Promise.all(targets.map(async destRoot => {
338
- const destPath = path.join(destRoot, rel);
339
- if (event === 'unlink') {
340
- await fs.remove(destPath);
341
- } else {
342
- const relDest = path.relative(projectRoot, destRoot);
343
- const patterns = include?.[relDest] || [];
344
- if (patterns.filter(p => (rel).startsWith(p)).length > 0) {
345
- await fs.ensureDir(path.dirname(destPath));
346
- await fs.copy(filePath, destPath, { overwrite: true });
347
- if ((await fs.lstat(filePath)).isFile()) {
348
- const data = await fs.readFile(filePath);
349
- const fd = await fs.open(destPath, 'w+');
350
- const buffer = Buffer.from(await getReplicatedFileHeader(filePath));
351
- await fs.write(fd, buffer, 0, buffer.length, 0);
352
- await fs.write(fd, data, 0, data.length, buffer.length);
353
- await fs.chmod(destPath, 0o444)
354
- }
355
- }
356
-
357
- }
358
- }));
359
- }
360
-
361
- /**
362
- * Setup included files or directories for apps
363
- */
364
- async function includeRpk() {
365
- const rawPkg = await fs.readJson(PACKAGE_JSON_ROOT_PATH, 'utf8');
366
- const cfg = rawPkg.replikator;
367
- if (!cfg || !cfg.src || !Array.isArray(cfg.targets)) {
368
- console.log(red('No Replikator configuration found. Please run `rpk init` first.'));
369
- process.exit(1);
370
- }
371
-
372
- const absSrc = path.resolve(projectRoot, cfg.src);
373
- const absTargets = cfg.targets.map(rel => path.resolve(projectRoot, rel));
374
-
375
- const apps = await findApplications(projectRoot);
376
- const choicesApps = absTargets.map(absT => {
377
- const match = apps.find(a => path.join(a.src, SHARED_PATH) === absT);
378
- return {
379
- name: match ? match.name : path.relative(projectRoot, absT),
380
- value: absT
381
- };
382
- });
383
-
384
- const { selectedApps } = await inquirer.prompt([{
385
- type: 'checkbox',
386
- name: 'selectedApps',
387
- message: 'Select applications on which to apply include:',
388
- choices: choicesApps,
389
- validate(ans) {
390
- return ans.length > 0 ? true : 'You must choose at least one application.';
391
- }
392
- }]);
393
-
394
- async function walk(dir, base = '') {
395
- const entries = [];
396
- const children = await fs.readdir(dir, { withFileTypes: true });
397
-
398
- const hasFile = children.some(c => c.isFile() && /\.(ts|tsx)$/.test(c.name));
399
- if (hasFile && base !== '') {
400
- entries.push(base);
401
- }
402
-
403
- for (const ent of children) {
404
- if (ent.isDirectory() && !ent.name.includes('node_modules')) {
405
- const rel = path.join(base, ent.name);
406
- const full = path.join(dir, ent.name);
407
- entries.push(...await walk(full, rel));
408
- }
409
- }
410
-
411
- return entries;
412
- }
413
-
414
- const allEntries = await walk(absSrc);
415
-
416
- const { toinclude } = await inquirer.prompt([{
417
- type: 'checkbox',
418
- name: 'toinclude',
419
- message: 'Select directories (relative to src) to include:',
420
- choices: allEntries.map(rel => ({ name: rel, value: rel })),
421
- validate(ans) {
422
- return ans.length > 0 ? true : 'You must choose at least one entry to include.';
423
- }
424
- }]);
425
-
426
- rawPkg.replikator.include = rawPkg.replikator.include || {};
427
- for (const absT of selectedApps) {
428
- const relT = path.relative(projectRoot, absT);
429
- rawPkg.replikator.include[relT] = toinclude;
430
- }
431
- await fs.writeJson(PACKAGE_JSON_ROOT_PATH, rawPkg, { spaces: 2 });
432
- console.log(green(`Inclusion config updated for ${selectedApps.length} app(s).`));
433
- }
434
-
435
- main().catch(err => {
436
- console.error('Fatal error:', err);
437
- process.exit(1);
1
+ #!/usr/bin/env node
2
+ import path from 'path';
3
+ import fs from 'fs-extra';
4
+ import chokidar from 'chokidar';
5
+ import inquirer from 'inquirer';
6
+ import url from 'url';
7
+ import { execa } from 'execa';
8
+ const projectRoot = process.cwd();
9
+ const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
10
+ const pkgPath = path.join(__dirname, 'package.json');
11
+
12
+ async function getVersion() {
13
+ const pkg = await fs.readJson(pkgPath, 'utf8');
14
+ return pkg.version;
15
+ }
16
+
17
+ async function getReplicatedFileHeader(path) {
18
+ return `/******************************************************
19
+ * RPK / Replikator CLI tool / version ${await getVersion()}
20
+ *
21
+ * File replicated by Replicator
22
+ * DO NOT EDIT
23
+ *
24
+ * Edit at '${path}'
25
+ *
26
+ ******************************************************/\n`
27
+
28
+ }
29
+
30
+ //We save configuration in root package.json
31
+ const PACKAGE_JSON_ROOT_PATH = path.resolve(projectRoot, 'package.json');
32
+ const SHARED_PATH = 'shared';
33
+
34
+ /**
35
+ * The configuration and the include patterns use '/' on every platform: relative paths
36
+ * are stored and compared in that form, so that the backslashes of Windows match too.
37
+ */
38
+ const toPosix = p => p.split(path.sep).join('/');
39
+
40
+ /**
41
+ * Recursively searches for folders that contain both
42
+ * a `src` subfolder and a `package.json` file, starting from `root`.
43
+ * Returns an array of objects: { name, src }.
44
+ */
45
+ async function findApplications(root) {
46
+ const applications = [];
47
+ async function recurse(dir) {
48
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
49
+ if (!entry.isDirectory()) continue;
50
+ if (entry.name == "node_modules") continue;
51
+ const fullPath = path.join(dir, entry.name);
52
+ const srcDir = path.join(fullPath, 'src');
53
+ const pkgFile = path.join(fullPath, 'package.json');
54
+ let hasSrcAndPkg = false;
55
+ try {
56
+ const [srcStat, pkgStat] = await Promise.all([
57
+ fs.stat(srcDir),
58
+ fs.stat(pkgFile)
59
+ ]);
60
+ hasSrcAndPkg = srcStat.isDirectory() && pkgStat.isFile();
61
+ } catch {
62
+ // either src or package.json doesn't exist, skip
63
+ }
64
+ if (hasSrcAndPkg) {
65
+ // read package.json to get the "name" field
66
+ let appName = entry.name;
67
+ try {
68
+ const pkg = JSON.parse(await fs.readFile(pkgFile, 'utf8'));
69
+ if (pkg.name) appName = pkg.name;
70
+ } catch {
71
+ // if JSON parse fails, stick with folder name
72
+ }
73
+ applications.push({ name: appName, src: srcDir, appPath: dir, fullPath: fullPath });
74
+ }
75
+ // dive deeper
76
+ await recurse(fullPath);
77
+ }
78
+ }
79
+ await recurse(root);
80
+ return applications;
81
+ }
82
+
83
+
84
+ /**
85
+ * Loads the config if it exists, or creates it via prompt.
86
+ * The stored config contains paths relative to process.cwd().
87
+ * Returns an object { src, targets, include } where src/targets are absolute paths.
88
+ */
89
+ async function loadConfigOrPrompt(prompt) {
90
+ if (await fs.pathExists(PACKAGE_JSON_ROOT_PATH)) {
91
+ if (!prompt) {
92
+ const raw = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
93
+ if (raw.replikator && raw.replikator.src && raw.replikator.targets && raw.replikator.include) {
94
+ return {
95
+ src: path.resolve(projectRoot, raw.replikator.src),
96
+ targets: raw.replikator.targets.map(rel => path.resolve(projectRoot, rel)),
97
+ include: Object.fromEntries(Object.entries(raw.replikator.include)
98
+ .map(([target, patterns]) => [toPosix(path.normalize(target)), patterns.map(p => toPosix(path.normalize(p)))]))
99
+ };
100
+ }
101
+ }
102
+ } else {
103
+ throw new Error(`Unable to find root package.json`);
104
+ }
105
+
106
+ const applications = await findApplications(projectRoot);
107
+ const answers = await inquirer.prompt([
108
+ {
109
+ name: 'src',
110
+ type: 'input',
111
+ message: 'Path to the directory to replicate:',
112
+ default: 'packages/shared',
113
+ validate: i => fs.pathExistsSync(path.resolve(projectRoot, i)) || 'The folder does not exist'
114
+ },
115
+ {
116
+ name: 'targets',
117
+ type: 'checkbox',
118
+ message: 'Select the targeted applications:',
119
+ choices: applications.map(a => { return { name: a.name, value: { src: a.src, appPath: a.appPath, fullPath: a.fullPath } } }),
120
+ validate(ans) {
121
+ if (ans.length < 1) {
122
+ return 'You must choose at least one application.';
123
+ }
124
+ return true;
125
+ }
126
+ },
127
+ {
128
+ name: 'turbo',
129
+ type: 'list',
130
+ message: 'Would you like to configure for Turbo?',
131
+ choices: [{ name: 'Yes', value: true }, { name: 'No', value: false }],
132
+ default: true
133
+ }
134
+ ]);
135
+
136
+ const absSrc = path.resolve(projectRoot, answers.src);
137
+ const absTargets = await Promise.all(answers.targets.map(async t => path.join(t.src, SHARED_PATH)));
138
+ const relSrc = toPosix(path.relative(projectRoot, absSrc));
139
+ const relTargets = absTargets.map(abs => toPosix(path.relative(projectRoot, abs)));
140
+
141
+ if (answers.turbo) {
142
+ const appPaths = new Set(answers.targets.map(t => t.appPath))
143
+ for (const appPath of appPaths) {
144
+ const replikatorPath = path.join(appPath, 'replikator')
145
+ const replikatorPackagePath = path.join(replikatorPath, 'package.json')
146
+ await fs.ensureDir(replikatorPath);
147
+ if (await fs.pathExists(replikatorPackagePath)) {
148
+ const replikatorPackageJson = await fs.readJson(replikatorPackagePath);
149
+ const config = { ...replikatorPackageJson, scripts: { dev: `cd ${path.relative(replikatorPath, projectRoot)} && rpk run` } };
150
+ fs.writeJson(replikatorPackagePath, config, { spaces: 2 });
151
+ } else {
152
+ const config = { name: 'replikator', scripts: { dev: `cd ${path.relative(replikatorPath, projectRoot)} && rpk run` } };
153
+ fs.writeJson(replikatorPackagePath, config, { spaces: 2 });
154
+ }
155
+ }
156
+ }
157
+
158
+ for (const app of answers.targets) {
159
+ const fullPath = app.fullPath
160
+ const tsconfigPath = path.join(fullPath, 'tsconfig.json')
161
+ if (await fs.pathExists(tsconfigPath)) {
162
+ const tsconfigJson = await fs.readJson(tsconfigPath);
163
+ const config = { ...tsconfigJson, compilerOptions: { ...tsconfigJson?.compilerOptions, paths: { ...tsconfigJson?.compilerOptions?.paths, "shared/*": [path.join(path.relative(fullPath, absSrc), '*')] } } };
164
+ fs.writeJson(tsconfigPath, config, { spaces: 2 });
165
+ } else {
166
+ const config = { compilerOptions: { paths: { "shared/*": [path.join(path.relative(fullPath, absSrc), '*')] } } };
167
+ fs.writeJson(tsconfigPath, config, { spaces: 2 });
168
+ }
169
+ const aliasLine = `'shared': path.resolve(__dirname, 'src/shared'),`;
170
+ const viteConfigPath = path.join(fullPath, 'vite.config.ts')
171
+ if (await fs.pathExists(viteConfigPath)) {
172
+ let code = await fs.readFile(viteConfigPath, 'utf-8');
173
+ if (!code.includes(aliasLine)) {
174
+ const aliasBlockRe = /(resolve\s*:\s*{[^}]*alias\s*:\s*{)([^}]*)(\})/m;
175
+ if (aliasBlockRe.test(code)) {
176
+ code = code.replace(aliasBlockRe, (_, start, inner, end) =>
177
+ `${start}${inner.trim()}\n ${aliasLine}\n ${end}`
178
+ );
179
+
180
+ } else if (/resolve\s*:\s*{/.test(code)) {
181
+ code = code.replace(
182
+ /resolve\s*:\s*{([^}]*)}/m,
183
+ (_, inner) => `resolve: {\n alias: {\n ${aliasLine}\n },\n ${inner.trim()}\n }`
184
+ );
185
+ } else {
186
+ code = code.replace(
187
+ /defineConfig\(\s*{([\s\S]*?)}\s*\)/m,
188
+ (_, inner) => `defineConfig({\n resolve: {\n alias: {\n ${aliasLine}\n }\n },\n${inner.trim()}\n})`
189
+ );
190
+ }
191
+ await fs.writeFile(viteConfigPath, code, 'utf-8');
192
+ }
193
+ } else {
194
+ await fs.ensureDir(path.dirname(viteConfigPath))
195
+ const tpl = `import { defineConfig } from 'vite';
196
+ import path from 'path';
197
+
198
+ export default defineConfig({
199
+ resolve: {
200
+ alias: {
201
+ ${aliasLine}
202
+ }
203
+ }
204
+ });
205
+ `;
206
+ await fs.writeFile(viteConfigPath, tpl, 'utf-8')
207
+ }
208
+ }
209
+
210
+
211
+
212
+
213
+ const package_json = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
214
+ const config = { ...package_json, replikator: { src: relSrc, targets: relTargets, include: {} } };
215
+ await fs.writeJson(PACKAGE_JSON_ROOT_PATH, config, { spaces: 2 });
216
+ console.log(`Configuration saved in ${path.relative(projectRoot, PACKAGE_JSON_ROOT_PATH)}`);
217
+
218
+ return { src: absSrc, targets: absTargets, include: [] };
219
+ }
220
+
221
+ /**
222
+ * Replikator run command
223
+ * @param {*} prompt - Should init config or no
224
+ */
225
+ async function run(prompt) {
226
+ const { src, targets, include } = await loadConfigOrPrompt(prompt);
227
+ await Promise.all(
228
+ targets.map(async dest => {
229
+ await fs.remove(dest)
230
+ await fs.ensureDir(dest);
231
+ const relDest = toPosix(path.relative(projectRoot, dest));
232
+ const patterns = include?.[relDest] || [];
233
+
234
+ const filterFn = srcFile => {
235
+ const rel = toPosix(path.relative(src, srcFile));
236
+ console.log(rel)
237
+ return patterns.filter(p => rel.startsWith(p)).length > 0;
238
+ };
239
+
240
+ console.log(dest)
241
+ await fs.copy(src, dest, { overwrite: true, filter: filterFn });
242
+
243
+ if ((await fs.lstat(src)).isFile() && !src.endsWith('.svg') && !src.endsWith('.png') && !src.endsWith('.jpg') && !src.endsWith('.jpeg') && !src.endsWith('.gif')) {
244
+ const data = await fs.readFile(src);
245
+ const fd = await fs.open(dest, 'w+');
246
+ const header = Buffer.from(await getReplicatedFileHeader(src));
247
+ await fs.write(fd, header, 0, header.length, 0);
248
+ await fs.write(fd, data, 0, data.length, header.length);
249
+ await fs.chmod(dest, 0o444);
250
+ }
251
+ })
252
+ );
253
+
254
+ console.log('Initial copy completed.');
255
+
256
+ const watcher = chokidar.watch(src, { persistent: true });
257
+ watcher
258
+ .on('add', p => syncFile('add', p, src, targets, include))
259
+ .on('change', p => syncFile('change', p, src, targets, include))
260
+ .on('unlink', p => syncFile('unlink', p, src, targets, include))
261
+ .on('error', e => console.error('Watcher error:', e));
262
+ }
263
+
264
+ /**
265
+ * Show infos of replikator
266
+ */
267
+ async function showInfo() {
268
+ console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
269
+ console.log("");
270
+ console.log("Usage: rpk [command]");
271
+ console.log("");
272
+ console.log("Commands:");
273
+ console.log(" init Command used to init replikator configuration.");
274
+ console.log(" run Command used to run replikator.");
275
+ console.log(" update Command used to update replikator.");
276
+ console.log(" include Command used to include files for selected apps.");
277
+ process.exit(0);
278
+ }
279
+
280
+ /**
281
+ * Starts the initial copy and then sets up the watcher.
282
+ */
283
+ async function main() {
284
+ if (process.argv.length > 2) {
285
+ switch (process.argv[2]) {
286
+ case "init":
287
+ await run(true);
288
+ break;
289
+ case "run":
290
+ await run(false);
291
+ break;
292
+ case "update":
293
+ await updateRpk();
294
+ break;
295
+ case "include":
296
+ await includeRpk();
297
+ break;
298
+ default:
299
+ await showInfo();
300
+ break
301
+ }
302
+ } else {
303
+ await showInfo();
304
+ }
305
+
306
+
307
+ }
308
+
309
+ /**
310
+ * Update the CLI to the last available version.
311
+ */
312
+ async function updateRpk() {
313
+ const ua = process.env.npm_config_user_agent || '';
314
+ let cmd, args;
315
+
316
+ if (ua.startsWith('pnpm')) {
317
+ cmd = 'pnpm';
318
+ args = ['add', '-g', '@9of9solutions/replikator@latest', '-w'];
319
+ } else if (ua.startsWith('yarn')) {
320
+ cmd = 'yarn';
321
+ args = ['global', 'add', '@9of9solutions/replikator@latest'];
322
+ } else {
323
+ cmd = 'npm';
324
+ args = ['install', '-g', '@9of9solutions/replikator@latest'];
325
+ }
326
+
327
+ try {
328
+ await execa(cmd, args, { stdio: 'inherit' });
329
+ const newVersion = await getVersion();
330
+ console.log(green(`RPK CLI updated to version ${newVersion}`));
331
+ } catch (err) {
332
+ console.log(red(`Failed to update RPK CLI: ${err.message}`));
333
+ process.exit(1);
334
+ }
335
+ }
336
+
337
+ const green = txt => `\x1b[32m${txt}\x1b[0m`;
338
+ const red = txt => `\x1b[31m${txt}\x1b[0m`;
339
+
340
+ /**
341
+ * Syncs a file that was added/modified/deleted to all targets.
342
+ */
343
+ async function syncFile(event, filePath, srcDir, targets, include) {
344
+ const rel = path.relative(srcDir, filePath);
345
+ await Promise.all(targets.map(async destRoot => {
346
+ const destPath = path.join(destRoot, rel);
347
+ if (event === 'unlink') {
348
+ await fs.remove(destPath);
349
+ } else {
350
+ const relDest = toPosix(path.relative(projectRoot, destRoot));
351
+ const patterns = include?.[relDest] || [];
352
+ if (patterns.filter(p => toPosix(rel).startsWith(p)).length > 0) {
353
+ await fs.ensureDir(path.dirname(destPath));
354
+ await fs.copy(filePath, destPath, { overwrite: true });
355
+ if ((await fs.lstat(filePath)).isFile() && !filePath.endsWith('.svg') && !filePath.endsWith('.png') && !filePath.endsWith('.jpg') && !filePath.endsWith('.jpeg') && !filePath.endsWith('.gif')) {
356
+ const data = await fs.readFile(filePath);
357
+ const fd = await fs.open(destPath, 'w+');
358
+ const buffer = Buffer.from(await getReplicatedFileHeader(filePath));
359
+ await fs.write(fd, buffer, 0, buffer.length, 0);
360
+ await fs.write(fd, data, 0, data.length, buffer.length);
361
+ await fs.close(fd);
362
+ await fs.chmod(destPath, 0o444)
363
+ }
364
+ }
365
+
366
+ }
367
+ }));
368
+ }
369
+
370
+ /**
371
+ * Setup included files or directories for apps
372
+ */
373
+ async function includeRpk() {
374
+ const rawPkg = await fs.readJson(PACKAGE_JSON_ROOT_PATH, 'utf8');
375
+ const cfg = rawPkg.replikator;
376
+ if (!cfg || !cfg.src || !Array.isArray(cfg.targets)) {
377
+ console.log(red('No Replikator configuration found. Please run `rpk init` first.'));
378
+ process.exit(1);
379
+ }
380
+
381
+ const absSrc = path.resolve(projectRoot, cfg.src);
382
+ const absTargets = cfg.targets.map(rel => path.resolve(projectRoot, rel));
383
+
384
+ const apps = await findApplications(projectRoot);
385
+ const choicesApps = absTargets.map(absT => {
386
+ const match = apps.find(a => path.join(a.src, SHARED_PATH) === absT);
387
+ return {
388
+ name: match ? match.name : path.relative(projectRoot, absT),
389
+ value: absT
390
+ };
391
+ });
392
+
393
+ const { selectedApps } = await inquirer.prompt([{
394
+ type: 'checkbox',
395
+ name: 'selectedApps',
396
+ message: 'Select applications on which to apply include:',
397
+ choices: choicesApps,
398
+ validate(ans) {
399
+ return ans.length > 0 ? true : 'You must choose at least one application.';
400
+ }
401
+ }]);
402
+
403
+ async function walk(dir, base = '') {
404
+ const entries = [];
405
+ const children = await fs.readdir(dir, { withFileTypes: true });
406
+
407
+ const hasFile = children.some(c => c.isFile() && /\.(ts|tsx)$/.test(c.name));
408
+ if (hasFile && base !== '') {
409
+ entries.push(base);
410
+ }
411
+
412
+ for (const ent of children) {
413
+ if (ent.isDirectory() && !ent.name.includes('node_modules')) {
414
+ const rel = base === '' ? ent.name : `${base}/${ent.name}`;
415
+ const full = path.join(dir, ent.name);
416
+ entries.push(...await walk(full, rel));
417
+ }
418
+ }
419
+
420
+ return entries;
421
+ }
422
+
423
+ const allEntries = await walk(absSrc);
424
+
425
+ const { toinclude } = await inquirer.prompt([{
426
+ type: 'checkbox',
427
+ name: 'toinclude',
428
+ message: 'Select directories (relative to src) to include:',
429
+ choices: allEntries.map(rel => ({ name: rel, value: rel })),
430
+ validate(ans) {
431
+ return ans.length > 0 ? true : 'You must choose at least one entry to include.';
432
+ }
433
+ }]);
434
+
435
+ rawPkg.replikator.include = rawPkg.replikator.include || {};
436
+ for (const absT of selectedApps) {
437
+ const relT = toPosix(path.relative(projectRoot, absT));
438
+ rawPkg.replikator.include[relT] = toinclude;
439
+ }
440
+ await fs.writeJson(PACKAGE_JSON_ROOT_PATH, rawPkg, { spaces: 2 });
441
+ console.log(green(`Inclusion config updated for ${selectedApps.length} app(s).`));
442
+ }
443
+
444
+ main().catch(err => {
445
+ console.error('Fatal error:', err);
446
+ process.exit(1);
438
447
  });
package/package.json CHANGED
@@ -1,32 +1,30 @@
1
- {
2
- "name": "@9of9solutions/replikator",
3
- "version": "1.0.18",
4
- "type": "module",
5
- "main": "main.js",
6
- "bin": {
7
- "replikator": "main.js",
8
- "rpk": "main.js"
9
- },
10
- "scripts": {
11
- "replikator": "node main.js",
12
- "rpk": "node main.js"
13
- },
14
- "files": [
15
- "main.js"
16
- ],
17
- "keywords": [],
18
- "author": "Germain LESPINGAL",
19
- "license": "ISC",
20
- "description": "",
21
- "devDependencies": {
22
- "chokidar": "^4.0.3",
23
- "fs-extra": "^11.3.0"
24
- },
25
- "dependencies": {
26
- "commander": "^13.1.0",
27
- "degit": "^2.8.4",
28
- "execa": "^9.5.2",
29
- "inquirer": "^8.2.6",
30
- "winston": "^3.17.0"
31
- }
32
- }
1
+ {
2
+ "name": "@9of9solutions/replikator",
3
+ "version": "1.0.20",
4
+ "type": "module",
5
+ "main": "main.js",
6
+ "bin": {
7
+ "replikator": "main.js",
8
+ "rpk": "main.js"
9
+ },
10
+ "scripts": {
11
+ "replikator": "node main.js",
12
+ "rpk": "node main.js"
13
+ },
14
+ "files": [
15
+ "main.js"
16
+ ],
17
+ "keywords": [],
18
+ "author": "Germain LESPINGAL",
19
+ "license": "ISC",
20
+ "description": "",
21
+ "dependencies": {
22
+ "chokidar": "^4.0.3",
23
+ "commander": "^13.1.0",
24
+ "degit": "^2.8.4",
25
+ "execa": "^9.5.2",
26
+ "fs-extra": "^11.3.0",
27
+ "inquirer": "^8.2.6",
28
+ "winston": "^3.17.0"
29
+ }
30
+ }