@cmmn/tools 1.1.0 → 1.2.3

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.
package/bin.js CHANGED
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
-
3
- import {bundle} from "./bundle/bundle.js";
4
- import {compile} from "./compile/compile.js";
5
-
6
- const [action, ...args] = process.argv.slice(2);
7
-
8
- const actions = {
9
- bundle, compile
10
- }
11
-
12
- actions[action](...args);
2
+
3
+ import {bundle} from "./bundle/bundle.js";
4
+ import {compile} from "./compile/compile.js";
5
+ import {gen} from "./gen/gen.js";
6
+
7
+ const [action, ...args] = process.argv.slice(2);
8
+
9
+ const actions = {
10
+ bundle, compile, gen
11
+ }
12
+
13
+ actions[action](...args);
package/bundle/bundle.js CHANGED
@@ -1,101 +1,116 @@
1
- import {getConfig} from "./rollup.config.js";
2
- import {rollup, watch} from "rollup";
3
- import fs from "fs";
4
- import path from "path";
5
- import fg from "fast-glob";
6
-
7
- function getPackageConfigs(rootDir, options) {
8
- const results = [];
9
- const pkg = JSON.parse(fs.readFileSync(path.join(rootDir, 'package.json')));
10
- for (let name in pkg.cmmn) {
11
- results.push(...getConfig({
12
- name,
13
- outDir: path.join(rootDir, pkg.cmmn[name].output ?? 'dist'),
14
- input: path.join(rootDir, pkg.cmmn[name].input ?? 'index.ts'),
15
- minify: options.includes('--prod'),
16
- devServer: options.includes('--run'),
17
- stats: options.includes('--stats'),
18
- module: pkg.cmmn[name].module ?? 'es'
19
- }))
20
- }
21
- return results;
22
- }
23
-
24
- function getLernaSubPackages(lernaFile, options) {
25
- const config = JSON.parse(fs.readFileSync(lernaFile, 'utf8'));
26
- const packages = config.packages;
27
- const dirs = packages.flatMap(pkg => fg.sync([pkg], {
28
- absolute: true,
29
- globstar: true,
30
- onlyDirectories: true,
31
- cwd: path.dirname(lernaFile)
32
- }));
33
- return dirs.flatMap(dir => getPackageConfigs(dir, options));
34
- }
35
-
36
- function getConfigs(options) {
37
- if (options.includes('-b')) {
38
- const rootDir = process.cwd();
39
- const lernaPath = path.join(rootDir, 'lerna.json');
40
- if (fs.existsSync(lernaPath)) {
41
- return getLernaSubPackages(lernaPath, options);
42
- }
43
- }
44
- const input = options.filter(x => !x.startsWith('-'))[0];
45
- return getConfig({
46
- input,
47
- minify: options.includes('--prod'),
48
- devServer: options.includes('--run'),
49
- stats: options.includes('--stats'),
50
- module: 'es'
51
- });
52
- }
53
-
54
- export async function bundle(...options) {
55
- const configs = getConfigs(options);
56
- if (!options.includes('--watch')) {
57
- for (let config of configs) {
58
- console.log(`1. ${config.input} -> ${config.output.file}`);
59
- const build = await rollup(config);
60
- await build.write(config.output);
61
- console.log('SUCCESS');
62
- }
63
- return;
64
- }
65
- const watcher = watch(configs);
66
- watcher.on('event', (event) => {
67
- switch (event.code) {
68
- case 'START':
69
- console.clear();
70
- console.log('START BUNDLING');
71
- break;
72
- case 'END':
73
- console.log('FINISH');
74
- break;
75
- case 'BUNDLE_START':
76
- console.log(`1. ${event.input} -> ${event.output}`);
77
- break;
78
- case 'BUNDLE_END':
79
- console.log(`1. ${event.input} -> ${event.output}, (${event.duration / 1000}s)`);
80
- break;
81
-
82
- case 'ERROR':
83
- switch (event.error.code) {
84
- case 'PARSE_ERROR':
85
- console.warn('Error parsing files:');
86
- console.log(`\t${event.error.parserError.message}`);
87
- console.log(`\tat: ${event.error.id}`);
88
- console.log(`\tline: ${event.error.frame}`);
89
- break;
90
- case 'UNRESOLVED_IMPORT':
91
- console.error(event.error.message);
92
- break;
93
- default:
94
- console.warn('Unknown error:', event.error.code);
95
- console.error(event.error);
96
- break;
97
- }
98
- break;
99
- }
100
- });
101
- }
1
+ import {ConfigCreator} from "./rollup.config.js";
2
+ import {rollup, watch} from "rollup";
3
+ import fs from "fs";
4
+ import path from "path";
5
+ import fg from "fast-glob";
6
+
7
+ function getProjectConfig(rootDir, cmmn, options) {
8
+ const configCreator = new ConfigCreator({
9
+ ...options,
10
+ ...cmmn,
11
+ });
12
+ configCreator.setRootDir(rootDir);
13
+ return configCreator.getConfig();
14
+ }
15
+
16
+ function getPackageConfigs(rootDir, options, name = null) {
17
+ const results = [];
18
+ const pkg = JSON.parse(fs.readFileSync(path.join(rootDir, 'package.json')));
19
+ if (name) {
20
+ results.push(...getProjectConfig(rootDir, pkg.cmmn[name], {
21
+ ...options,
22
+ name
23
+ }));
24
+ } else {
25
+ for (let name in pkg.cmmn) {
26
+ results.push(...getProjectConfig(rootDir, pkg.cmmn[name], {
27
+ ...options,
28
+ name
29
+ }));
30
+ }
31
+ }
32
+ return results;
33
+ }
34
+
35
+ function getLernaSubPackages(lernaFile, options) {
36
+ const config = JSON.parse(fs.readFileSync(lernaFile, 'utf8'));
37
+ const packages = config.packages;
38
+ const dirs = packages.flatMap(pkg => fg.sync([pkg], {
39
+ absolute: true,
40
+ globstar: true,
41
+ onlyDirectories: true,
42
+ cwd: path.dirname(lernaFile)
43
+ }));
44
+ return dirs.flatMap(dir => getPackageConfigs(dir, options));
45
+ }
46
+
47
+ function getConfigs(options) {
48
+ if (!options.input || options.project) {
49
+ const rootDir = process.cwd();
50
+ const lernaPath = path.join(rootDir, 'lerna.json');
51
+ if (fs.existsSync(lernaPath)) {
52
+ return getLernaSubPackages(lernaPath, options);
53
+ }
54
+ return getPackageConfigs(process.cwd(), options);
55
+ }
56
+ if (!options.input.includes('.') || !fs.existsSync(options.input)) {
57
+ return getPackageConfigs(process.cwd(), options, options.input);
58
+ }
59
+ const creator = new ConfigCreator(options);
60
+ return creator.getConfig();
61
+ }
62
+
63
+ export async function bundle(...options) {
64
+ const configs = getConfigs({
65
+ input: options.filter(x => !x.startsWith('-'))[0],
66
+ project: options.includes('-b'),
67
+ minify: options.includes('--prod'),
68
+ devServer: options.includes('--run'),
69
+ stats: options.includes('--stats'),
70
+ });
71
+ if (!options.includes('--watch')) {
72
+ for (let config of configs) {
73
+ console.log(`1. ${config.input} -> ${config.output.file}`);
74
+ const build = await rollup(config);
75
+ await build.write(config.output);
76
+ console.log('SUCCESS');
77
+ }
78
+ return;
79
+ }
80
+ const watcher = watch(configs);
81
+ watcher.on('event', (event) => {
82
+ switch (event.code) {
83
+ case 'START':
84
+ console.clear();
85
+ console.log('START BUNDLING');
86
+ break;
87
+ case 'END':
88
+ console.log('FINISH');
89
+ break;
90
+ case 'BUNDLE_START':
91
+ console.log(`1. ${event.input} -> ${event.output}`);
92
+ break;
93
+ case 'BUNDLE_END':
94
+ console.log(`1. ${event.input} -> ${event.output}, (${event.duration / 1000}s)`);
95
+ break;
96
+
97
+ case 'ERROR':
98
+ switch (event.error.code) {
99
+ case 'PARSE_ERROR':
100
+ console.warn('Error parsing files:');
101
+ console.log(`\t${event.error.parserError.message}`);
102
+ console.log(`\tat: ${event.error.id}`);
103
+ console.log(`\tline: ${event.error.frame}`);
104
+ break;
105
+ case 'UNRESOLVED_IMPORT':
106
+ console.error(event.error.message);
107
+ break;
108
+ default:
109
+ console.warn('Unknown error:', event.error.code);
110
+ console.error(event.error);
111
+ break;
112
+ }
113
+ break;
114
+ }
115
+ });
116
+ }
@@ -1,61 +1,196 @@
1
- import commonjs from '@rollup/plugin-commonjs';
2
- import nodeResolve from '@rollup/plugin-node-resolve';
3
- import {terser} from "rollup-plugin-terser"
4
- import {visualizer} from 'rollup-plugin-visualizer';
5
- import styles from "rollup-plugin-styles";
6
- import {string} from "rollup-plugin-string";
7
- import serve from 'rollup-plugin-serve'
8
- import livereload from 'rollup-plugin-livereload'
9
-
10
- export const getConfig = ({minify, input, devServer, module, stats, name, outDir}) => {
11
- const output = `${outDir ?? 'dist'}/${name ?? 'index'}-${module}${minify ? '.min' : ''}.js`;
12
- return [{
13
- input,
14
- output: {
15
- file: output,
16
- sourcemap: !minify,
17
- format: module,
18
- exports: 'auto',
19
- name: 'global'
20
- },
21
- onwarn: function () {
22
-
23
- },
24
- // prettier-ignore
25
- plugins: [
26
- nodeResolve({
27
- browser: true,
28
- dedupe: ['lib0']
29
- }),
30
- commonjs({}),
31
- styles({mode: "emit"}),
32
- string({
33
- include: /\.(html|svg|less|css)$/,
34
- }),
35
- ...(minify ? [terser({})] : []),
36
- ...(devServer ? [
37
- serve({
38
- open: false,
39
- contentBase: ['dist', 'assets'],
40
- port: 3001,
41
- historyApiFallback: true
42
- }), livereload({
43
- watch: ['dist', 'assets'],
44
- verbose: false, // Disable console output
45
-
46
- // other livereload options
47
- port: 12345,
48
- delay: 300,
49
- })] : []),
50
- ...(stats ? [
51
- visualizer({
52
- open: true,
53
- sourcemap: true,
54
- template: 'treemap',
55
- brotliSize: true,
56
- filename: 'dist/stats.html'
57
- }),
58
- ] : [])
59
- ]
60
- }];
61
- };
1
+ import commonjs from '@rollup/plugin-commonjs';
2
+ import nodeResolve from '@rollup/plugin-node-resolve';
3
+ import {terser} from "rollup-plugin-terser"
4
+ import {visualizer} from 'rollup-plugin-visualizer';
5
+ import styles from "rollup-plugin-styles";
6
+ import {string} from "rollup-plugin-string";
7
+ import serve from 'rollup-plugin-serve'
8
+ import livereload from 'rollup-plugin-livereload'
9
+ import fs from "fs";
10
+ import path from "path";
11
+ import html from '@open-wc/rollup-plugin-html';
12
+ import json from '@rollup/plugin-json';
13
+ import alias from '@rollup/plugin-alias';
14
+
15
+ /**
16
+ * @typedef {import(rollup).RollupOptions} RollupOptions
17
+ * @typedef {import(rollup).OutputOptions} OutputOptions
18
+ */
19
+
20
+ export class ConfigCreator {
21
+
22
+ /**
23
+ * @type {{
24
+ * minify: boolean,
25
+ * input: string,
26
+ * devServer: boolean,
27
+ * module: string,
28
+ * external: string[],
29
+ * stats: boolean,
30
+ * name: string,
31
+ * outDir: string,
32
+ * html: string,
33
+ * browser: boolean,
34
+ * dedupe: string[]
35
+ * }}
36
+ */
37
+ options;
38
+
39
+ /**
40
+ * @type {string}
41
+ */
42
+ root = process.cwd();
43
+
44
+
45
+ constructor(options) {
46
+ this.options = {
47
+ ...options
48
+ };
49
+ }
50
+
51
+ setRootDir(rootDir) {
52
+ this.root = rootDir;
53
+ }
54
+
55
+ get outDir() {
56
+ return path.join(this.root, this.options.outDir);
57
+ }
58
+
59
+ /**
60
+ *
61
+ * @returns {OutputOptions}
62
+ */
63
+ get output() {
64
+ // const output = `${this.options.name ?? 'index'}-${this.options.module}${this.options.minify ? '.min' : ''}.js`;
65
+ return {
66
+ entryFileNames: `[name]-${this.options.module}${this.options.minify ? '.min' : ''}.js`,
67
+ // file: output,
68
+ dir: this.outDir,
69
+ sourcemap: true,
70
+ format: this.options.module,
71
+ name: 'global',
72
+ };
73
+ }
74
+
75
+ get html() {
76
+ return html({
77
+ publicPath: '/',
78
+ dir: this.outDir,
79
+ template: () => fs.readFileSync(path.join(this.root, this.options.html), 'utf8')
80
+ });
81
+ }
82
+
83
+ get devServer() {
84
+ return serve({
85
+ open: false,
86
+ contentBase: [this.outDir, path.join(this.root, 'assets')],
87
+ port: 3001,
88
+ historyApiFallback: true
89
+ });
90
+ }
91
+
92
+ get livereload() {
93
+ return livereload({
94
+ watch: [this.outDir, path.join(this.root, 'assets')],
95
+ verbose: false, // Disable console output
96
+ // other livereload options
97
+ port: 12345,
98
+ delay: 300,
99
+ })
100
+ }
101
+
102
+ get visualizer() {
103
+ return visualizer({
104
+ open: true,
105
+ sourcemap: true,
106
+ template: 'treemap',
107
+ brotliSize: true,
108
+
109
+ filename: path.join(this.outDir, '/stats.html')
110
+ })
111
+ }
112
+
113
+ get plugins() {
114
+ const result = [
115
+ // builtins(),
116
+ nodeResolve({
117
+ browser: this.options.browser,
118
+ dedupe: this.options.dedupe || []
119
+ }),
120
+ commonjs({
121
+ requireReturnsDefault: "namespace",
122
+ }),
123
+ styles({
124
+ mode: "emit",
125
+ }),
126
+ string({
127
+ include: /\.(html|svg|less|css)$/,
128
+ }),
129
+ json(),
130
+
131
+ ];
132
+ if (this.options.alias) {
133
+ result.unshift(alias({
134
+ entries: this.options.alias
135
+ }));
136
+ console.log(this.options.alias)
137
+ }
138
+ if (this.options.html || this.options.input.endsWith('.html')) {
139
+ result.push(this.html);
140
+ }
141
+ if (this.options.minify) {
142
+ result.push(terser({
143
+ module: true,
144
+ ecma: 2020,
145
+ compress: true,
146
+ keep_classnames: false,
147
+ keep_fnames: false,
148
+ mangle: true,
149
+ output: {
150
+ comments: false
151
+ }
152
+ }));
153
+ }
154
+ if (this.options.devServer) {
155
+ result.push(this.devServer, this.livereload);
156
+ }
157
+ if (this.options.stats) {
158
+ result.push(this.visualizer);
159
+ }
160
+ return result;
161
+ }
162
+
163
+ /**
164
+ * @returns {RollupOptions[]}
165
+ */
166
+ getConfig() {
167
+ Object.assign(this.options, {
168
+ module: this.options.module || 'es',
169
+ external: this.options.external || [],
170
+ name: this.options.name || 'index',
171
+ outDir: this.options.outDir || 'dist'
172
+ });
173
+ if (this.options.external && typeof this.options.external === "string")
174
+ this.options.external = [this.options.external]
175
+ console.log(this.options);
176
+ return [{
177
+ input: {
178
+ [this.options.name]: path.join(this.root, this.options.input)
179
+ },
180
+ output: this.output,
181
+ external: (this.options.external || []).map(s => new RegExp(s)),
182
+ onwarn(warning) {
183
+ // Silence circular dependency warning for moment package
184
+ if (
185
+ warning.code === 'CIRCULAR_DEPENDENCY'
186
+ ) {
187
+ return
188
+ }
189
+
190
+ console.warn(`(!) ${warning.message}`)
191
+ },
192
+ plugins: this.plugins,
193
+ treeshake: this.options.minify ? "smallest" : "recommended",
194
+ }]
195
+ }
196
+ }
@@ -0,0 +1,33 @@
1
+ import ts from "ttypescript";
2
+ import {resolve} from 'path';
3
+
4
+ const rootDir = process.cwd();
5
+
6
+ export function compile(...flags) {
7
+
8
+ const host = ts.createSolutionBuilderWithWatchHost(ts.sys, createProgram);
9
+ host.useCaseSensitiveFileNames();
10
+
11
+ const builderFactory = flags.includes('--watch') ?
12
+ ts.createSolutionBuilderWithWatch :
13
+ ts.createSolutionBuilder;
14
+
15
+ const builder = builderFactory(host, [rootDir], {
16
+ incremental: true,
17
+ dry: false
18
+ }, {
19
+ excludeDirectories: ["node_modules", "dist"]
20
+ });
21
+ builder.clean(rootDir);
22
+ builder.build(rootDir);
23
+ }
24
+
25
+ function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) {
26
+ options.outDir = resolve(options.configFilePath, '../dist/esm');
27
+ options.declarationDir = resolve(options.configFilePath, '../dist/typings');
28
+ options.baseUrl = resolve(options.configFilePath, '../');
29
+ console.log('build', options.configFilePath);
30
+ return ts.createEmitAndSemanticDiagnosticsBuilderProgram(
31
+ rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences
32
+ )
33
+ }
@@ -0,0 +1,47 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "esnext",
4
+ "moduleResolution": "Node",
5
+ "target": "ES2019",
6
+ "composite": true,
7
+ "sourceMap": true,
8
+ "baseUrl": "./",
9
+ "experimentalDecorators": true,
10
+ "checkJs": false,
11
+ "outDir": "./dist/esm",
12
+ "skipLibCheck": true,
13
+ "skipDefaultLibCheck": true,
14
+ "allowJs": true,
15
+ "allowSyntheticDefaultImports": true,
16
+ "emitDecoratorMetadata": true ,
17
+ "noEmitHelpers": true,
18
+ "declarationDir": "./dist/typings",
19
+ "declaration": true,
20
+ "types": [
21
+ ],
22
+ "lib": [
23
+ "ES2020.BigInt",
24
+ "ESNext",
25
+ "DOM"
26
+ ],
27
+ "plugins": [
28
+ {
29
+ "transform": "@cmmn/tools/plugins/absolute-plugin.cjs",
30
+ "after": true
31
+ },
32
+ // Transform paths in output .js files
33
+ {
34
+ "transform": "typescript-transform-paths"
35
+ },
36
+ // Transform paths in output .d.ts files (Include this line if you output declarations files)
37
+ {
38
+ "transform": "typescript-transform-paths",
39
+ "afterDeclarations": true
40
+ }
41
+ ]
42
+ },
43
+ "exclude": [
44
+ "node_modules",
45
+ "dist"
46
+ ]
47
+ }
@@ -0,0 +1,16 @@
1
+ import {component, HtmlComponent, property} from "@cmmn/ui";
2
+ import {template, IState, IEvents} from "./$name$.template";
3
+ import style from "./$name$.style.less";
4
+ import {Injectable} from "@cmmn/core";
5
+
6
+ @Injectable(true)
7
+ @component({name: '$name$', template, style})
8
+ export class $Name$Component extends HtmlComponent<IState, IEvents> {
9
+
10
+ @property()
11
+ private property!: any;
12
+
13
+ get State() {
14
+ return this.property;
15
+ }
16
+ }
package/gen/gen.js ADDED
@@ -0,0 +1,27 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import {fileURLToPath} from 'url';
4
+ import {execSync} from "child_process";
5
+
6
+ const currentDir = '__dirname' in global ? __dirname : path.dirname(fileURLToPath(import.meta.url));
7
+
8
+ const templateTpl = fs.readFileSync(path.join(currentDir, './template.ts.tpl'), 'utf8');
9
+ const componentTpl = fs.readFileSync(path.join(currentDir, './component.ts.tpl'), 'utf8');
10
+ const styleTpl = fs.readFileSync(path.join(currentDir, './style.less.tpl'), 'utf8');
11
+
12
+
13
+ export function gen(name, directory, nested = false) {
14
+ const Name = name.replace(/^./, c => c.toUpperCase());
15
+ name = Name.replace(/[A-Z]/g, (c, i) => (i ? '-' : '') + c.toLowerCase());
16
+ process.chdir(directory);
17
+ if (nested) {
18
+ fs.mkdirSync(name);
19
+ process.chdir(name);
20
+ }
21
+ fs.writeFileSync(name + '.component.ts', componentTpl.replace(/\$Name\$/g, Name).replace(/\$name\$/g, name), 'utf8');
22
+ fs.writeFileSync(name + '.template.ts', templateTpl.replace(/\$Name\$/g, Name).replace(/\$name\$/g, name), 'utf8');
23
+ fs.writeFileSync(name + '.style.less', styleTpl.replace(/\$Name\$/g, Name).replace(/\$name\$/g, name), 'utf8');
24
+ execSync(`git add ${name}.component.ts`);
25
+ execSync(`git add ${name}.template.ts`);
26
+ execSync(`git add ${name}.style.less`);
27
+ }
@@ -0,0 +1,3 @@
1
+ $name$ {
2
+ display: block;
3
+ }
@@ -0,0 +1,8 @@
1
+ import {ITemplate} from "@cmmn/ui";
2
+
3
+ export const template: ITemplate<IState, IEvents> = (html, state, events) => html`
4
+ `;
5
+
6
+ export type IState = {}
7
+
8
+ export type IEvents = {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cmmn/tools",
3
- "version": "1.1.0",
3
+ "version": "1.2.3",
4
4
  "description": "di, base extensions, useful functions",
5
5
  "main": "dist/rollup.config.js",
6
6
  "type": "module",
@@ -13,29 +13,35 @@
13
13
  },
14
14
  "files": [
15
15
  "bin.js",
16
- "bundle/*"
16
+ "gen/*",
17
+ "compile/*",
18
+ "bundle/*",
19
+ "plugins/*"
17
20
  ],
18
21
  "dependencies": {
19
- "less": "^4",
20
- "ttypescript": "1.5.13",
21
- "typescript": "4.4.3",
22
- "typescript-transform-paths": "^3.3.1"
23
- },
24
- "devDependencies": {
22
+ "@open-wc/rollup-plugin-html": "^1.2.5",
23
+ "@rollup/plugin-alias": "3",
25
24
  "@rollup/plugin-commonjs": "^21",
25
+ "@rollup/plugin-json": "4",
26
26
  "@rollup/plugin-node-resolve": "^13",
27
27
  "@rollup/plugin-typescript": "^8",
28
28
  "@web/rollup-plugin-html": "^1.10.1",
29
29
  "fast-glob": "^3.2.11",
30
+ "less": "^4",
30
31
  "rollup": "^2",
31
32
  "rollup-plugin-livereload": "^2.0.5",
33
+ "rollup-plugin-node-builtins": "^2.1.2",
34
+ "rollup-plugin-node-globals": "^1.4.0",
32
35
  "rollup-plugin-serve": "^1.1.0",
33
36
  "rollup-plugin-string": "^3.0.0",
34
37
  "rollup-plugin-styles": "^4",
35
38
  "rollup-plugin-terser": "^7",
36
- "rollup-plugin-visualizer": "^5.5.4"
39
+ "rollup-plugin-visualizer": "^5.5.4",
40
+ "ttypescript": "1.5.13",
41
+ "typescript": "4.4.3",
42
+ "typescript-transform-paths": "^3.3.1"
37
43
  },
38
44
  "author": "",
39
45
  "license": "ISC",
40
- "gitHead": "5309832cf3397001967465f0508d947cbab2540d"
46
+ "gitHead": "68d02f49f1ecba35975351e05ec1cb0519bf0ada"
41
47
  }
@@ -0,0 +1,90 @@
1
+ const ts = require("typescript");
2
+ const path = require("path");
3
+ const fs = require("fs");
4
+
5
+ function visitExportNode(exportNode, sourceFile) {
6
+ if (exportNode.typeOnly){
7
+ console.log('type olnly')
8
+ return ;
9
+ }
10
+ const file = exportNode.moduleSpecifier?.text ?? exportNode.test;
11
+ if (!file)
12
+ return;
13
+ const sourceFileDir = path.dirname(sourceFile.path);
14
+ const abs = path.resolve(sourceFileDir, file);
15
+ if (/\.(less|css|scss|sass|svg|png|html)$/.test(file)) {
16
+ return ts.updateExportDeclaration(exportNode, exportNode.decorators, exportNode.modifiers, exportNode.exportClause, ts.createStringLiteral(abs), exportNode.typeOnly);
17
+ }
18
+ if (fs.existsSync(abs + '.ts')) {
19
+ return ts.updateExportDeclaration(exportNode, exportNode.decorators, exportNode.modifiers, exportNode.exportClause, ts.createStringLiteral(file + '.js'), exportNode.typeOnly);
20
+ }
21
+ if (fs.existsSync(abs + '/')) {
22
+ const indexFile = './'+path.join(file, 'index.js');
23
+ console.log(sourceFileDir, file, indexFile);
24
+ return ts.updateExportDeclaration(exportNode, exportNode.decorators, exportNode.modifiers, exportNode.exportClause, ts.createStringLiteral(indexFile), exportNode.typeOnly);
25
+ }
26
+ }
27
+
28
+ function visitImportNode(importNode, sourceFile) {
29
+ const file = importNode.moduleSpecifier?.text;
30
+ if (!file)
31
+ return;
32
+ const sourceFileDir = path.dirname(sourceFile.path);
33
+ const abs = path.resolve(sourceFileDir, file);
34
+ if (/\.(less|css|scss|sass|svg|png|html)$/.test(file)) {
35
+ return ts.updateImportDeclaration(importNode, importNode.decorators, importNode.modifiers, importNode.importClause, ts.createStringLiteral(abs));
36
+ }
37
+ if (fs.existsSync(abs + '.ts')) {
38
+ return ts.updateImportDeclaration(importNode, importNode.decorators, importNode.modifiers, importNode.importClause, ts.createStringLiteral(file + '.js'));
39
+ }
40
+ if (fs.existsSync(abs + '/')) {
41
+ const indexFile = './' + path.join(file, 'index.js');
42
+ return ts.updateImportDeclaration(importNode, importNode.decorators, importNode.modifiers, importNode.importClause, ts.createStringLiteral(indexFile));
43
+ }
44
+ }
45
+
46
+ function visitRequireNode(importNode, sourceFile) {
47
+ if (!(importNode.expression.kind == ts.SyntaxKind.Identifier &&
48
+ importNode.expression.escapedText == "require")) {
49
+ return;
50
+ }
51
+ const file = importNode.arguments[0].text;
52
+ if (/\.(less|css|scss|sass|svg|png|html)/.test(file)) {
53
+ const sourceFileDir = path.dirname(sourceFile.path);
54
+ const real = path.join(sourceFileDir, file);
55
+ return ts.updateCall(importNode, importNode.expression, undefined, [ts.createStringLiteral(real)]);
56
+ }
57
+ }
58
+
59
+ const lessToStringTransformer = function (context) {
60
+ return (sourceFile) => {
61
+ function visitor(node) {
62
+ // if (node && node.kind == ts.SyntaxKind.ImportDeclaration) {
63
+ // return visitImportNode(node as ts.ImportDeclaration);
64
+ // }
65
+ if (!node)
66
+ return ts.visitEachChild(node, visitor, context);
67
+ if (ts.isCallExpression(node)) {
68
+ const result = visitRequireNode(node, sourceFile);
69
+ if (result)
70
+ return result;
71
+ }
72
+ if (ts.isImportDeclaration(node)) {
73
+ const result = visitImportNode(node, sourceFile);
74
+ if (result)
75
+ return result;
76
+ }
77
+ if (ts.isExportDeclaration(node)) {
78
+ const result = visitExportNode(node, sourceFile);
79
+ if (result)
80
+ return result;
81
+ }
82
+ return ts.visitEachChild(node, visitor, context);
83
+ }
84
+
85
+ return ts.visitEachChild(sourceFile, visitor, context);
86
+ };
87
+ };
88
+ exports.default = function (program, pluginOptions) {
89
+ return lessToStringTransformer;
90
+ }
package/readme.md ADDED
@@ -0,0 +1,11 @@
1
+ ## Builder and bundler for your projects
2
+
3
+ ### Use cases:
4
+ `cmmn compile [target] [-b] [--watch]`
5
+ > Runs typescript compiler
6
+
7
+ `cmmn bundle [target] [-b] [--watch] [--run] [--prod]`
8
+ > Runs rollup bundler
9
+
10
+ `cmmn gen name directory [-n]`
11
+ > Generates component with template at directory