Skip to content

Commit 06b5f01

Browse files
committed
feat(cubejs-cli): Move helpers to TypeScript
1 parent 009ff7a commit 06b5f01

File tree

7 files changed

+109
-96
lines changed

7 files changed

+109
-96
lines changed

packages/cubejs-cli/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"node": ">=8.11.1"
1313
},
1414
"bin": {
15-
"cubejs": "src/index.js"
15+
"cubejs": "dist/index.js"
1616
},
1717
"scripts": {
1818
"tsc": "tsc",
@@ -42,6 +42,7 @@
4242
"request-promise": "^4.2.5"
4343
},
4444
"devDependencies": {
45+
"@types/cross-spawn": "^6.0.2",
4546
"@types/node": "^14.11.10",
4647
"eslint": "^6.8.0",
4748
"eslint-config-airbnb-base": "^13.1.0",

packages/cubejs-cli/src/cli.js

Lines changed: 2 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,48 +4,25 @@ eslint import/no-dynamic-require: 0
44
/*
55
eslint global-require: 0
66
*/
7+
78
const program = require('commander');
89
const fs = require('fs-extra');
910
const path = require('path');
10-
const os = require('os');
1111
const chalk = require('chalk');
12-
const spawn = require('cross-spawn');
1312
const crypto = require('crypto');
1413
const inquirer = require('inquirer');
1514

1615
const Config = require('./config');
1716
const templates = require('./templates');
1817
const { deploy } = require('./deploy');
1918
const { token, defaultExpiry, collect } = require('./token');
20-
const { requireFromPackage, event, displayError } = require('./utils');
19+
import { executeCommand, npmInstall, writePackageJson, requireFromPackage, event, displayError } from './utils';
2120

2221
const packageJson = require('../package.json');
2322

2423
program.name(Object.keys(packageJson.bin)[0])
2524
.version(packageJson.version);
2625

27-
const executeCommand = (command, args) => {
28-
const child = spawn(command, args, { stdio: 'inherit' });
29-
return new Promise((resolve, reject) => {
30-
child.on('close', code => {
31-
if (code !== 0) {
32-
reject(new Error(`${command} ${args.join(' ')} failed with exit code ${code}`));
33-
return;
34-
}
35-
resolve();
36-
});
37-
});
38-
};
39-
40-
const writePackageJson = async (json) => fs.writeJson('package.json', json, {
41-
spaces: 2,
42-
EOL: os.EOL
43-
});
44-
45-
const npmInstall = (dependencies, isDev) => executeCommand(
46-
'npm', ['install', isDev ? '--save-dev' : '--save'].concat(dependencies)
47-
);
48-
4926
const logStage = (stage) => {
5027
console.log(`- ${stage}`);
5128
};

packages/cubejs-cli/src/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,4 @@ if (major < 8) {
2424
process.exit(1);
2525
}
2626

27-
require('./cubejsCli');
27+
require('./cli');

packages/cubejs-cli/src/track.js

Lines changed: 0 additions & 50 deletions
This file was deleted.

packages/cubejs-cli/src/track.ts

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
const fetch = require('node-fetch');
2+
const crypto = require('crypto');
3+
4+
export type BaseEvent = any;
5+
export type Event = BaseEvent & any;
6+
7+
let flushPromise: Promise<any>|null = null;
8+
let trackEvents: Array<Event> = [];
9+
10+
const flush = async (toFlush?: Array<Event>, retries: number = 10): Promise<any> => {
11+
if (!toFlush) {
12+
toFlush = trackEvents;
13+
trackEvents = [];
14+
}
15+
16+
if (!toFlush.length) {
17+
return;
18+
}
19+
20+
try {
21+
const sentAt = new Date().toJSON();
22+
const result = await fetch('https://track.cube.dev/track', {
23+
method: 'post',
24+
body: JSON.stringify(toFlush.map(r => ({ ...r, sentAt }))),
25+
headers: { 'Content-Type': 'application/json' },
26+
});
27+
if (result.status !== 200 && retries > 0) {
28+
// eslint-disable-next-line consistent-return
29+
return flush(toFlush, retries - 1);
30+
}
31+
32+
// console.log(await result.json());
33+
} catch (e) {
34+
if (retries > 0) {
35+
// eslint-disable-next-line consistent-return
36+
return flush(toFlush, retries - 1);
37+
}
38+
// console.log(e);
39+
}
40+
};
41+
42+
export const track = async (event: BaseEvent) => {
43+
trackEvents.push({
44+
...event,
45+
id: crypto.randomBytes(16).toString('hex'),
46+
clientTimestamp: new Date().toJSON()
47+
});
48+
49+
const currentPromise = (flushPromise || Promise.resolve()).then(() => flush()).then(() => {
50+
if (currentPromise === flushPromise) {
51+
flushPromise = null;
52+
}
53+
});
54+
55+
flushPromise = currentPromise;
56+
return flushPromise;
57+
};

packages/cubejs-cli/src/utils.js renamed to packages/cubejs-cli/src/utils.ts

Lines changed: 39 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,39 @@
1-
const path = require('path');
2-
const fs = require('fs-extra');
3-
const { machineIdSync } = require('node-machine-id');
4-
const chalk = require('chalk');
5-
const track = require('./track');
1+
import os from 'os';
2+
import { spawn } from 'cross-spawn';
3+
import fs from 'fs-extra';
4+
import path from 'path';
5+
import chalk from 'chalk';
6+
import { machineIdSync } from 'node-machine-id';
7+
8+
import { track } from './track';
9+
10+
export const executeCommand = (command: string, args: string[]) => {
11+
const child = spawn(command, args, { stdio: 'inherit' });
12+
13+
return new Promise((resolve, reject) => {
14+
child.on('close', (code: number) => {
15+
if (code !== 0) {
16+
reject(new Error(`${command} ${args.join(' ')} failed with exit code ${code}`));
17+
return;
18+
}
19+
20+
resolve();
21+
});
22+
});
23+
};
24+
25+
export const writePackageJson = async (json: any) => fs.writeJson('package.json', json, {
26+
spaces: 2,
27+
EOL: os.EOL
28+
});
29+
30+
export const npmInstall = (dependencies: string[], isDev?: boolean) => executeCommand(
31+
'npm', ['install', isDev ? '--save-dev' : '--save'].concat(dependencies)
32+
);
633

734
const anonymousId = machineIdSync();
835

9-
const event = async (name, props) => {
36+
export const event = async (name: string, props: any) => {
1037
try {
1138
await track({
1239
event: name,
@@ -18,9 +45,7 @@ const event = async (name, props) => {
1845
}
1946
};
2047

21-
exports.event = event;
22-
23-
const displayError = async (text, options = {}) => {
48+
export const displayError = async (text: string, options = {}) => {
2449
console.error('');
2550
console.error(chalk.cyan('Cube.js Error ---------------------------------------'));
2651
console.error('');
@@ -39,27 +64,23 @@ const displayError = async (text, options = {}) => {
3964
process.exit(1);
4065
};
4166

42-
exports.displayError = displayError;
43-
44-
exports.requireFromPackage = async (module) => {
67+
export const requireFromPackage = async (moduleName: string) => {
4568
if (
46-
!(await fs.pathExists(path.join(process.cwd(), 'node_modules', module))) &&
69+
!(await fs.pathExists(path.join(process.cwd(), 'node_modules', moduleName))) &&
4770
!(await fs.pathExists(path.join(process.cwd(), 'node_modules', `${module}.js`)))
4871
) {
4972
await displayError(
50-
`${module} dependency not found. Please run this command from project directory.`
73+
`${moduleName} dependency not found. Please run this command from project directory.`
5174
);
5275
}
5376

5477
// eslint-disable-next-line global-require,import/no-dynamic-require
55-
return require(path.join(process.cwd(), 'node_modules', module));
78+
return require(path.join(process.cwd(), 'node_modules', moduleName));
5679
};
5780

58-
const logStage = async (stage, eventName, props) => {
81+
const logStage = async (stage: string, eventName: string, props: any) => {
5982
console.log(`- ${stage}`);
6083
if (eventName) {
6184
await event(eventName, props);
6285
}
6386
};
64-
65-
exports.logStage = logStage;

packages/cubejs-cli/yarn.lock

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,13 @@
330330
resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.1.tgz#1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0"
331331
integrity sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==
332332

333+
"@types/cross-spawn@^6.0.2":
334+
version "6.0.2"
335+
resolved "https://registry.yarnpkg.com/@types/cross-spawn/-/cross-spawn-6.0.2.tgz#168309de311cd30a2b8ae720de6475c2fbf33ac7"
336+
integrity sha512-KuwNhp3eza+Rhu8IFI5HUXRP0LIhqH5cAjubUvGXXthh4YYBuP2ntwEX+Cz8GJoZUHlKo247wPWOfA9LYEq4cw==
337+
dependencies:
338+
"@types/node" "*"
339+
333340
"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0":
334341
version "2.0.1"
335342
resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.1.tgz#42995b446db9a48a11a07ec083499a860e9138ff"
@@ -355,7 +362,7 @@
355362
resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee"
356363
integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4=
357364

358-
"@types/node@^14.11.10":
365+
"@types/node@*", "@types/node@^14.11.10":
359366
version "14.11.10"
360367
resolved "https://registry.yarnpkg.com/@types/node/-/node-14.11.10.tgz#8c102aba13bf5253f35146affbf8b26275069bef"
361368
integrity sha512-yV1nWZPlMFpoXyoknm4S56y2nlTAuFYaJuQtYRAOU7xA/FJ9RY0Xm7QOkaYMMmr8ESdHIuUb6oQgR/0+2NqlyA==

0 commit comments

Comments
 (0)