innetjs 2.6.0-alpha.1 → 2.6.0-alpha.10

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/innet CHANGED
@@ -22,7 +22,7 @@ var glob = require('glob');
22
22
  var http = require('node:http');
23
23
  var https = require('node:https');
24
24
  var linesAndColumns = require('lines-and-columns');
25
- var path$1 = require('node:path');
25
+ var path = require('node:path');
26
26
  var prompt = require('prompts');
27
27
  var rollup = require('rollup');
28
28
  var external = require('rollup-plugin-external-node-modules');
@@ -34,10 +34,10 @@ var rollupPluginPreserveShebangs = require('rollup-plugin-preserve-shebangs');
34
34
  var env = require('rollup-plugin-process-env');
35
35
  var styles = require('rollup-plugin-styles');
36
36
  var rollupPluginTerser = require('rollup-plugin-terser');
37
+ var stream = require('node:stream');
37
38
  var tmp = require('tmp');
38
- var typescript = require('typescript');
39
- var node_util = require('node:util');
40
39
  var unzipper = require('unzipper');
40
+ var node_util = require('node:util');
41
41
 
42
42
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
43
43
 
@@ -58,7 +58,7 @@ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
58
58
  var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
59
59
  var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
60
60
  var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
61
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
61
+ var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
62
62
  var prompt__default = /*#__PURE__*/_interopDefaultLegacy(prompt);
63
63
  var rollup__default = /*#__PURE__*/_interopDefaultLegacy(rollup);
64
64
  var external__default = /*#__PURE__*/_interopDefaultLegacy(external);
@@ -68,755 +68,713 @@ var externals__default = /*#__PURE__*/_interopDefaultLegacy(externals);
68
68
  var polyfill__default = /*#__PURE__*/_interopDefaultLegacy(polyfill);
69
69
  var env__default = /*#__PURE__*/_interopDefaultLegacy(env);
70
70
  var styles__default = /*#__PURE__*/_interopDefaultLegacy(styles);
71
+ var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream);
71
72
  var tmp__default = /*#__PURE__*/_interopDefaultLegacy(tmp);
72
- var typescript__default = /*#__PURE__*/_interopDefaultLegacy(typescript);
73
73
 
74
- const lintInclude = [
75
- '**/*.ts',
76
- '**/*.tsx',
77
- '**/*.js',
78
- '**/*.jsx',
79
- '**/*.mjs',
80
- ];
81
- const imageInclude = [
82
- '**/*.gif',
83
- '**/*.png',
84
- '**/*.jpeg',
85
- '**/*.jpg',
86
- '**/*.svg',
87
- '**/*.webp',
88
- ];
89
- const stringExcludeDom = [
90
- ...lintInclude,
91
- '**/*.json',
92
- '**/*.css',
93
- '**/*.scss',
94
- '**/*.webp',
95
- ...imageInclude,
96
- ];
97
- const stringExcludeNode = [
98
- ...lintInclude,
99
- '**/*.json',
74
+ const lintInclude = [
75
+ '**/*.ts',
76
+ '**/*.tsx',
77
+ '**/*.js',
78
+ '**/*.jsx',
79
+ '**/*.mjs',
80
+ ];
81
+ const imageInclude = [
82
+ '**/*.gif',
83
+ '**/*.png',
84
+ '**/*.jpeg',
85
+ '**/*.jpg',
86
+ '**/*.svg',
87
+ '**/*.webp',
88
+ ];
89
+ const stringExcludeDom = [
90
+ ...lintInclude,
91
+ '**/*.json',
92
+ '**/*.css',
93
+ '**/*.scss',
94
+ '**/*.webp',
95
+ ...imageInclude,
96
+ ];
97
+ const stringExcludeNode = [
98
+ ...lintInclude,
99
+ '**/*.json',
100
100
  ];
101
101
 
102
- const Writer = require('fstream').Writer;
103
- const path = require('path');
104
- const stream = require('stream');
105
- const duplexer2 = require('duplexer2');
106
- const Promise$1 = require('bluebird');
107
- function Extract(opts, template) {
108
- const reduceCount = 19 + template.length;
109
- // make sure path is normalized before using it
110
- opts.path = path.resolve(path.normalize(opts.path));
111
- // @ts-expect-error
112
- const parser = new unzipper.Parse(opts);
113
- const outStream = new stream.Writable({ objectMode: true });
114
- outStream._write = function (entry, encoding, cb) {
115
- if (entry.type === 'Directory')
116
- return cb();
117
- const extractPath = path.join(opts.path, entry.path.slice(reduceCount));
118
- if (extractPath.indexOf(opts.path) !== 0) {
119
- return cb();
120
- }
121
- const writer = opts.getWriter ? opts.getWriter({ path: extractPath }) : Writer({ path: extractPath });
122
- entry.pipe(writer)
123
- .on('error', cb)
124
- .on('close', cb);
125
- };
126
- const extract = duplexer2(parser, outStream);
127
- parser.once('crx-header', function (crxHeader) {
128
- extract.crxHeader = crxHeader;
129
- });
130
- parser
131
- .pipe(outStream)
132
- .on('finish', function () {
133
- extract.emit('close');
134
- });
135
- extract.promise = function () {
136
- return new Promise$1(function (resolve, reject) {
137
- extract.on('close', resolve);
138
- extract.on('error', reject);
139
- });
140
- };
141
- return extract;
102
+ function getFile(file) {
103
+ file = path__default["default"].resolve(file);
104
+ if (!fs__default["default"].existsSync(file)) {
105
+ throw Error('Cannot find the file: ' + file);
106
+ }
107
+ if (fs__default["default"].lstatSync(file).isDirectory()) {
108
+ let tmpFile = file;
109
+ if (!fs__default["default"].existsSync(tmpFile = path__default["default"].join(file, 'index.ts')) &&
110
+ !fs__default["default"].existsSync(tmpFile = path__default["default"].join(file, 'index.tsx')) &&
111
+ !fs__default["default"].existsSync(tmpFile = path__default["default"].join(file, 'index.js'))) {
112
+ throw Error('Cannot find index file in: ' + file);
113
+ }
114
+ file = tmpFile;
115
+ }
116
+ else if (!file.endsWith('.ts') && !file.endsWith('.tsx') && !file.endsWith('.js')) {
117
+ throw Error('File should has `.ts` or `.tsx` or `.js` extension: ' + file);
118
+ }
119
+ if (!fs__default["default"].existsSync(file)) {
120
+ throw Error('Cannot find the file: ' + file);
121
+ }
122
+ return file;
142
123
  }
143
-
144
- function getFile(file) {
145
- file = path__default["default"].resolve(file);
146
- if (!fs__default["default"].existsSync(file)) {
147
- throw Error('Cannot find the file: ' + file);
148
- }
149
- if (fs__default["default"].lstatSync(file).isDirectory()) {
150
- let tmpFile = file;
151
- if (!fs__default["default"].existsSync(tmpFile = path__default["default"].join(file, 'index.ts')) &&
152
- !fs__default["default"].existsSync(tmpFile = path__default["default"].join(file, 'index.tsx')) &&
153
- !fs__default["default"].existsSync(tmpFile = path__default["default"].join(file, 'index.js'))) {
154
- throw Error('Cannot find index file in: ' + file);
155
- }
156
- file = tmpFile;
157
- }
158
- else if (!file.endsWith('.ts') && !file.endsWith('.tsx') && !file.endsWith('.js')) {
159
- throw Error('File should has `.ts` or `.tsx` or `.js` extension: ' + file);
160
- }
161
- if (!fs__default["default"].existsSync(file)) {
162
- throw Error('Cannot find the file: ' + file);
163
- }
164
- return file;
165
- }
166
- function convertIndexFile(data, version, baseUrl, index, inject) {
167
- return tslib.__awaiter(this, void 0, void 0, function* () {
168
- const { env } = process;
169
- const indexString = data
170
- .toString()
171
- .replace(/%([A-Z0-9_]+)%/g, (placeholder, placeholderId) => { var _a; return (_a = env[placeholderId]) !== null && _a !== void 0 ? _a : placeholder; });
172
- return inject
173
- ? indexString
174
- .replace('</head>', `<script type="module" defer src="${baseUrl}${index}.js${version ? `?v=${version}` : ''}"></script></head>`)
175
- : indexString;
176
- });
177
- }
178
- const reporter = (options, outputOptions, info) => {
179
- logger__default["default"].log(`${chalk__default["default"].yellow(info.fileName)} ${chalk__default["default"].green(info.bundleSize)} [ gzip: ${chalk__default["default"].green(info.gzipSize)} ]`);
180
- return '';
124
+ function convertIndexFile(data, version, baseUrl, index, inject) {
125
+ return tslib.__awaiter(this, void 0, void 0, function* () {
126
+ const { env } = process;
127
+ const indexString = data
128
+ .toString()
129
+ .replace(/%([A-Z0-9_]+)%/g, (placeholder, placeholderId) => { var _a; return (_a = env[placeholderId]) !== null && _a !== void 0 ? _a : placeholder; });
130
+ return inject
131
+ ? indexString
132
+ .replace('</head>', `<script type="module" defer src="${baseUrl}${index}.js${version ? `?v=${version}` : ''}"></script></head>`)
133
+ : indexString;
134
+ });
135
+ }
136
+ const reporter = (options, outputOptions, info) => {
137
+ logger__default["default"].log(`${chalk__default["default"].yellow(info.fileName)} ${chalk__default["default"].green(info.bundleSize)} [ gzip: ${chalk__default["default"].green(info.gzipSize)} ]`);
138
+ return '';
181
139
  };
182
140
 
183
- function updateDotenv() {
184
- const { __INNETJS__PACKAGE_VERSION: before } = process.env;
185
- delete process.env.__INNETJS__PACKAGE_VERSION;
186
- require('dotenv-expand').expand(require('dotenv').config());
187
- if (!('__INNETJS__PACKAGE_VERSION' in process.env)) {
188
- process.env.__INNETJS__PACKAGE_VERSION = before;
189
- }
141
+ function updateDotenv() {
142
+ const { __INNETJS__PACKAGE_VERSION: before } = process.env;
143
+ delete process.env.__INNETJS__PACKAGE_VERSION;
144
+ require('dotenv-expand').expand(require('dotenv').config());
145
+ if (!('__INNETJS__PACKAGE_VERSION' in process.env)) {
146
+ process.env.__INNETJS__PACKAGE_VERSION = before;
147
+ }
190
148
  }
191
149
 
192
- const livereload = require('rollup-plugin-livereload');
193
- const { string } = require('rollup-plugin-string');
194
- const { exec, spawn } = require('child_process');
195
- const readline = require('readline');
196
- const importAssets = require('rollup-plugin-import-assets');
197
- const execAsync = node_util.promisify(exec);
198
- const copyFiles = node_util.promisify(fs__default["default"].copy);
199
- updateDotenv();
200
- const REG_CLEAR_TEXT = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
201
- const REG_RPT_ERROR_FILE = /(src[^:]+):(\d+):(\d+)/;
202
- const REG_TJSX = /\.[tj]sx?$/;
203
- const REG_EXT = /\.([^.]+)$/;
204
- const scriptExtensions = ['ts', 'js', 'tsx', 'jsx'];
205
- const indexExt = scriptExtensions.join(',');
206
- class InnetJS {
207
- constructor({ envPrefix = process.env.INNETJS_ENV_PREFIX || 'INNETJS_', projectFolder = process.env.PROJECT_FOLDER || '', baseUrl = process.env.BASE_URL || '', publicFolder = process.env.PUBLIC_FOLDER || 'public', releaseFolder = process.env.RELEASE_FOLDER || 'release', buildFolder = process.env.BUILD_FOLDER || 'build', srcFolder = process.env.SRC_FOLDER || 'src', sourcemap = process.env.SOURCEMAP ? process.env.SOURCEMAP === 'true' : false, cssModules = process.env.CSS_MODULES ? process.env.CSS_MODULES === 'true' : true, cssInJs = process.env.CSS_IN_JS ? process.env.CSS_IN_JS === 'true' : true, sslKey = process.env.SSL_KEY || 'localhost.key', sslCrt = process.env.SSL_CRT || 'localhost.crt', proxy = process.env.PROXY || '', simulateIP = process.env.IP, port = process.env.PORT ? +process.env.PORT : 3000, api = process.env.API || '/api/?*', } = {}) {
208
- this.projectFolder = path__default["default"].resolve(projectFolder);
209
- this.publicFolder = path__default["default"].resolve(publicFolder);
210
- this.releaseFolder = path__default["default"].resolve(releaseFolder);
211
- this.buildFolder = path__default["default"].resolve(buildFolder);
212
- this.srcFolder = path__default["default"].resolve(srcFolder);
213
- this.licenseFile = path__default["default"].join(projectFolder, 'LICENSE');
214
- this.licenseReleaseFile = path__default["default"].join(releaseFolder, 'LICENSE');
215
- this.readmeFile = path__default["default"].join(projectFolder, 'README.md');
216
- this.readmeReleaseFile = path__default["default"].join(releaseFolder, 'README.md');
217
- this.declarationFile = path__default["default"].join(srcFolder, 'declaration.d.ts');
218
- this.declarationReleaseFile = path__default["default"].join(releaseFolder, 'declaration.d.ts');
219
- this.publicIndexFile = path__default["default"].join(publicFolder, 'index.html');
220
- this.buildIndexFile = path__default["default"].join(buildFolder, 'index.html');
221
- this.devBuildFolder = path__default["default"].resolve(projectFolder, 'node_modules', '.cache', 'innetjs', 'build');
222
- this.devBuildIndexFile = path__default["default"].join(this.devBuildFolder, 'index.html');
223
- this.sourcemap = sourcemap;
224
- this.cssModules = cssModules;
225
- this.cssInJs = cssInJs;
226
- this.sslKey = sslKey;
227
- this.sslCrt = sslCrt;
228
- this.port = port;
229
- this.proxy = proxy;
230
- this.api = api;
231
- this.baseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
232
- this.envPrefix = envPrefix;
233
- this.simulateIP = simulateIP;
234
- }
235
- // Methods
236
- init(appName, { template, force = false } = {}) {
237
- return tslib.__awaiter(this, void 0, void 0, function* () {
238
- const appPath = path__default["default"].resolve(appName);
239
- const { data } = yield logger__default["default"].start('Get templates list', () => tslib.__awaiter(this, void 0, void 0, function* () { return yield axios__default["default"].get('https://api.github.com/repos/d8corp/innetjs-templates/branches'); }));
240
- const templates = data.map(({ name }) => name).filter(name => name !== 'main');
241
- if (!template || !templates.includes(template)) {
242
- logger__default["default"].log(chalk__default["default"].green('Select one of those templates'));
243
- const { value } = yield selector__default["default"]({
244
- values: templates,
245
- });
246
- template = value;
247
- readline.moveCursor(process.stdout, 0, -1);
248
- const text = `Selected template: ${chalk__default["default"].white(value)}`;
249
- logger__default["default"].start(text);
250
- logger__default["default"].end(text);
251
- }
252
- if (!force) {
253
- yield logger__default["default"].start('Check if app folder is available', () => tslib.__awaiter(this, void 0, void 0, function* () {
254
- if (fs__default["default"].existsSync(appPath)) {
255
- logger__default["default"].log(chalk__default["default"].red(`'${appPath}' already exist, what do you want?`));
256
- const { id: result, value } = yield selector__default["default"]({
257
- values: ['Stop the process', 'Remove the folder', 'Merge with template'],
258
- });
259
- readline.moveCursor(process.stdout, 0, -1);
260
- logger__default["default"].log(`Already exist, selected: ${value}`);
261
- if (!result) {
262
- throw Error(`'${appPath}' already exist`);
263
- }
264
- if (result === 1) {
265
- yield fs__default["default"].remove(appPath);
266
- }
267
- }
268
- }));
269
- }
270
- yield logger__default["default"].start('Download template', () => tslib.__awaiter(this, void 0, void 0, function* () {
271
- const { data } = yield axios__default["default"].get(`https://github.com/d8corp/innetjs-templates/archive/refs/heads/${template}.zip`, {
272
- responseType: 'stream',
273
- });
274
- yield new Promise((resolve, reject) => {
275
- data.pipe(Extract({
276
- path: appPath,
277
- }, template)).on('finish', resolve).on('error', reject);
278
- });
279
- }));
280
- yield logger__default["default"].start('Install packages', () => execAsync(`cd ${appPath} && npm i`));
281
- });
282
- }
283
- build({ node = false, inject = false, index = 'index' } = {}) {
284
- return tslib.__awaiter(this, void 0, void 0, function* () {
285
- const input = glob__default["default"].sync(`src/${index}.{${indexExt}}`);
286
- if (!input.length) {
287
- throw Error('index file is not detected');
288
- }
289
- yield logger__default["default"].start('Remove build', () => fs__default["default"].remove(this.buildFolder));
290
- const pkg = node && (yield this.getPackage());
291
- const options = {
292
- input,
293
- preserveEntrySignatures: 'strict',
294
- plugins: [
295
- commonjs__default["default"](),
296
- json__default["default"](),
297
- ts__default["default"]({
298
- typescript: typescript__default["default"],
299
- noEmitOnError: true,
300
- compilerOptions: {
301
- declaration: false,
302
- },
303
- }),
304
- jsx__default["default"](),
305
- ],
306
- onwarn(warning, warn) {
307
- if (warning.code === 'THIS_IS_UNDEFINED' || warning.code === 'SOURCEMAP_ERROR')
308
- return;
309
- warn(warning);
310
- },
311
- };
312
- this.withLint(options, true);
313
- const outputOptions = {
314
- dir: this.buildFolder,
315
- sourcemap: this.sourcemap,
316
- };
317
- if (node) {
318
- outputOptions.format = 'cjs';
319
- options.external = Object.keys((pkg === null || pkg === void 0 ? void 0 : pkg.dependencies) || {});
320
- options.plugins.push(pluginNodeResolve.nodeResolve(), string({
321
- include: '**/*.*',
322
- exclude: stringExcludeNode,
323
- }));
324
- }
325
- else {
326
- options.plugins.push(pluginNodeResolve.nodeResolve({
327
- browser: true,
328
- }), polyfill__default["default"](), importAssets({
329
- include: imageInclude.map(img => `src/${img}`),
330
- publicPath: this.baseUrl,
331
- }), styles__default["default"]({
332
- mode: this.cssInJs ? 'inject' : 'extract',
333
- url: {
334
- inline: false,
335
- publicPath: `${this.baseUrl}assets`,
336
- },
337
- plugins: [autoprefixer__default["default"]()],
338
- autoModules: this.cssModules ? (id) => !id.includes('.global.') : true,
339
- sourceMap: this.sourcemap,
340
- minimize: true,
341
- }), string({
342
- include: '**/*.*',
343
- exclude: stringExcludeDom,
344
- }));
345
- outputOptions.format = 'es';
346
- outputOptions.plugins = [
347
- rollupPluginTerser.terser(),
348
- filesize__default["default"]({
349
- reporter,
350
- }),
351
- ];
352
- }
353
- this.withEnv(options, true);
354
- yield logger__default["default"].start('Build production bundle', () => tslib.__awaiter(this, void 0, void 0, function* () {
355
- const bundle = yield rollup__default["default"].rollup(options);
356
- yield bundle.write(outputOptions);
357
- yield bundle.close();
358
- if (!node) {
359
- yield copyFiles(this.publicFolder, this.buildFolder);
360
- const data = yield fs.promises.readFile(this.publicIndexFile);
361
- const pkg = yield this.getPackage();
362
- yield fs.promises.writeFile(this.buildIndexFile, yield convertIndexFile(data, pkg.version, this.baseUrl, path__default["default"].parse(input[0]).name, inject));
363
- }
364
- }));
365
- if (pkg) {
366
- yield logger__default["default"].start('Copy package.json', () => tslib.__awaiter(this, void 0, void 0, function* () {
367
- const data = Object.assign({}, pkg);
368
- delete data.private;
369
- delete data.devDependencies;
370
- yield fs__default["default"].writeFile(path__default["default"].resolve(this.buildFolder, 'package.json'), JSON.stringify(data, undefined, 2), 'UTF-8');
371
- }));
372
- const pkgLockPath = path__default["default"].resolve(this.projectFolder, 'package-lock.json');
373
- if (fs__default["default"].existsSync(pkgLockPath)) {
374
- yield logger__default["default"].start('Copy package-lock.json', () => {
375
- return fs__default["default"].copy(pkgLockPath, path__default["default"].resolve(this.buildFolder, 'package-lock.json'));
376
- });
377
- }
378
- }
379
- });
380
- }
381
- start({ node = false, inject = false, error = false, index = 'index' } = {}) {
382
- return tslib.__awaiter(this, void 0, void 0, function* () {
383
- const pkg = yield this.getPackage();
384
- const input = glob__default["default"].sync(`src/${index}.{${indexExt}}`);
385
- if (!input.length) {
386
- throw Error('index file is not detected');
387
- }
388
- yield logger__default["default"].start('Remove build', () => fs__default["default"].remove(this.devBuildFolder));
389
- const options = {
390
- input,
391
- preserveEntrySignatures: 'strict',
392
- output: {
393
- dir: this.devBuildFolder,
394
- sourcemap: true,
395
- },
396
- plugins: [
397
- commonjs__default["default"](),
398
- json__default["default"](),
399
- ts__default["default"]({
400
- typescript: typescript__default["default"],
401
- compilerOptions: {
402
- declaration: false,
403
- sourceMap: true,
404
- },
405
- }),
406
- jsx__default["default"](),
407
- ],
408
- onwarn(warning, warn) {
409
- if (warning.code === 'THIS_IS_UNDEFINED' || warning.code === 'SOURCEMAP_ERROR')
410
- return;
411
- if (warning.plugin === 'typescript') {
412
- const { loc: { line, column, file }, frame, message } = warning;
413
- console.log(`ERROR in ${file}:${line}:${column}`);
414
- console.log(message);
415
- console.log(frame);
416
- return;
417
- }
418
- warn(warning);
419
- },
420
- };
421
- this.withLint(options);
422
- if (node) {
423
- // @ts-expect-error
424
- options.output.format = 'cjs';
425
- options.external = Object.keys((pkg === null || pkg === void 0 ? void 0 : pkg.dependencies) || {});
426
- options.plugins.push(pluginNodeResolve.nodeResolve(), string({
427
- include: '**/*.*',
428
- exclude: stringExcludeNode,
429
- }), this.createServer());
430
- }
431
- else {
432
- const key = path__default["default"].basename(this.sslKey) !== this.sslKey
433
- ? this.sslKey
434
- : fs__default["default"].existsSync(this.sslKey)
435
- ? fs__default["default"].readFileSync(this.sslKey)
436
- : undefined;
437
- const cert = path__default["default"].basename(this.sslCrt) !== this.sslCrt
438
- ? this.sslCrt
439
- : fs__default["default"].existsSync(this.sslCrt)
440
- ? fs__default["default"].readFileSync(this.sslCrt)
441
- : undefined;
442
- // @ts-expect-error
443
- options.output.format = 'es';
444
- options.plugins.push(pluginNodeResolve.nodeResolve({
445
- browser: true,
446
- }), polyfill__default["default"](), importAssets({
447
- include: imageInclude.map(img => `src/${img}`),
448
- publicPath: this.baseUrl,
449
- }), styles__default["default"]({
450
- mode: this.cssInJs ? 'inject' : 'extract',
451
- url: {
452
- inline: false,
453
- publicPath: `${this.baseUrl}assets`,
454
- },
455
- plugins: [autoprefixer__default["default"]()],
456
- autoModules: this.cssModules ? (id) => !id.includes('.global.') : true,
457
- sourceMap: true,
458
- }), string({
459
- include: '**/*.*',
460
- exclude: stringExcludeDom,
461
- }), this.createClient(key, cert, pkg, path__default["default"].parse(input[0]).name, inject), livereload(Object.assign({ exts: ['html', 'css', 'js', 'png', 'svg', 'webp', 'gif', 'jpg', 'json'], watch: [this.devBuildFolder, this.publicFolder], verbose: false }, (key && cert ? { https: { key, cert } } : {}))));
462
- }
463
- this.withEnv(options, true);
464
- const watcher = rollup__default["default"].watch(options);
465
- watcher.on('event', (e) => tslib.__awaiter(this, void 0, void 0, function* () {
466
- if (e.code === 'ERROR') {
467
- if (e.error.code === 'UNRESOLVED_IMPORT') {
468
- const [, importer, file] = e.error.message.match(/^Could not resolve '(.+)' from (.+)$/) || [];
469
- const text = (yield fs__default["default"].readFile(file)).toString();
470
- const lines = new linesAndColumns.LinesAndColumns(text);
471
- const { line, column } = lines.locationForIndex(text.indexOf(importer));
472
- logger__default["default"].end('Bundling', e.error.message);
473
- console.log(`ERROR in ${file}:${line + 1}:${column + 1}`);
474
- }
475
- else if (e.error.code === 'PLUGIN_ERROR' && ['rpt2', 'commonjs', 'typescript'].includes(e.error.plugin)) {
476
- const [, file, line, column] = e.error.message
477
- .replace(REG_CLEAR_TEXT, '')
478
- .match(REG_RPT_ERROR_FILE) || [];
479
- logger__default["default"].end('Bundling', e.error.message);
480
- if (file) {
481
- console.log(`ERROR in ${file}:${line}:${column}`);
482
- }
483
- else if (e.error.loc) {
484
- console.log(`ERROR in ${e.error.loc.file}:${e.error.loc.line}:${e.error.loc.column}`);
485
- console.log(e.error.frame);
486
- }
487
- }
488
- else {
489
- logger__default["default"].end('Bundling', error ? e.error.stack : e.error.message);
490
- }
491
- }
492
- else if (e.code === 'BUNDLE_START') {
493
- logger__default["default"].start('Bundling');
494
- }
495
- else if (e.code === 'BUNDLE_END') {
496
- logger__default["default"].end('Bundling');
497
- }
498
- }));
499
- });
500
- }
501
- run(file) {
502
- return tslib.__awaiter(this, void 0, void 0, function* () {
503
- const input = yield logger__default["default"].start('Check file', () => getFile(file));
504
- const folder = yield new Promise((resolve, reject) => {
505
- tmp__default["default"].dir((err, folder) => {
506
- if (err) {
507
- reject(err);
508
- }
509
- else {
510
- resolve(folder);
511
- }
512
- });
513
- });
514
- const jsFilePath = `${folder}/index.js`;
515
- yield logger__default["default"].start('Build bundle', () => tslib.__awaiter(this, void 0, void 0, function* () {
516
- const inputOptions = {
517
- input,
518
- plugins: [
519
- commonjs__default["default"](),
520
- pluginNodeResolve.nodeResolve(),
521
- json__default["default"](),
522
- ts__default["default"]({
523
- typescript: typescript__default["default"],
524
- tsconfigOverride: {
525
- compilerOptions: {
526
- sourceMap: true,
527
- },
528
- },
529
- }),
530
- ],
531
- };
532
- const outputOptions = {
533
- format: 'cjs',
534
- file: jsFilePath,
535
- sourcemap: true,
536
- };
537
- const bundle = yield rollup__default["default"].rollup(inputOptions);
538
- yield bundle.write(outputOptions);
539
- yield bundle.close();
540
- }));
541
- yield logger__default["default"].start('Running of the script', () => tslib.__awaiter(this, void 0, void 0, function* () {
542
- spawn('node', ['-r', 'source-map-support/register', jsFilePath], { stdio: 'inherit' });
543
- }));
544
- });
545
- }
546
- release({ index = 'index', pub } = {}) {
547
- return tslib.__awaiter(this, void 0, void 0, function* () {
548
- const { releaseFolder, cssModules } = this;
549
- yield logger__default["default"].start('Remove previous release', () => fs__default["default"].remove(releaseFolder));
550
- const pkg = yield this.getPackage();
551
- const build = (format) => tslib.__awaiter(this, void 0, void 0, function* () {
552
- var _a, _b;
553
- const ext = format === 'es'
554
- ? ((_a = (pkg.module || pkg.esnext || pkg['jsnext:main'])) === null || _a === void 0 ? void 0 : _a.replace('index', '')) || '.mjs'
555
- : ((_b = pkg.main) === null || _b === void 0 ? void 0 : _b.replace('index', '')) || '.js';
556
- const input = glob__default["default"].sync(`src/${index}.{${indexExt}}`);
557
- if (!input.length) {
558
- throw Error('index file is not detected');
559
- }
560
- const options = {
561
- input,
562
- external: ['tslib'],
563
- treeshake: false,
564
- output: {
565
- dir: releaseFolder,
566
- entryFileNames: ({ name, facadeModuleId }) => {
567
- if (REG_TJSX.test(facadeModuleId)) {
568
- return `${name}${ext}`;
569
- }
570
- const match = facadeModuleId.match(REG_EXT);
571
- return match ? `${name}${match[0]}${ext}` : `${name}${ext}`;
572
- },
573
- format,
574
- preserveModules: true,
575
- exports: 'named',
576
- },
577
- plugins: [
578
- json__default["default"](),
579
- ts__default["default"]({
580
- typescript: typescript__default["default"],
581
- clean: true,
582
- tsconfigOverride: {
583
- compilerOptions: {
584
- sourceMap: false,
585
- },
586
- include: [...input, 'src/declaration.d.ts'],
587
- },
588
- }),
589
- jsx__default["default"](),
590
- externals__default["default"](),
591
- string({
592
- include: '**/*.*',
593
- exclude: stringExcludeDom,
594
- }),
595
- image__default["default"](),
596
- styles__default["default"]({
597
- mode: this.cssInJs ? 'inject' : 'extract',
598
- plugins: [autoprefixer__default["default"]()],
599
- autoModules: cssModules ? (id) => !id.includes('.global.') : true,
600
- minimize: true,
601
- }),
602
- pluginNodeResolve.nodeResolve(),
603
- external__default["default"](),
604
- ],
605
- };
606
- this.withLint(options);
607
- this.withEnv(options, true);
608
- const bundle = yield rollup__default["default"].rollup(options);
609
- yield bundle.write(options.output);
610
- yield bundle.close();
611
- });
612
- yield logger__default["default"].start('Build cjs bundle', () => tslib.__awaiter(this, void 0, void 0, function* () {
613
- yield build('cjs');
614
- }));
615
- yield logger__default["default"].start('Build es6 bundle', () => tslib.__awaiter(this, void 0, void 0, function* () {
616
- yield build('es');
617
- }));
618
- yield logger__default["default"].start('Copy package.json', () => tslib.__awaiter(this, void 0, void 0, function* () {
619
- const data = Object.assign({}, pkg);
620
- delete data.private;
621
- delete data.devDependencies;
622
- yield fs__default["default"].writeFile(path__default["default"].resolve(this.releaseFolder, 'package.json'), JSON.stringify(data, undefined, 2), 'UTF-8');
623
- }));
624
- if (pkg.bin) {
625
- yield logger__default["default"].start('Build bin', () => tslib.__awaiter(this, void 0, void 0, function* () {
626
- const { bin } = pkg;
627
- for (const name in bin) {
628
- const value = bin[name];
629
- const input = glob__default["default"].sync(`src/${value}.{${indexExt}}`);
630
- const file = path__default["default"].join(this.releaseFolder, value);
631
- const options = {
632
- input,
633
- external: [...Object.keys(pkg.dependencies), 'tslib'],
634
- output: {
635
- file,
636
- format: 'cjs',
637
- },
638
- plugins: [
639
- rollupPluginPreserveShebangs.preserveShebangs(),
640
- json__default["default"](),
641
- ts__default["default"]({
642
- typescript: typescript__default["default"],
643
- clean: true,
644
- tsconfigOverride: {
645
- compilerOptions: {
646
- declaration: false,
647
- },
648
- },
649
- }),
650
- externals__default["default"](),
651
- jsx__default["default"](),
652
- ],
653
- };
654
- this.withLint(options);
655
- this.withEnv(options);
656
- const bundle = yield rollup__default["default"].rollup(options);
657
- yield bundle.write(options.output);
658
- yield bundle.close();
659
- }
660
- }));
661
- }
662
- if (fs__default["default"].existsSync(this.licenseFile)) {
663
- yield logger__default["default"].start('Copy license', () => tslib.__awaiter(this, void 0, void 0, function* () {
664
- yield fs.promises.copyFile(this.licenseFile, this.licenseReleaseFile);
665
- }));
666
- }
667
- if (fs__default["default"].existsSync(this.readmeFile)) {
668
- yield logger__default["default"].start('Copy readme', () => tslib.__awaiter(this, void 0, void 0, function* () {
669
- yield fs.promises.copyFile(this.readmeFile, this.readmeReleaseFile);
670
- }));
671
- }
672
- if (fs__default["default"].existsSync(this.declarationFile)) {
673
- yield logger__default["default"].start('Copy declaration', () => tslib.__awaiter(this, void 0, void 0, function* () {
674
- yield fs.promises.copyFile(this.declarationFile, this.declarationReleaseFile);
675
- }));
676
- }
677
- if (pub) {
678
- const date = (Date.now() / 1000) | 0;
679
- yield logger__default["default"].start(`publishing v${pkg.version} ${date}`, () => tslib.__awaiter(this, void 0, void 0, function* () {
680
- yield execAsync(`npm publish ${this.releaseFolder}`);
681
- }));
682
- }
683
- });
684
- }
685
- withLint(options, prod = false) {
686
- if (this._lintUsage === undefined) {
687
- this._lintUsage = fs__default["default"].existsSync(path__default["default"].join(this.projectFolder, '.eslintrc'));
688
- }
689
- if (this._lintUsage) {
690
- options.plugins.push(eslint__default["default"]({
691
- include: lintInclude,
692
- throwOnError: prod,
693
- }));
694
- }
695
- }
696
- withEnv(options, virtual) {
697
- options.plugins.push(env__default["default"](this.envPrefix, {
698
- include: options.input,
699
- virtual,
700
- }));
701
- }
702
- increaseVersion(release) {
703
- return tslib.__awaiter(this, void 0, void 0, function* () {
704
- const pkg = yield this.getPackage();
705
- yield logger__default["default"].start('Prepare package.json', () => tslib.__awaiter(this, void 0, void 0, function* () {
706
- const version = pkg.version.split('.');
707
- switch (release) {
708
- case 'patch': {
709
- version[2]++;
710
- break;
711
- }
712
- case 'minor': {
713
- version[1]++;
714
- version[2] = 0;
715
- break;
716
- }
717
- case 'major': {
718
- version[1] = 0;
719
- version[2] = 0;
720
- version[0]++;
721
- break;
722
- }
723
- default: return;
724
- }
725
- pkg.version = version.join('.');
726
- yield fs__default["default"].writeFile(path__default["default"].resolve(this.projectFolder, 'package.json'), JSON.stringify(pkg, undefined, 2), 'UTF-8');
727
- }));
728
- });
729
- }
730
- getPackage() {
731
- return tslib.__awaiter(this, void 0, void 0, function* () {
732
- if (this.package) {
733
- return this.package;
734
- }
735
- const packageFolder = path__default["default"].resolve(this.projectFolder, 'package.json');
736
- yield logger__default["default"].start('Check package.json', () => tslib.__awaiter(this, void 0, void 0, function* () {
737
- if (fs__default["default"].existsSync(packageFolder)) {
738
- this.package = yield fs__default["default"].readJson(packageFolder);
739
- }
740
- }));
741
- return this.package;
742
- });
743
- }
744
- createClient(key, cert, pkg, index, inject) {
745
- let app;
746
- return {
747
- name: 'client',
748
- writeBundle: () => tslib.__awaiter(this, void 0, void 0, function* () {
749
- var _a;
750
- if (!app) {
751
- app = express__default["default"]();
752
- const update = () => tslib.__awaiter(this, void 0, void 0, function* () {
753
- const data = yield fs.promises.readFile(this.publicIndexFile);
754
- yield fs.promises.writeFile(this.devBuildIndexFile, yield convertIndexFile(data, pkg.version, this.baseUrl, index, inject));
755
- });
756
- fs__default["default"].watch(this.publicIndexFile, update);
757
- yield update();
758
- const httpsUsing = !!(cert && key);
759
- app.use(this.baseUrl, express__default["default"].static(this.devBuildFolder));
760
- app.use(this.baseUrl, express__default["default"].static(this.publicFolder));
761
- if ((_a = this.proxy) === null || _a === void 0 ? void 0 : _a.startsWith('http')) {
762
- if (this.simulateIP) {
763
- app.use((req, res, next) => {
764
- req.headers['X-Real-IP'] = this.simulateIP;
765
- next();
766
- });
767
- }
768
- app.use(this.api, proxy__default["default"](this.proxy, {
769
- https: httpsUsing,
770
- limit: '1000mb',
771
- proxyReqPathResolver: req => req.originalUrl,
772
- }));
773
- }
774
- app.use(/^([^.]*|.*\.[^.]{5,})$/, (req, res) => {
775
- res.sendFile(this.devBuildFolder + '/index.html');
776
- });
777
- const server = httpsUsing ? https__default["default"].createServer({ key, cert }, app) : http__default["default"].createServer(app);
778
- let port = this.port;
779
- const listener = () => {
780
- const baseUrl = this.baseUrl === '/' ? '' : this.baseUrl;
781
- console.log(`${chalk__default["default"].green('➤')} Started on http${httpsUsing ? 's' : ''}://localhost:${port}${baseUrl} and http${httpsUsing ? 's' : ''}://${address__default["default"].ip()}:${port}${baseUrl}`);
782
- };
783
- server.listen(port, listener);
784
- server.on('error', (e) => tslib.__awaiter(this, void 0, void 0, function* () {
785
- if (e.code === 'EADDRINUSE') {
786
- port++;
787
- const { userPort } = yield prompt__default["default"]({
788
- name: 'userPort',
789
- type: 'number',
790
- message: `Port ${e.port} is reserved, please enter another one [${port}]:`,
791
- });
792
- if (userPort) {
793
- port = userPort;
794
- }
795
- server.listen(port);
796
- }
797
- else {
798
- throw e;
799
- }
800
- }));
801
- }
802
- }),
803
- };
804
- }
805
- createServer() {
806
- let app;
807
- return {
808
- name: 'server',
809
- writeBundle: () => tslib.__awaiter(this, void 0, void 0, function* () {
810
- app === null || app === void 0 ? void 0 : app.kill();
811
- const filePath = path__default["default"].resolve(this.devBuildFolder, 'index.js');
812
- app = spawn('node', ['-r', 'source-map-support/register', filePath], { stdio: 'inherit' });
813
- }),
814
- };
815
- }
150
+ const livereload = require('rollup-plugin-livereload');
151
+ const { string } = require('rollup-plugin-string');
152
+ const { exec, spawn } = require('child_process');
153
+ const readline = require('readline');
154
+ const importAssets = require('rollup-plugin-import-assets');
155
+ const execAsync = node_util.promisify(exec);
156
+ const copyFiles = node_util.promisify(fs__default["default"].copy);
157
+ const pipeline = node_util.promisify(stream__default["default"].pipeline);
158
+ updateDotenv();
159
+ const REG_CLEAR_TEXT = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
160
+ const REG_RPT_ERROR_FILE = /(src[^:]+):(\d+):(\d+)/;
161
+ const REG_TJSX = /\.[tj]sx?$/;
162
+ const REG_EXT = /\.([^.]+)$/;
163
+ const scriptExtensions = ['ts', 'js', 'tsx', 'jsx'];
164
+ const indexExt = scriptExtensions.join(',');
165
+ class InnetJS {
166
+ constructor({ envPrefix = process.env.INNETJS_ENV_PREFIX || 'INNETJS_', projectFolder = process.env.PROJECT_FOLDER || '', baseUrl = process.env.BASE_URL || '', publicFolder = process.env.PUBLIC_FOLDER || 'public', releaseFolder = process.env.RELEASE_FOLDER || 'release', buildFolder = process.env.BUILD_FOLDER || 'build', srcFolder = process.env.SRC_FOLDER || 'src', sourcemap = process.env.SOURCEMAP ? process.env.SOURCEMAP === 'true' : false, cssModules = process.env.CSS_MODULES ? process.env.CSS_MODULES === 'true' : true, cssInJs = process.env.CSS_IN_JS ? process.env.CSS_IN_JS === 'true' : true, sslKey = process.env.SSL_KEY || 'localhost.key', sslCrt = process.env.SSL_CRT || 'localhost.crt', proxy = process.env.PROXY || '', simulateIP = process.env.IP, port = process.env.PORT ? +process.env.PORT : 3000, api = process.env.API || '/api/?*', } = {}) {
167
+ this.projectFolder = path__default["default"].resolve(projectFolder);
168
+ this.publicFolder = path__default["default"].resolve(publicFolder);
169
+ this.releaseFolder = path__default["default"].resolve(releaseFolder);
170
+ this.buildFolder = path__default["default"].resolve(buildFolder);
171
+ this.srcFolder = path__default["default"].resolve(srcFolder);
172
+ this.licenseFile = path__default["default"].join(projectFolder, 'LICENSE');
173
+ this.licenseReleaseFile = path__default["default"].join(releaseFolder, 'LICENSE');
174
+ this.readmeFile = path__default["default"].join(projectFolder, 'README.md');
175
+ this.readmeReleaseFile = path__default["default"].join(releaseFolder, 'README.md');
176
+ this.declarationFile = path__default["default"].join(srcFolder, 'declaration.d.ts');
177
+ this.declarationReleaseFile = path__default["default"].join(releaseFolder, 'declaration.d.ts');
178
+ this.publicIndexFile = path__default["default"].join(publicFolder, 'index.html');
179
+ this.buildIndexFile = path__default["default"].join(buildFolder, 'index.html');
180
+ this.devBuildFolder = path__default["default"].resolve(projectFolder, 'node_modules', '.cache', 'innetjs', 'build');
181
+ this.devBuildIndexFile = path__default["default"].join(this.devBuildFolder, 'index.html');
182
+ this.sourcemap = sourcemap;
183
+ this.cssModules = cssModules;
184
+ this.cssInJs = cssInJs;
185
+ this.sslKey = sslKey;
186
+ this.sslCrt = sslCrt;
187
+ this.port = port;
188
+ this.proxy = proxy;
189
+ this.api = api;
190
+ this.baseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
191
+ this.envPrefix = envPrefix;
192
+ this.simulateIP = simulateIP;
193
+ }
194
+ // Methods
195
+ init(appName, { template, force = false } = {}) {
196
+ return tslib.__awaiter(this, void 0, void 0, function* () {
197
+ const appPath = path__default["default"].resolve(appName);
198
+ const { data } = yield logger__default["default"].start('Get templates list', () => tslib.__awaiter(this, void 0, void 0, function* () { return yield axios__default["default"].get('https://api.github.com/repos/d8corp/innetjs-templates/branches'); }));
199
+ const templates = data.map(({ name }) => name).filter(name => name !== 'main');
200
+ if (!template || !templates.includes(template)) {
201
+ logger__default["default"].log(chalk__default["default"].green('Select one of those templates'));
202
+ const { value } = yield selector__default["default"]({
203
+ values: templates,
204
+ });
205
+ template = value;
206
+ readline.moveCursor(process.stdout, 0, -1);
207
+ const text = `Selected template: ${chalk__default["default"].white(value)}`;
208
+ logger__default["default"].start(text);
209
+ logger__default["default"].end(text);
210
+ }
211
+ if (!force) {
212
+ yield logger__default["default"].start('Check if app folder is available', () => tslib.__awaiter(this, void 0, void 0, function* () {
213
+ if (fs__default["default"].existsSync(appPath)) {
214
+ logger__default["default"].log(chalk__default["default"].red(`'${appPath}' already exist, what do you want?`));
215
+ const { id: result, value } = yield selector__default["default"]({
216
+ values: ['Stop the process', 'Remove the folder', 'Merge with template'],
217
+ });
218
+ readline.moveCursor(process.stdout, 0, -1);
219
+ logger__default["default"].log(`Already exist, selected: ${value}`);
220
+ if (!result) {
221
+ throw Error(`'${appPath}' already exist`);
222
+ }
223
+ if (result === 1) {
224
+ yield fs__default["default"].remove(appPath);
225
+ }
226
+ }
227
+ }));
228
+ }
229
+ yield logger__default["default"].start('Download template', () => tslib.__awaiter(this, void 0, void 0, function* () {
230
+ if (!fs__default["default"].existsSync(appPath)) {
231
+ fs__default["default"].mkdirSync(appPath);
232
+ }
233
+ const zipPath = path__default["default"].join(appPath, 'template.zip');
234
+ const unzipPath = path__default["default"].join(appPath, `innetjs-templates-${template}`);
235
+ const { data } = yield axios__default["default"].get(`https://github.com/d8corp/innetjs-templates/archive/refs/heads/${template}.zip`, {
236
+ responseType: 'stream',
237
+ });
238
+ yield pipeline(data, fs__default["default"].createWriteStream(zipPath));
239
+ yield new Promise((resolve, reject) => {
240
+ fs__default["default"].createReadStream(zipPath)
241
+ .pipe(unzipper.Extract({ path: appPath }))
242
+ .on('finish', resolve).on('error', reject);
243
+ });
244
+ yield fs__default["default"].remove(zipPath);
245
+ yield fs__default["default"].move(unzipPath, appPath);
246
+ }));
247
+ yield logger__default["default"].start('Install packages', () => execAsync(`cd ${appPath} && npm i`));
248
+ });
249
+ }
250
+ build({ node = false, inject = false, index = 'index' } = {}) {
251
+ return tslib.__awaiter(this, void 0, void 0, function* () {
252
+ const input = glob__default["default"].sync(`src/${index}.{${indexExt}}`);
253
+ if (!input.length) {
254
+ throw Error('index file is not detected');
255
+ }
256
+ yield logger__default["default"].start('Remove build', () => fs__default["default"].remove(this.buildFolder));
257
+ const pkg = node && (yield this.getPackage());
258
+ const options = {
259
+ input,
260
+ preserveEntrySignatures: 'strict',
261
+ plugins: [
262
+ commonjs__default["default"](),
263
+ json__default["default"](),
264
+ ts__default["default"]({
265
+ noEmitOnError: true,
266
+ compilerOptions: {
267
+ declaration: false,
268
+ },
269
+ }),
270
+ jsx__default["default"](),
271
+ ],
272
+ onwarn(warning, warn) {
273
+ if (warning.code === 'THIS_IS_UNDEFINED' || warning.code === 'SOURCEMAP_ERROR')
274
+ return;
275
+ warn(warning);
276
+ },
277
+ };
278
+ this.withLint(options, true);
279
+ const outputOptions = {
280
+ dir: this.buildFolder,
281
+ sourcemap: this.sourcemap,
282
+ };
283
+ if (node) {
284
+ outputOptions.format = 'cjs';
285
+ options.external = Object.keys((pkg === null || pkg === void 0 ? void 0 : pkg.dependencies) || {});
286
+ options.plugins.push(pluginNodeResolve.nodeResolve(), string({
287
+ include: '**/*.*',
288
+ exclude: stringExcludeNode,
289
+ }));
290
+ }
291
+ else {
292
+ options.plugins.push(pluginNodeResolve.nodeResolve({
293
+ browser: true,
294
+ }), polyfill__default["default"](), importAssets({
295
+ include: imageInclude.map(img => `src/${img}`),
296
+ publicPath: this.baseUrl,
297
+ }), styles__default["default"]({
298
+ mode: this.cssInJs ? 'inject' : 'extract',
299
+ url: {
300
+ inline: false,
301
+ publicPath: `${this.baseUrl}assets`,
302
+ },
303
+ plugins: [autoprefixer__default["default"]()],
304
+ autoModules: this.cssModules ? (id) => !id.includes('.global.') : true,
305
+ sourceMap: this.sourcemap,
306
+ minimize: true,
307
+ }), string({
308
+ include: '**/*.*',
309
+ exclude: stringExcludeDom,
310
+ }));
311
+ outputOptions.format = 'es';
312
+ outputOptions.plugins = [
313
+ rollupPluginTerser.terser(),
314
+ filesize__default["default"]({
315
+ reporter,
316
+ }),
317
+ ];
318
+ }
319
+ this.withEnv(options, true);
320
+ yield logger__default["default"].start('Build production bundle', () => tslib.__awaiter(this, void 0, void 0, function* () {
321
+ const bundle = yield rollup__default["default"].rollup(options);
322
+ yield bundle.write(outputOptions);
323
+ yield bundle.close();
324
+ if (!node) {
325
+ yield copyFiles(this.publicFolder, this.buildFolder);
326
+ const data = yield fs.promises.readFile(this.publicIndexFile);
327
+ const pkg = yield this.getPackage();
328
+ yield fs.promises.writeFile(this.buildIndexFile, yield convertIndexFile(data, pkg.version, this.baseUrl, path__default["default"].parse(input[0]).name, inject));
329
+ }
330
+ }));
331
+ if (pkg) {
332
+ yield logger__default["default"].start('Copy package.json', () => tslib.__awaiter(this, void 0, void 0, function* () {
333
+ const data = Object.assign({}, pkg);
334
+ delete data.private;
335
+ delete data.devDependencies;
336
+ yield fs__default["default"].writeFile(path__default["default"].resolve(this.buildFolder, 'package.json'), JSON.stringify(data, undefined, 2), 'UTF-8');
337
+ }));
338
+ const pkgLockPath = path__default["default"].resolve(this.projectFolder, 'package-lock.json');
339
+ if (fs__default["default"].existsSync(pkgLockPath)) {
340
+ yield logger__default["default"].start('Copy package-lock.json', () => {
341
+ return fs__default["default"].copy(pkgLockPath, path__default["default"].resolve(this.buildFolder, 'package-lock.json'));
342
+ });
343
+ }
344
+ }
345
+ });
346
+ }
347
+ start({ node = false, inject = false, error = false, index = 'index' } = {}) {
348
+ return tslib.__awaiter(this, void 0, void 0, function* () {
349
+ const pkg = yield this.getPackage();
350
+ const input = glob__default["default"].sync(`src/${index}.{${indexExt}}`);
351
+ if (!input.length) {
352
+ throw Error('index file is not detected');
353
+ }
354
+ yield logger__default["default"].start('Remove build', () => fs__default["default"].remove(this.devBuildFolder));
355
+ const options = {
356
+ input,
357
+ preserveEntrySignatures: 'strict',
358
+ output: {
359
+ dir: this.devBuildFolder,
360
+ sourcemap: true,
361
+ },
362
+ plugins: [
363
+ commonjs__default["default"](),
364
+ json__default["default"](),
365
+ ts__default["default"]({
366
+ compilerOptions: {
367
+ declaration: false,
368
+ sourceMap: true,
369
+ },
370
+ }),
371
+ jsx__default["default"](),
372
+ ],
373
+ onwarn(warning, warn) {
374
+ if (warning.code === 'THIS_IS_UNDEFINED' || warning.code === 'SOURCEMAP_ERROR')
375
+ return;
376
+ if (warning.plugin === 'typescript') {
377
+ const { loc: { line, column, file }, frame, message } = warning;
378
+ console.log(`ERROR in ${file}:${line}:${column}`);
379
+ console.log(message);
380
+ console.log(frame);
381
+ return;
382
+ }
383
+ warn(warning);
384
+ },
385
+ };
386
+ this.withLint(options);
387
+ if (node) {
388
+ // @ts-expect-error
389
+ options.output.format = 'cjs';
390
+ options.external = Object.keys((pkg === null || pkg === void 0 ? void 0 : pkg.dependencies) || {});
391
+ options.plugins.push(pluginNodeResolve.nodeResolve(), string({
392
+ include: '**/*.*',
393
+ exclude: stringExcludeNode,
394
+ }), this.createServer(input));
395
+ }
396
+ else {
397
+ const key = path__default["default"].basename(this.sslKey) !== this.sslKey
398
+ ? this.sslKey
399
+ : fs__default["default"].existsSync(this.sslKey)
400
+ ? fs__default["default"].readFileSync(this.sslKey)
401
+ : undefined;
402
+ const cert = path__default["default"].basename(this.sslCrt) !== this.sslCrt
403
+ ? this.sslCrt
404
+ : fs__default["default"].existsSync(this.sslCrt)
405
+ ? fs__default["default"].readFileSync(this.sslCrt)
406
+ : undefined;
407
+ // @ts-expect-error
408
+ options.output.format = 'es';
409
+ options.plugins.push(pluginNodeResolve.nodeResolve({
410
+ browser: true,
411
+ }), polyfill__default["default"](), importAssets({
412
+ include: imageInclude.map(img => `src/${img}`),
413
+ publicPath: this.baseUrl,
414
+ }), styles__default["default"]({
415
+ mode: this.cssInJs ? 'inject' : 'extract',
416
+ url: {
417
+ inline: false,
418
+ publicPath: `${this.baseUrl}assets`,
419
+ },
420
+ plugins: [autoprefixer__default["default"]()],
421
+ autoModules: this.cssModules ? (id) => !id.includes('.global.') : true,
422
+ sourceMap: true,
423
+ }), string({
424
+ include: '**/*.*',
425
+ exclude: stringExcludeDom,
426
+ }), this.createClient(key, cert, pkg, path__default["default"].parse(input[0]).name, inject), livereload(Object.assign({ exts: ['html', 'css', 'js', 'png', 'svg', 'webp', 'gif', 'jpg', 'json'], watch: [this.devBuildFolder, this.publicFolder], verbose: false }, (key && cert ? { https: { key, cert } } : {}))));
427
+ }
428
+ this.withEnv(options, true);
429
+ const watcher = rollup__default["default"].watch(options);
430
+ watcher.on('event', (e) => tslib.__awaiter(this, void 0, void 0, function* () {
431
+ if (e.code === 'ERROR') {
432
+ if (e.error.code === 'UNRESOLVED_IMPORT') {
433
+ const [, importer, file] = e.error.message.match(/^Could not resolve '(.+)' from (.+)$/) || [];
434
+ const text = (yield fs__default["default"].readFile(file)).toString();
435
+ const lines = new linesAndColumns.LinesAndColumns(text);
436
+ const { line, column } = lines.locationForIndex(text.indexOf(importer));
437
+ logger__default["default"].end('Bundling', e.error.message);
438
+ console.log(`ERROR in ${file}:${line + 1}:${column + 1}`);
439
+ }
440
+ else if (e.error.code === 'PLUGIN_ERROR' && ['rpt2', 'commonjs', 'typescript'].includes(e.error.plugin)) {
441
+ const [, file, line, column] = e.error.message
442
+ .replace(REG_CLEAR_TEXT, '')
443
+ .match(REG_RPT_ERROR_FILE) || [];
444
+ logger__default["default"].end('Bundling', e.error.message);
445
+ if (file) {
446
+ console.log(`ERROR in ${file}:${line}:${column}`);
447
+ }
448
+ else if (e.error.loc) {
449
+ console.log(`ERROR in ${e.error.loc.file}:${e.error.loc.line}:${e.error.loc.column}`);
450
+ console.log(e.error.frame);
451
+ }
452
+ }
453
+ else {
454
+ logger__default["default"].end('Bundling', error ? e.error.stack : e.error.message);
455
+ }
456
+ }
457
+ else if (e.code === 'BUNDLE_START') {
458
+ logger__default["default"].start('Bundling');
459
+ }
460
+ else if (e.code === 'BUNDLE_END') {
461
+ logger__default["default"].end('Bundling');
462
+ }
463
+ }));
464
+ });
465
+ }
466
+ run(file) {
467
+ return tslib.__awaiter(this, void 0, void 0, function* () {
468
+ const input = yield logger__default["default"].start('Check file', () => getFile(file));
469
+ const folder = yield new Promise((resolve, reject) => {
470
+ tmp__default["default"].dir((err, folder) => {
471
+ if (err) {
472
+ reject(err);
473
+ }
474
+ else {
475
+ resolve(folder);
476
+ }
477
+ });
478
+ });
479
+ const jsFilePath = `${folder}/index.js`;
480
+ yield logger__default["default"].start('Build bundle', () => tslib.__awaiter(this, void 0, void 0, function* () {
481
+ const inputOptions = {
482
+ input,
483
+ plugins: [
484
+ commonjs__default["default"](),
485
+ pluginNodeResolve.nodeResolve(),
486
+ json__default["default"](),
487
+ ts__default["default"]({
488
+ compilerOptions: {
489
+ sourceMap: true,
490
+ },
491
+ }),
492
+ ],
493
+ };
494
+ const outputOptions = {
495
+ format: 'cjs',
496
+ file: jsFilePath,
497
+ sourcemap: true,
498
+ };
499
+ const bundle = yield rollup__default["default"].rollup(inputOptions);
500
+ yield bundle.write(outputOptions);
501
+ yield bundle.close();
502
+ }));
503
+ yield logger__default["default"].start('Running of the script', () => tslib.__awaiter(this, void 0, void 0, function* () {
504
+ spawn('node', ['-r', 'source-map-support/register', jsFilePath], { stdio: 'inherit' });
505
+ }));
506
+ });
507
+ }
508
+ release({ index = 'index', pub } = {}) {
509
+ return tslib.__awaiter(this, void 0, void 0, function* () {
510
+ const { releaseFolder, cssModules } = this;
511
+ yield logger__default["default"].start('Remove previous release', () => fs__default["default"].remove(releaseFolder));
512
+ const pkg = yield this.getPackage();
513
+ const build = (format) => tslib.__awaiter(this, void 0, void 0, function* () {
514
+ var _a, _b;
515
+ const ext = format === 'es'
516
+ ? ((_a = (pkg.module || pkg.esnext || pkg['jsnext:main'])) === null || _a === void 0 ? void 0 : _a.replace('index', '')) || '.mjs'
517
+ : ((_b = pkg.main) === null || _b === void 0 ? void 0 : _b.replace('index', '')) || '.js';
518
+ const input = glob__default["default"].sync(`src/${index}.{${indexExt}}`);
519
+ if (!input.length) {
520
+ throw Error('index file is not detected');
521
+ }
522
+ const options = {
523
+ input,
524
+ external: ['tslib'],
525
+ treeshake: false,
526
+ output: {
527
+ dir: releaseFolder,
528
+ entryFileNames: ({ name, facadeModuleId }) => {
529
+ if (REG_TJSX.test(facadeModuleId)) {
530
+ return `${name}${ext}`;
531
+ }
532
+ const match = facadeModuleId.match(REG_EXT);
533
+ return match ? `${name}${match[0]}${ext}` : `${name}${ext}`;
534
+ },
535
+ format,
536
+ preserveModules: true,
537
+ exports: 'named',
538
+ },
539
+ plugins: [
540
+ json__default["default"](),
541
+ ts__default["default"]({
542
+ compilerOptions: {
543
+ sourceMap: false,
544
+ outDir: releaseFolder,
545
+ },
546
+ }),
547
+ jsx__default["default"](),
548
+ externals__default["default"](),
549
+ string({
550
+ include: '**/*.*',
551
+ exclude: stringExcludeDom,
552
+ }),
553
+ image__default["default"](),
554
+ styles__default["default"]({
555
+ mode: this.cssInJs ? 'inject' : 'extract',
556
+ plugins: [autoprefixer__default["default"]()],
557
+ autoModules: cssModules ? (id) => !id.includes('.global.') : true,
558
+ minimize: true,
559
+ }),
560
+ pluginNodeResolve.nodeResolve(),
561
+ external__default["default"](),
562
+ ],
563
+ };
564
+ this.withLint(options);
565
+ this.withEnv(options, true);
566
+ const bundle = yield rollup__default["default"].rollup(options);
567
+ yield bundle.write(options.output);
568
+ yield bundle.close();
569
+ });
570
+ yield logger__default["default"].start('Build cjs bundle', () => tslib.__awaiter(this, void 0, void 0, function* () {
571
+ yield build('cjs');
572
+ }));
573
+ yield logger__default["default"].start('Build es6 bundle', () => tslib.__awaiter(this, void 0, void 0, function* () {
574
+ yield build('es');
575
+ }));
576
+ yield logger__default["default"].start('Copy package.json', () => tslib.__awaiter(this, void 0, void 0, function* () {
577
+ const data = Object.assign({}, pkg);
578
+ delete data.private;
579
+ delete data.devDependencies;
580
+ yield fs__default["default"].writeFile(path__default["default"].resolve(this.releaseFolder, 'package.json'), JSON.stringify(data, undefined, 2), 'UTF-8');
581
+ }));
582
+ if (pkg.bin) {
583
+ yield logger__default["default"].start('Build bin', () => tslib.__awaiter(this, void 0, void 0, function* () {
584
+ const { bin } = pkg;
585
+ for (const name in bin) {
586
+ const value = bin[name];
587
+ const input = glob__default["default"].sync(`src/${value}.{${indexExt}}`);
588
+ const file = path__default["default"].join(this.releaseFolder, value);
589
+ const options = {
590
+ input,
591
+ external: [...Object.keys(pkg.dependencies), 'tslib'],
592
+ output: {
593
+ file,
594
+ format: 'cjs',
595
+ },
596
+ plugins: [
597
+ rollupPluginPreserveShebangs.preserveShebangs(),
598
+ json__default["default"](),
599
+ ts__default["default"]({
600
+ compilerOptions: {
601
+ declaration: false,
602
+ },
603
+ }),
604
+ externals__default["default"](),
605
+ jsx__default["default"](),
606
+ ],
607
+ };
608
+ this.withLint(options);
609
+ this.withEnv(options);
610
+ const bundle = yield rollup__default["default"].rollup(options);
611
+ yield bundle.write(options.output);
612
+ yield bundle.close();
613
+ }
614
+ }));
615
+ }
616
+ if (fs__default["default"].existsSync(this.licenseFile)) {
617
+ yield logger__default["default"].start('Copy license', () => tslib.__awaiter(this, void 0, void 0, function* () {
618
+ yield fs.promises.copyFile(this.licenseFile, this.licenseReleaseFile);
619
+ }));
620
+ }
621
+ if (fs__default["default"].existsSync(this.readmeFile)) {
622
+ yield logger__default["default"].start('Copy readme', () => tslib.__awaiter(this, void 0, void 0, function* () {
623
+ yield fs.promises.copyFile(this.readmeFile, this.readmeReleaseFile);
624
+ }));
625
+ }
626
+ if (fs__default["default"].existsSync(this.declarationFile)) {
627
+ yield logger__default["default"].start('Copy declaration', () => tslib.__awaiter(this, void 0, void 0, function* () {
628
+ yield fs.promises.copyFile(this.declarationFile, this.declarationReleaseFile);
629
+ }));
630
+ }
631
+ if (pub) {
632
+ const date = (Date.now() / 1000) | 0;
633
+ yield logger__default["default"].start(`publishing v${pkg.version} ${date}`, () => tslib.__awaiter(this, void 0, void 0, function* () {
634
+ yield execAsync(`npm publish ${this.releaseFolder}`);
635
+ }));
636
+ }
637
+ });
638
+ }
639
+ withLint(options, prod = false) {
640
+ if (this._lintUsage === undefined) {
641
+ this._lintUsage = fs__default["default"].existsSync(path__default["default"].join(this.projectFolder, '.eslintrc'));
642
+ }
643
+ if (this._lintUsage) {
644
+ options.plugins.push(eslint__default["default"]({
645
+ include: lintInclude,
646
+ throwOnError: prod,
647
+ }));
648
+ }
649
+ }
650
+ withEnv(options, virtual) {
651
+ options.plugins.push(env__default["default"](this.envPrefix, {
652
+ include: options.input,
653
+ virtual,
654
+ }));
655
+ }
656
+ increaseVersion(release) {
657
+ return tslib.__awaiter(this, void 0, void 0, function* () {
658
+ const pkg = yield this.getPackage();
659
+ yield logger__default["default"].start('Prepare package.json', () => tslib.__awaiter(this, void 0, void 0, function* () {
660
+ const version = pkg.version.split('.');
661
+ switch (release) {
662
+ case 'patch': {
663
+ version[2]++;
664
+ break;
665
+ }
666
+ case 'minor': {
667
+ version[1]++;
668
+ version[2] = 0;
669
+ break;
670
+ }
671
+ case 'major': {
672
+ version[1] = 0;
673
+ version[2] = 0;
674
+ version[0]++;
675
+ break;
676
+ }
677
+ default: return;
678
+ }
679
+ pkg.version = version.join('.');
680
+ yield fs__default["default"].writeFile(path__default["default"].resolve(this.projectFolder, 'package.json'), JSON.stringify(pkg, undefined, 2), 'UTF-8');
681
+ }));
682
+ });
683
+ }
684
+ getPackage() {
685
+ return tslib.__awaiter(this, void 0, void 0, function* () {
686
+ if (this.package) {
687
+ return this.package;
688
+ }
689
+ const packageFolder = path__default["default"].resolve(this.projectFolder, 'package.json');
690
+ yield logger__default["default"].start('Check package.json', () => tslib.__awaiter(this, void 0, void 0, function* () {
691
+ if (fs__default["default"].existsSync(packageFolder)) {
692
+ this.package = yield fs__default["default"].readJson(packageFolder);
693
+ }
694
+ }));
695
+ return this.package;
696
+ });
697
+ }
698
+ createClient(key, cert, pkg, index, inject) {
699
+ let app;
700
+ return {
701
+ name: 'client',
702
+ writeBundle: () => tslib.__awaiter(this, void 0, void 0, function* () {
703
+ var _a;
704
+ if (!app) {
705
+ app = express__default["default"]();
706
+ const update = () => tslib.__awaiter(this, void 0, void 0, function* () {
707
+ const data = yield fs.promises.readFile(this.publicIndexFile);
708
+ yield fs.promises.writeFile(this.devBuildIndexFile, yield convertIndexFile(data, pkg.version, this.baseUrl, index, inject));
709
+ });
710
+ fs__default["default"].watch(this.publicIndexFile, update);
711
+ yield update();
712
+ const httpsUsing = !!(cert && key);
713
+ app.use(this.baseUrl, express__default["default"].static(this.devBuildFolder));
714
+ app.use(this.baseUrl, express__default["default"].static(this.publicFolder));
715
+ if ((_a = this.proxy) === null || _a === void 0 ? void 0 : _a.startsWith('http')) {
716
+ if (this.simulateIP) {
717
+ app.use((req, res, next) => {
718
+ req.headers['X-Real-IP'] = this.simulateIP;
719
+ next();
720
+ });
721
+ }
722
+ app.use(this.api, proxy__default["default"](this.proxy, {
723
+ https: httpsUsing,
724
+ limit: '1000mb',
725
+ proxyReqPathResolver: req => req.originalUrl,
726
+ }));
727
+ }
728
+ app.use(/^([^.]*|.*\.[^.]{5,})$/, (req, res) => {
729
+ res.sendFile(this.devBuildFolder + '/index.html');
730
+ });
731
+ const server = httpsUsing ? https__default["default"].createServer({ key, cert }, app) : http__default["default"].createServer(app);
732
+ let port = this.port;
733
+ const listener = () => {
734
+ const baseUrl = this.baseUrl === '/' ? '' : this.baseUrl;
735
+ console.log(`${chalk__default["default"].green('➤')} Started on http${httpsUsing ? 's' : ''}://localhost:${port}${baseUrl} and http${httpsUsing ? 's' : ''}://${address__default["default"].ip()}:${port}${baseUrl}`);
736
+ };
737
+ server.listen(port, listener);
738
+ server.on('error', (e) => tslib.__awaiter(this, void 0, void 0, function* () {
739
+ if (e.code === 'EADDRINUSE') {
740
+ port++;
741
+ const { userPort } = yield prompt__default["default"]({
742
+ name: 'userPort',
743
+ type: 'number',
744
+ message: `Port ${e.port} is reserved, please enter another one [${port}]:`,
745
+ });
746
+ if (userPort) {
747
+ port = userPort;
748
+ }
749
+ server.listen(port);
750
+ }
751
+ else {
752
+ throw e;
753
+ }
754
+ }));
755
+ }
756
+ }),
757
+ };
758
+ }
759
+ createServer(input) {
760
+ const apps = {};
761
+ return {
762
+ name: 'server',
763
+ writeBundle: () => tslib.__awaiter(this, void 0, void 0, function* () {
764
+ var _a;
765
+ for (const file of input) {
766
+ const { name } = path__default["default"].parse(file);
767
+ (_a = apps[name]) === null || _a === void 0 ? void 0 : _a.kill();
768
+ const filePath = path__default["default"].resolve(this.devBuildFolder, `${name}.js`);
769
+ apps[name] = spawn('node', ['-r', 'source-map-support/register', filePath], { stdio: 'inherit' });
770
+ }
771
+ }),
772
+ };
773
+ }
816
774
  }
817
775
 
818
776
  (function () {
819
- const env = {"__INNETJS__PACKAGE_VERSION":"2.6.0-alpha.1"};
777
+ const env = {"__INNETJS__PACKAGE_VERSION":"2.6.0-alpha.10"};
820
778
  if (typeof process === 'undefined') {
821
779
  globalThis.process = { env: env };
822
780
  } else if (process.env) {
@@ -825,115 +783,115 @@ class InnetJS {
825
783
  process.env = env;
826
784
  }
827
785
  })();
828
- updateDotenv();
829
- const innetJS = new InnetJS();
830
- const errorOption = new commander.Option('-e, --error', 'Show error details');
831
- commander.program
832
- .version(process.env.__INNETJS__PACKAGE_VERSION, '-v, --version');
833
- commander.program
834
- .command('init <app-name>')
835
- .description('Create innet boilerplate')
836
- .option('-t, --template <template>', 'Select template fe or be')
837
- .addOption(errorOption)
838
- .action((appName, { error, template }) => {
839
- innetJS.init(appName, { template }).catch(e => {
840
- if (error) {
841
- console.error(e);
842
- process.exit(1);
843
- }
844
- });
845
- });
846
- commander.program
847
- .command('run <file-path>')
848
- .description('Run js, ts or tsx file')
849
- .addOption(errorOption)
850
- .action((filePath, { error }) => {
851
- innetJS.run(filePath).catch(e => {
852
- if (error) {
853
- console.error(e);
854
- process.exit(1);
855
- }
856
- });
857
- });
858
- commander.program
859
- .command('start')
860
- .description('Start development with innet boilerplate')
861
- .option('-n, --node', 'Start development for Node.js')
862
- .option('-in, --inject', 'Injects script element into index.html')
863
- .option('-i, --index <index>', 'Root index file name', 'index')
864
- .addOption(errorOption)
865
- .action(({ error, node, index, inject }) => {
866
- innetJS.start({ node, error, index, inject }).catch(e => {
867
- if (error) {
868
- console.error(e);
869
- process.exit(1);
870
- }
871
- });
872
- });
873
- commander.program
874
- .command('build')
875
- .description('Build production bundle')
876
- .addOption(errorOption)
877
- .option('-n, --node', 'Build for node.js')
878
- .option('-in, --inject', 'Injects script element into index.html')
879
- .option('-i, --index <index>', 'Root index file name', 'index')
880
- .action(({ error, node, index, inject }) => {
881
- innetJS.build({ node, index, inject }).catch(e => {
882
- if (error) {
883
- console.error(e);
884
- process.exit(1);
885
- }
886
- });
887
- });
888
- commander.program
889
- .command('release')
890
- .description('Release new version of your library')
891
- .option('-i, --index <index>', 'Root index file name', 'index')
892
- .option('-p, --public', 'Public the package')
893
- .addOption(errorOption)
894
- .action(({ error, index, public: pub }) => {
895
- innetJS.release({ index, pub }).catch(e => {
896
- if (error) {
897
- console.error(e);
898
- process.exit(1);
899
- }
900
- });
901
- });
902
- commander.program
903
- .command('patch')
904
- .description('Increase patch version of package')
905
- .addOption(errorOption)
906
- .action(({ error }) => {
907
- innetJS.increaseVersion('patch').catch(e => {
908
- if (error) {
909
- console.error(e);
910
- process.exit(1);
911
- }
912
- });
913
- });
914
- commander.program
915
- .command('minor')
916
- .description('Increase minor version of package')
917
- .addOption(errorOption)
918
- .action(({ error }) => {
919
- innetJS.increaseVersion('minor').catch(e => {
920
- if (error) {
921
- console.error(e);
922
- process.exit(1);
923
- }
924
- });
925
- });
926
- commander.program
927
- .command('major')
928
- .description('Increase major version of package')
929
- .addOption(errorOption)
930
- .action(({ error }) => {
931
- innetJS.increaseVersion('major').catch(e => {
932
- if (error) {
933
- console.error(e);
934
- process.exit(1);
935
- }
936
- });
937
- });
938
- commander.program
786
+ updateDotenv();
787
+ const innetJS = new InnetJS();
788
+ const errorOption = new commander.Option('-e, --error', 'Show error details');
789
+ commander.program
790
+ .version(process.env.__INNETJS__PACKAGE_VERSION, '-v, --version');
791
+ commander.program
792
+ .command('init <app-name>')
793
+ .description('Create innet boilerplate')
794
+ .option('-t, --template <template>', 'Select template fe or be')
795
+ .addOption(errorOption)
796
+ .action((appName, { error, template }) => {
797
+ innetJS.init(appName, { template }).catch(e => {
798
+ if (error) {
799
+ console.error(e);
800
+ process.exit(1);
801
+ }
802
+ });
803
+ });
804
+ commander.program
805
+ .command('run <file-path>')
806
+ .description('Run js, ts or tsx file')
807
+ .addOption(errorOption)
808
+ .action((filePath, { error }) => {
809
+ innetJS.run(filePath).catch(e => {
810
+ if (error) {
811
+ console.error(e);
812
+ process.exit(1);
813
+ }
814
+ });
815
+ });
816
+ commander.program
817
+ .command('start')
818
+ .description('Start development with innet boilerplate')
819
+ .option('-n, --node', 'Start development for Node.js')
820
+ .option('-in, --inject', 'Injects script element into index.html')
821
+ .option('-i, --index <index>', 'Root index file name', 'index')
822
+ .addOption(errorOption)
823
+ .action(({ error, node, index, inject }) => {
824
+ innetJS.start({ node, error, index, inject }).catch(e => {
825
+ if (error) {
826
+ console.error(e);
827
+ process.exit(1);
828
+ }
829
+ });
830
+ });
831
+ commander.program
832
+ .command('build')
833
+ .description('Build production bundle')
834
+ .addOption(errorOption)
835
+ .option('-n, --node', 'Build for node.js')
836
+ .option('-in, --inject', 'Injects script element into index.html')
837
+ .option('-i, --index <index>', 'Root index file name', 'index')
838
+ .action(({ error, node, index, inject }) => {
839
+ innetJS.build({ node, index, inject }).catch(e => {
840
+ if (error) {
841
+ console.error(e);
842
+ process.exit(1);
843
+ }
844
+ });
845
+ });
846
+ commander.program
847
+ .command('release')
848
+ .description('Release new version of your library')
849
+ .option('-i, --index <index>', 'Root index file name', 'index')
850
+ .option('-p, --public', 'Public the package')
851
+ .addOption(errorOption)
852
+ .action(({ error, index, public: pub }) => {
853
+ innetJS.release({ index, pub }).catch(e => {
854
+ if (error) {
855
+ console.error(e);
856
+ process.exit(1);
857
+ }
858
+ });
859
+ });
860
+ commander.program
861
+ .command('patch')
862
+ .description('Increase patch version of package')
863
+ .addOption(errorOption)
864
+ .action(({ error }) => {
865
+ innetJS.increaseVersion('patch').catch(e => {
866
+ if (error) {
867
+ console.error(e);
868
+ process.exit(1);
869
+ }
870
+ });
871
+ });
872
+ commander.program
873
+ .command('minor')
874
+ .description('Increase minor version of package')
875
+ .addOption(errorOption)
876
+ .action(({ error }) => {
877
+ innetJS.increaseVersion('minor').catch(e => {
878
+ if (error) {
879
+ console.error(e);
880
+ process.exit(1);
881
+ }
882
+ });
883
+ });
884
+ commander.program
885
+ .command('major')
886
+ .description('Increase major version of package')
887
+ .addOption(errorOption)
888
+ .action(({ error }) => {
889
+ innetJS.increaseVersion('major').catch(e => {
890
+ if (error) {
891
+ console.error(e);
892
+ process.exit(1);
893
+ }
894
+ });
895
+ });
896
+ commander.program
939
897
  .parse(process.argv);