fabrique 0.0.1 → 0.2.0

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 (45) hide show
  1. package/.editorconfig +7 -0
  2. package/.nvmrc +1 -0
  3. package/.prettierrc +7 -0
  4. package/LICENSE +21 -0
  5. package/README.md +218 -0
  6. package/package.json +24 -9
  7. package/src/actions/create.js +123 -0
  8. package/src/actions/refactor.js +166 -0
  9. package/src/actions/upgrade.js +157 -0
  10. package/src/actions/verdaccio.js +20 -0
  11. package/src/helpers/cmd.js +45 -0
  12. package/src/helpers/fs/exists.js +10 -0
  13. package/src/helpers/fs/explore.js +18 -0
  14. package/src/helpers/fs/read-json-file.js +11 -0
  15. package/src/helpers/fs/write-file-safe.js +13 -0
  16. package/src/helpers/fs/write-json-file.js +12 -0
  17. package/src/helpers/handle-error.js +14 -0
  18. package/src/helpers/list-available-templates.js +11 -0
  19. package/src/helpers/log/log-error.js +7 -0
  20. package/src/helpers/log/log.js +28 -0
  21. package/src/helpers/paths.constant.js +15 -0
  22. package/src/helpers/replace-pattern.js +16 -0
  23. package/src/index.js +43 -0
  24. package/templates/lib/.editorconfig +7 -0
  25. package/templates/lib/.nvmrc +1 -0
  26. package/templates/lib/.prettierrc +7 -0
  27. package/templates/lib/.yarnrc.yml +6 -0
  28. package/templates/lib/CONTRIBUTING.md +40 -0
  29. package/templates/lib/LICENSE +21 -0
  30. package/templates/lib/README.md +15 -0
  31. package/templates/lib/fabrique/actions/build.js +355 -0
  32. package/templates/lib/fabrique/helpers/cmd.js +44 -0
  33. package/templates/lib/fabrique/test/tools.ts +18 -0
  34. package/templates/lib/package.json +30 -0
  35. package/templates/lib/src/add.test.ts +8 -0
  36. package/templates/lib/src/add.ts +3 -0
  37. package/templates/lib/src/style.private.scss +5 -0
  38. package/templates/lib/src/style.scss +5 -0
  39. package/templates/lib/src/sub.private.ts +3 -0
  40. package/templates/lib/src/variables.scss +1 -0
  41. package/templates/lib/tsconfig.build.json +17 -0
  42. package/templates/lib/tsconfig.json +37 -0
  43. package/templates/lib/vitest.config.ts +7 -0
  44. package/tsconfig.json +43 -0
  45. package/index.js +0 -13
@@ -0,0 +1,355 @@
1
+ import { cp, glob, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { cmd } from '../helpers/cmd.js';
4
+
5
+ /**
6
+ * Builds the lib.
7
+ * @param {{ cwd?: string; dev?: boolean }} options
8
+ * @return {Promise<void>}
9
+ */
10
+ async function build({ dev = false } = {}) {
11
+ const rootPath = '.';
12
+ const sourcePath = './src';
13
+ const destinationPath = './dist';
14
+
15
+ await removeDestination(destinationPath);
16
+
17
+ try {
18
+ const [withProtected] = await Promise.all([
19
+ buildTypescript(sourcePath),
20
+ buildScss(sourcePath, destinationPath),
21
+ copyOtherFiles(rootPath, destinationPath),
22
+ ]);
23
+
24
+ await buildPackageJsonFile(destinationPath, {
25
+ dev,
26
+ withProtected,
27
+ });
28
+ } catch (error) {
29
+ await removeDestination(destinationPath);
30
+ throw error;
31
+ }
32
+
33
+ console.log('Library built with success !');
34
+ }
35
+
36
+ /**
37
+ * Removes the destination folder.
38
+ *
39
+ * @param {string} destinationPath
40
+ * @return {Promise<void>}
41
+ */
42
+ async function removeDestination(destinationPath) {
43
+ await rm(destinationPath, { recursive: true, force: true });
44
+ }
45
+
46
+ /**
47
+ * Builds the typescript part.
48
+ *
49
+ * @param {string} sourcePath
50
+ * @return {Promise<boolean>}
51
+ */
52
+ async function buildTypescript(sourcePath) {
53
+ const typescriptIndexFilePath = await buildTypescriptIndexFile(sourcePath);
54
+ const typescriptProtectedIndexFilePath = await buildTypescriptProtectedIndexFile(sourcePath);
55
+
56
+ try {
57
+ await compileTypescript();
58
+ // await copyTypescriptFiles(sourcePath, destinationPath);
59
+ } finally {
60
+ await removeTypescriptIndexFile(typescriptIndexFilePath);
61
+ if (typescriptProtectedIndexFilePath !== null) {
62
+ await removeTypescriptIndexFile(typescriptProtectedIndexFilePath);
63
+ }
64
+ }
65
+
66
+ return typescriptProtectedIndexFilePath !== null;
67
+ }
68
+
69
+ /**
70
+ * Builds the scss part.
71
+ *
72
+ * @param {string} sourcePath
73
+ * @param {string} destinationPath
74
+ * @return {Promise<void>}
75
+ */
76
+ async function buildScss(sourcePath, destinationPath) {
77
+ await copyScssFiles(sourcePath, destinationPath);
78
+ await buildScssIndexFile(destinationPath);
79
+ }
80
+
81
+ /**
82
+ * Builds the typescript index file used to export all public APIs.
83
+ *
84
+ * @param {string} cwd
85
+ * @return {Promise<string>}
86
+ */
87
+ async function buildTypescriptIndexFile(cwd = process.cwd()) {
88
+ console.log('Building typescript index file...');
89
+
90
+ const content = (
91
+ await Array.fromAsync(
92
+ glob('./**/*.ts', {
93
+ cwd,
94
+ exclude: (path) => {
95
+ return (
96
+ path.endsWith('.spec.ts') ||
97
+ path.endsWith('.test.ts') ||
98
+ path.includes('.private') ||
99
+ path.includes('.protected')
100
+ );
101
+ },
102
+ }),
103
+ )
104
+ )
105
+ .map((path) => {
106
+ return `export * from './${path.slice(0, -3)}.js';`;
107
+ })
108
+ .join('\n');
109
+
110
+ if (content === '') {
111
+ throw new Error('Nothing exported.');
112
+ }
113
+
114
+ const indexFilePath = join(cwd, 'index.ts');
115
+ await writeFile(indexFilePath, content + '\n');
116
+
117
+ return indexFilePath;
118
+ }
119
+
120
+ /**
121
+ * Builds the typescript index file used to export all protected APIs.
122
+ *
123
+ * @param {string} cwd
124
+ * @return {Promise<string | null>}
125
+ */
126
+ async function buildTypescriptProtectedIndexFile(cwd = process.cwd()) {
127
+ console.log('Building typescript protected index file...');
128
+
129
+ const content = (
130
+ await Array.fromAsync(
131
+ glob('{./**/*.protected/**/*.ts,./**/*.protected.ts,}', {
132
+ cwd,
133
+ exclude: (path) => {
134
+ return (
135
+ path.endsWith('.spec.ts') || path.endsWith('.test.ts') || path.includes('.private')
136
+ );
137
+ },
138
+ }),
139
+ )
140
+ )
141
+ .map((path) => {
142
+ return `export * from './${path.slice(0, -3)}.js';`;
143
+ })
144
+ .join('\n');
145
+
146
+ if (content === '') {
147
+ return null;
148
+ }
149
+
150
+ const indexFilePath = join(cwd, 'index.protected.ts');
151
+ await writeFile(indexFilePath, content + '\n');
152
+
153
+ return indexFilePath;
154
+ }
155
+
156
+ /**
157
+ * Compiles the typescript files.
158
+ *
159
+ * @param {string | undefined } cwd
160
+ * @return {Promise<void>}
161
+ */
162
+ async function compileTypescript(cwd = process.cwd()) {
163
+ console.log('Compiling typescript...');
164
+
165
+ await cmd('tsc', ['-p', './tsconfig.build.json'], { cwd });
166
+ }
167
+
168
+ /**
169
+ * Copies typescript files into the destination.
170
+ *
171
+ * @param {string} sourcePath
172
+ * @param {string} destinationPath
173
+ * @return {Promise<void>}
174
+ */
175
+ async function copyTypescriptFiles(sourcePath, destinationPath) {
176
+ console.log('Copying typescript files...');
177
+
178
+ for await (const path of glob('./**/!(*.spec|*.test).ts', { cwd: sourcePath })) {
179
+ await cp(join(sourcePath, path), join(destinationPath, path));
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Builds the typescript index file used to export all public APIs.
185
+ *
186
+ * @param {string} cwd
187
+ * @return {Promise<void>}
188
+ */
189
+ async function buildScssIndexFile(cwd = process.cwd()) {
190
+ console.log('Building scss index file...');
191
+
192
+ // TODO exclude directories too
193
+ const content = (await Array.fromAsync(glob('./**/!(*.private).scss', { cwd })))
194
+ .map((path) => {
195
+ return `@forward './${path.slice(0, -5)}';`;
196
+ })
197
+ .join('\n');
198
+
199
+ if (content === '') {
200
+ console.log('=> No scss file to export.');
201
+ } else {
202
+ const indexFilePath = join(cwd, 'index.scss');
203
+ await writeFile(indexFilePath, content + '\n');
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Copies scss files into the destination.
209
+ *
210
+ * @param {string} sourcePath
211
+ * @param {string} destinationPath
212
+ * @return {Promise<void>}
213
+ */
214
+ async function copyScssFiles(sourcePath, destinationPath) {
215
+ console.log('Copying scss files...');
216
+
217
+ for await (const path of glob('./**/!(*.private).scss', { cwd: sourcePath })) {
218
+ // await cp(join(sourcePath, path), join(destinationPath, path));
219
+ await writeFile(
220
+ join(destinationPath, path),
221
+ fixScssFileContent(await readFile(join(sourcePath, path), { encoding: 'utf8' })),
222
+ );
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Fixes the content of a scss file.
228
+ *
229
+ * @param {string} content
230
+ * @return {string}
231
+ */
232
+ function fixScssFileContent(content) {
233
+ return content.replace(/@(use|import)\s+['"]([^'"]*)['"]/g, (_, type, importPath) => {
234
+ if (isAbsolute(importPath)) {
235
+ throw new Error(`Import path ${importPath} cannot be absolute.`);
236
+ }
237
+
238
+ if (!importPath.startsWith('./') && !importPath.startsWith('../')) {
239
+ importPath = `./${importPath}`;
240
+ }
241
+
242
+ if (importPath.endsWith('.scss')) {
243
+ importPath = importPath.slice(0, -5);
244
+ }
245
+
246
+ return `@${type} '${fixScssFilePath(importPath)}'`;
247
+ });
248
+ }
249
+
250
+ /**
251
+ * Fixes a scss file path.
252
+ *
253
+ * @param {string} path
254
+ * @return {string}
255
+ */
256
+ function fixScssFilePath(path) {
257
+ if (!path.startsWith('@')) {
258
+ if (isAbsolute(path)) {
259
+ throw new Error(`Import path ${path} cannot be absolute.`);
260
+ }
261
+
262
+ if (!path.startsWith('./') && !path.startsWith('../')) {
263
+ path = `./${path}`;
264
+ }
265
+ }
266
+
267
+ if (path.endsWith('.scss')) {
268
+ path = path.slice(0, -5);
269
+ }
270
+
271
+ return path;
272
+ }
273
+
274
+ /**
275
+ * Copies other files.
276
+ *
277
+ * @param {string} rootPath
278
+ * @param {string} destinationPath
279
+ * @return {Promise<void>}
280
+ */
281
+ async function copyOtherFiles(rootPath, destinationPath) {
282
+ console.log('Copying other files...');
283
+
284
+ await Promise.all(
285
+ ['README.md', 'CONTRIBUTING.md', 'LICENSE'].map((path) => {
286
+ return cp(join(rootPath, path), join(destinationPath, path)).catch(() => {
287
+ console.log(`Missing file: ${path}`);
288
+ });
289
+ }),
290
+ );
291
+ }
292
+
293
+ /**
294
+ * Removes the index file.
295
+ *
296
+ * @param {string} indexFilePath
297
+ * @return {Promise<void>}
298
+ */
299
+ async function removeTypescriptIndexFile(indexFilePath) {
300
+ await rm(indexFilePath);
301
+ }
302
+
303
+ /**
304
+ * Generates the package.json to publish.
305
+ *
306
+ * @param {string} destinationPath
307
+ * @param {{ cwd?: string; dev?: boolean, withProtected?: boolean }} options
308
+ * @return {Promise<void>}
309
+ */
310
+ async function buildPackageJsonFile(
311
+ destinationPath,
312
+ { cwd = process.cwd(), dev = false, withProtected = false } = {},
313
+ ) {
314
+ console.log('Building package.json...');
315
+
316
+ const fileName = 'package.json';
317
+
318
+ /**
319
+ * @type any
320
+ */
321
+ const pkg = JSON.parse(await readFile(join(cwd, fileName), { encoding: 'utf8' }));
322
+
323
+ const indexTypesPath = './index.d.ts';
324
+
325
+ if (dev) {
326
+ pkg.version += `-dev.${Date.now()}`;
327
+ }
328
+
329
+ Object.assign(pkg, {
330
+ exports: {
331
+ '.': {
332
+ types: indexTypesPath,
333
+ default: './index.js',
334
+ },
335
+ ...(withProtected
336
+ ? {
337
+ './protected': {
338
+ types: './index.protected.d.ts',
339
+ default: './index.protected.js',
340
+ },
341
+ }
342
+ : {}),
343
+ },
344
+ typings: indexTypesPath,
345
+ types: indexTypesPath,
346
+ });
347
+
348
+ await writeFile(join(destinationPath, fileName), JSON.stringify(pkg, null, 2));
349
+ }
350
+
351
+ /*-----------------------------------*/
352
+
353
+ const [dev = false] = process.argv.slice(2);
354
+
355
+ build({ dev });
@@ -0,0 +1,44 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ /**
4
+ * Runs "command" into the terminal.
5
+ * @param {string} command
6
+ * @param {readonly string[]} args
7
+ * @param {SpawnOptions | undefined} options
8
+ */
9
+ export async function cmd(command, args = [], options) {
10
+ return new Promise((resolve, reject) => {
11
+ console.log(`> ${command} ${args.join(' ')}`);
12
+
13
+ const childProcess = spawn(command, args, {
14
+ cwd: process.cwd(),
15
+ detached: false,
16
+ stdio: 'inherit',
17
+ ...options,
18
+ });
19
+
20
+ childProcess.on('exit', (code) => {
21
+ if (code === 0) {
22
+ resolve();
23
+ } else {
24
+ reject(new Error(`Exit with code ${code}.`));
25
+ }
26
+ });
27
+
28
+ childProcess.on('error', (err) => {
29
+ reject(err);
30
+ });
31
+
32
+ // process.on('SIGINT', () => {
33
+ // childProcess.kill('SIGINT');
34
+ // });
35
+ //
36
+ // process.on('SIGTERM', () => {
37
+ // childProcess.kill('SIGTERM');
38
+ // });
39
+ //
40
+ // process.on('SIGBREAK', () => {
41
+ // childProcess.kill('SIGBREAK');
42
+ // });
43
+ });
44
+ }
@@ -0,0 +1,18 @@
1
+ export namespace testTools {
2
+ export function sleep(t: number): Promise<void> {
3
+ return new Promise((_) => setTimeout(_, t));
4
+ }
5
+
6
+ export function polyfillRequestIdleCallback(): void {
7
+ globalThis.requestIdleCallback ??= (
8
+ callback: IdleRequestCallback,
9
+ { timeout = 0 }: IdleRequestOptions = {},
10
+ ): number => {
11
+ return setTimeout(callback, timeout);
12
+ };
13
+
14
+ globalThis.cancelIdleCallback ??= (handle: number): void => {
15
+ clearTimeout(handle);
16
+ };
17
+ }
18
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "{{libname}}",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "main": "./index.js",
6
+ "scripts": {
7
+ "fb:build": "node fabrique/actions/build.js",
8
+ "fb:format": "prettier --write --ignore-unknown --config ./.prettierrc \"src/**/*.{js,jsx,ts,tsx,html,css,scss}\"",
9
+ "fb:test": "vitest",
10
+ "fb:test:coverage": "vitest run --coverage",
11
+ "fb:prod": "node fabrique/actions/build.js && cd dist && npm publish --access public --registry https://registry.npmjs.org",
12
+ "fb:dev": "node fabrique/actions/build.js --dev && cd dist && npm publish --quiet --registry http://localhost:4873"
13
+ },
14
+ "description": "{{description}}",
15
+ "keywords": [],
16
+ "author": "{{author}}",
17
+ "license": "MIT",
18
+ "access": "public",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "{{giturl}}"
22
+ },
23
+ "devDependencies": {
24
+ "prettier": "^3.3.3",
25
+ "prettier-plugin-organize-imports": "^4.1.0",
26
+ "typescript": "^5.6.3",
27
+ "vitest": "^2.1.4"
28
+ },
29
+ "packageManager": "yarn@4.5.1"
30
+ }
@@ -0,0 +1,8 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { add } from './add.js';
3
+
4
+ describe('add', () => {
5
+ it('should return correct result', () => {
6
+ expect(add(1, 2)).toBe(3);
7
+ });
8
+ });
@@ -0,0 +1,3 @@
1
+ export function add(a: number, b: number): number {
2
+ return a + b;
3
+ }
@@ -0,0 +1,5 @@
1
+ @use 'variables' as variables;
2
+
3
+ :host {
4
+ background-color: variables.$color-red;
5
+ }
@@ -0,0 +1,5 @@
1
+ @use 'variables' as variables;
2
+
3
+ :host {
4
+ color: variables.$color-red;
5
+ }
@@ -0,0 +1,3 @@
1
+ export function sub(a: number, b: number): number {
2
+ return a - b;
3
+ }
@@ -0,0 +1 @@
1
+ $color-red: red;
@@ -0,0 +1,17 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "declarationDir": "./dist",
6
+ "downlevelIteration": false,
7
+ "emitDecoratorMetadata": false,
8
+ "importHelpers": false,
9
+ "noEmitHelpers": false,
10
+ "noLib": false,
11
+ "outDir": "dist",
12
+ "preserveConstEnums": false,
13
+ "pretty": true,
14
+ "removeComments": false,
15
+ "sourceMap": true
16
+ }
17
+ }
@@ -0,0 +1,37 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowSyntheticDefaultImports": true,
4
+ "allowUnreachableCode": false,
5
+ "allowUnusedLabels": false,
6
+ "alwaysStrict": true,
7
+ "experimentalDecorators": true,
8
+ "lib": [
9
+ "ESNext",
10
+ "DOM"
11
+ ],
12
+ "module": "NodeNext",
13
+ "moduleResolution": "NodeNext",
14
+ "noFallthroughCasesInSwitch": false,
15
+ "noImplicitAny": true,
16
+ "noImplicitReturns": true,
17
+ "noImplicitThis": true,
18
+ "noImplicitUseStrict": false,
19
+ "noUnusedLocals": false,
20
+ "strict": true,
21
+ "strictFunctionTypes": true,
22
+ "strictNullChecks": true,
23
+ "strictPropertyInitialization": true,
24
+ "stripInternal": false,
25
+ "target": "esnext",
26
+ "typeRoots": [
27
+ "node_modules/@types"
28
+ ]
29
+ },
30
+ "include": [
31
+ "src/**/*"
32
+ ],
33
+ "exclude": [
34
+ "src/**/*.spec.ts",
35
+ "src/**/*.test.ts",
36
+ ]
37
+ }
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ // ...
6
+ },
7
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowUnreachableCode": false,
4
+ "allowUnusedLabels": false,
5
+ "alwaysStrict": true,
6
+ "declaration": false,
7
+ "downlevelIteration": false,
8
+ "emitDecoratorMetadata": false,
9
+ "experimentalDecorators": true,
10
+ "noEmitHelpers": false,
11
+ "noFallthroughCasesInSwitch": false,
12
+ "noImplicitUseStrict": false,
13
+ "noLib": false,
14
+ "pretty": true,
15
+ "removeComments": true,
16
+ "preserveConstEnums": false,
17
+ "sourceMap": true,
18
+ "strictFunctionTypes": true,
19
+ "noImplicitAny": true,
20
+ "noImplicitReturns": true,
21
+ "noImplicitThis": true,
22
+ "strictNullChecks": true,
23
+ "strictPropertyInitialization": true,
24
+ "noUnusedLocals": false,
25
+ "stripInternal": false,
26
+ "strict": true,
27
+ "allowSyntheticDefaultImports": true,
28
+ "module": "esnext",
29
+ "moduleResolution": "bundler",
30
+ "target": "esnext",
31
+ "lib": [
32
+ "ESNext",
33
+ "DOM"
34
+ ],
35
+ "outDir": "dist",
36
+ "typeRoots": [
37
+ "node_modules/@types"
38
+ ]
39
+ },
40
+ "include": [
41
+ "src"
42
+ ]
43
+ }
package/index.js DELETED
@@ -1,13 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { program } from "commander";
4
-
5
- program
6
- .version("1.0.0")
7
- .description("My Node CLI")
8
- .option("-n, --name <type>", "Add your name")
9
- .action((options) => {
10
- console.log(`Hey, ${options.name}!`);
11
- });
12
-
13
- program.parse(process.argv);