at-builder 1.1.6 → 1.1.7

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.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.setupEnv = exports.getHelpInfo = exports.getVersion = void 0;
3
+ exports.getENV = exports.setupEnv = exports.getHelpInfo = exports.getVersion = void 0;
4
4
  const path = require("path");
5
5
  const fs = require("fs");
6
6
  var clc = require("cli-color");
@@ -80,6 +80,7 @@ TARGET_URL=""
80
80
  LOGIN_URL=""
81
81
  VARIATION="Variation-1"
82
82
  NODE_ENV="development"
83
+ VERBOSE=false
83
84
  `;
84
85
  // Write the content to the .env file
85
86
  fs.writeFileSync(envPath, envContent.trim(), 'utf8');
@@ -107,3 +108,39 @@ const createWatchConfig = (basePath) => {
107
108
  console.log('watch-config.json file already exists!');
108
109
  }
109
110
  };
111
+ /**
112
+ * Reads and returns environment variables from the specified .env file
113
+ * @param {string} basePath - The base path where the .env file is located
114
+ * @returns {Promise<Object>} Object containing environment variables
115
+ */
116
+ const getENV = async (basePath) => {
117
+ const envPath = path.join(basePath, '.env');
118
+ try {
119
+ // Check if .env file exists
120
+ if (!fs.existsSync(envPath)) {
121
+ throw new Error('.env file not found');
122
+ }
123
+ // Read the .env file
124
+ const envContent = await fs.promises.readFile(envPath, { encoding: 'utf8' });
125
+ // Parse the .env file content
126
+ const envVars = {};
127
+ envContent.split('\n').forEach(line => {
128
+ line = line.trim();
129
+ // Skip empty lines and comments
130
+ if (line && !line.startsWith('#')) {
131
+ const [key, ...valueParts] = line.split('=');
132
+ if (key) {
133
+ const value = valueParts.join('=').trim();
134
+ // Remove quotes if present
135
+ envVars[key.trim()] = value.replace(/^["'](.*)["']$/, '$1');
136
+ }
137
+ }
138
+ });
139
+ return envVars;
140
+ }
141
+ catch (error) {
142
+ console.error(clc.red(`Error reading .env file: ${error.message}`));
143
+ throw error;
144
+ }
145
+ };
146
+ exports.getENV = getENV;
package/bin/index.js CHANGED
@@ -10,21 +10,22 @@ const fs_1 = __importDefault(require("fs"));
10
10
  const inquirer_1 = __importDefault(require("inquirer"));
11
11
  const commander_1 = require("commander");
12
12
  const config_1 = require("./constants/config");
13
+ const logger_1 = __importDefault(require("./services/logger"));
13
14
  /**
14
15
  * Checks if the .env file exists at the current working directory
15
16
  *
16
17
  * @throws {Error} If the .env file is not found
17
18
  */
18
19
  const checkEnvFile = () => {
19
- console.log("Checking if .env file exists at current working directory");
20
+ logger_1.default.info("checkEnvFile", "Checking if .env file exists at current working directory");
20
21
  try {
21
22
  // Check if the file exists and is readable
22
23
  fs_1.default.accessSync(path_1.default.join(process.cwd(), ".env"), fs_1.default.constants.R_OK);
23
- console.log(".env file found");
24
+ logger_1.default.info("checkEnvFile", ".env file found");
24
25
  }
25
26
  catch (error) {
26
27
  // If the file does not exist, throw an error
27
- console.log(`Error: Couldn't find .env file at location ${process.cwd()}`);
28
+ logger_1.default.error("checkEnvFile", `Error: Couldn't find .env file at location ${process.cwd()}`);
28
29
  throw error;
29
30
  }
30
31
  };
@@ -35,9 +36,9 @@ const productionEnv = {
35
36
  };
36
37
  // Commander setup
37
38
  const setupCommander = async () => {
38
- console.log("Setting up commander");
39
+ logger_1.default.info("setupCommander", "Setting up commander");
39
40
  const version = await (0, config_1.getVersion)();
40
- console.log(`Version: ${version}`);
41
+ logger_1.default.info("setupCommander", `Version: ${version}`);
41
42
  const program = new commander_1.Command();
42
43
  program
43
44
  .version(version, "-V, --version")
@@ -46,7 +47,7 @@ const setupCommander = async () => {
46
47
  .option("-p, --prod")
47
48
  .option("-v, --verbose", "Enable verbose logging")
48
49
  .parse(process.argv);
49
- console.log("Commander setup complete");
50
+ logger_1.default.info("setupCommander", "Commander setup complete");
50
51
  return program.opts();
51
52
  };
52
53
  /**
@@ -56,9 +57,9 @@ const setupCommander = async () => {
56
57
  * @param env - The environment object to pass to the spawned process.
57
58
  */
58
59
  const runCommand = (commandArr, env) => {
59
- console.log(`Running npm command [${commandArr.join(", ")}]`);
60
- console.log(`Current working directory: ${process.cwd()}`);
61
- // console.log(`Environment variables: ${JSON.stringify(env, null, 2)}`);
60
+ logger_1.default.info("runCommand", `Running npm command [${commandArr.join(", ")}]`);
61
+ logger_1.default.info("runCommand", `Current working directory: ${process.cwd()}`);
62
+ // logger.log(`Environment variables: ${JSON.stringify(env, null, 2)}`);
62
63
  // Spawn the command using `npm` with the given environment and current working directory.
63
64
  (0, child_process_1.spawn)("npm", commandArr, {
64
65
  cwd: path_1.default.join(__dirname, "../"),
@@ -74,16 +75,16 @@ const runCommand = (commandArr, env) => {
74
75
  * If false, runs the build with development environment.
75
76
  */
76
77
  const handleBuild = async (prod) => {
77
- console.log(`Handling build with options: production=${prod}`);
78
+ logger_1.default.info("handleBuild", `Handling build with options: production=${prod}`);
78
79
  if (prod) {
79
80
  // Set production environment
80
81
  process.env['NODE_ENV'] = 'production';
81
- console.log("Running build with production environment");
82
+ logger_1.default.info("handleBuild", "Running build with production environment");
82
83
  // Run the build command
83
84
  runCommand(['run', 'build-prod'], productionEnv);
84
85
  }
85
86
  else {
86
- console.log("Running build with development environment");
87
+ logger_1.default.info("handleBuild", "Running build with development environment");
87
88
  // Prompt the user to ask if they want to open the build in a browser tab
88
89
  const { openInBrowser } = await inquirer_1.default.prompt([
89
90
  {
@@ -93,14 +94,14 @@ const handleBuild = async (prod) => {
93
94
  default: false,
94
95
  },
95
96
  ]);
96
- console.log(`User opted for opening in browser: ${openInBrowser}`);
97
+ logger_1.default.info("handleBuild", `User opted for opening in browser: ${openInBrowser}`);
97
98
  const commandArr = ['run', 'dev'];
98
99
  if (openInBrowser) {
99
100
  // If the user wants to open the build in a browser, run the build with
100
101
  // puppeteer
101
102
  commandArr[1] = 'dev-puppeteer';
102
103
  }
103
- console.log(`Running command: ${commandArr.join(', ')}`);
104
+ logger_1.default.info("handleBuild", `Running command: ${commandArr.join(', ')}`);
104
105
  // Run the build command
105
106
  runCommand(commandArr, productionEnv);
106
107
  // TO_DO: verify
@@ -114,20 +115,20 @@ const handleBuild = async (prod) => {
114
115
  * @returns {Promise<void>}
115
116
  */
116
117
  const executeCommand = async () => {
117
- console.log("Entering executeCommand");
118
+ logger_1.default.info("executeCommand", "Entering executeCommand");
118
119
  // Check if .env file is present
119
120
  // Get the command options
120
121
  const options = await setupCommander();
121
122
  if (options.command !== 'init')
122
123
  checkEnvFile();
123
- console.log(`Options: ${JSON.stringify(options)}`);
124
+ logger_1.default.info("executeCommand", `Options: ${JSON.stringify(options)}`);
124
125
  /**
125
126
  * Logs a message if verbose mode is enabled
126
127
  * @param {string} message - The message to log
127
128
  */
128
129
  const verboseLog = (message) => {
129
130
  if (options.verbose) {
130
- console.log(`[VERBOSE] ${message}`);
131
+ logger_1.default.info("verbose", message);
131
132
  }
132
133
  };
133
134
  switch (options.command) {
@@ -154,12 +155,12 @@ const executeCommand = async () => {
154
155
  process.exit(0);
155
156
  break;
156
157
  }
157
- console.log("Exiting executeCommand");
158
+ logger_1.default.info("executeCommand", "Exiting executeCommand");
158
159
  };
159
160
  // Print command help
160
161
  const printCommandHelp = async () => {
161
162
  const help = await (0, config_1.getHelpInfo)();
162
- console.log(help);
163
+ logger_1.default.info("printCommandHelp", help);
163
164
  process.exit(0);
164
165
  };
165
166
  /**
@@ -176,7 +177,7 @@ const main = async () => {
176
177
  }
177
178
  catch (error) {
178
179
  // Log the error message if the command fails
179
- console.error(error.message);
180
+ logger_1.default.error("main", error.message);
180
181
  // Exit with code 1 if the command fails
181
182
  process.exit(1);
182
183
  }
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const config_1 = require("../constants/config");
4
+ // Initialize verbose setting with a default value
5
+ let isVerbose = false;
6
+ // Set up verbose mode asynchronously
7
+ (0, config_1.getENV)(process.cwd())
8
+ .then(envVars => {
9
+ isVerbose = envVars.VERBOSE === 'true';
10
+ })
11
+ .catch(() => {
12
+ isVerbose = false;
13
+ });
14
+ const logger = {
15
+ MAX_RECORDS: 2000,
16
+ get verbose() {
17
+ return isVerbose;
18
+ },
19
+ // "debug"
20
+ log: function (tag, msg, ...rest) {
21
+ this._log("l", msg, tag, rest);
22
+ },
23
+ // "info"
24
+ info: function (tag, msg, ...rest) {
25
+ this._log("i", msg, tag, rest);
26
+ },
27
+ // "warn"
28
+ warn: function (tag, msg, ...rest) {
29
+ this._log("w", msg, tag, rest);
30
+ },
31
+ // "error"
32
+ error: function (tag, msg, ...rest) {
33
+ this._log("e", msg, tag, rest);
34
+ },
35
+ _log: function (level, msg, tag, ...rest) {
36
+ const origMsg = msg;
37
+ if (rest.length) {
38
+ msg = msg + " " + rest.join("\n");
39
+ }
40
+ let record;
41
+ tag = tag || null;
42
+ record = ((tag != null) ? "[" + tag + "] " + msg : msg);
43
+ const time = (new Date).toLocaleDateString() + " " + (new Date).toLocaleTimeString();
44
+ record = time + " " + record;
45
+ if (logger.verbose) {
46
+ const colors = {
47
+ reset: "\x1b[0m",
48
+ bright: "\x1b[1m",
49
+ dim: "\x1b[2m",
50
+ time: "\x1b[36m", // cyan
51
+ tag: "\x1b[35m", // magenta
52
+ message: "\x1b[37m", // white
53
+ error: "\x1b[31m", // red
54
+ warn: "\x1b[33m", // yellow
55
+ info: "\x1b[32m", // green
56
+ debug: "\x1b[34m" // blue
57
+ };
58
+ const coloredTime = `${colors.time}${time}${colors.reset}`;
59
+ const coloredTag = tag ? `${colors.tag}[${tag}]${colors.reset}` : '';
60
+ switch (level) {
61
+ case "l":
62
+ console.log(coloredTime, coloredTag, `${colors.debug}${origMsg}${colors.reset}`, rest.join(" "));
63
+ break;
64
+ case "i":
65
+ console.info(coloredTime, coloredTag, `${colors.info}${origMsg}${colors.reset}`, rest.join(" "));
66
+ break;
67
+ case "w":
68
+ console.warn(coloredTime, coloredTag, `${colors.warn}${origMsg}${colors.reset}`, rest.join(" "));
69
+ break;
70
+ case "e":
71
+ console.error(coloredTime, coloredTag, `${colors.error}${origMsg}${colors.reset}`, rest.join(" "));
72
+ break;
73
+ }
74
+ }
75
+ }
76
+ };
77
+ exports.default = logger;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "at-builder",
3
- "version": "1.1.6",
3
+ "version": "1.1.7",
4
4
  "main": "bin/index.js",
5
5
  "bin": {
6
6
  "atb": "bin/index.js"
@@ -80,6 +80,7 @@ TARGET_URL=""
80
80
  LOGIN_URL=""
81
81
  VARIATION="Variation-1"
82
82
  NODE_ENV="development"
83
+ VERBOSE=false
83
84
  `;
84
85
  // Write the content to the .env file
85
86
  fs.writeFileSync(envPath, envContent.trim(), 'utf8');
@@ -108,4 +109,42 @@ const createWatchConfig = (basePath) => {
108
109
  } else {
109
110
  console.log('watch-config.json file already exists!');
110
111
  }
111
- }
112
+ }
113
+
114
+ /**
115
+ * Reads and returns environment variables from the specified .env file
116
+ * @param {string} basePath - The base path where the .env file is located
117
+ * @returns {Promise<Object>} Object containing environment variables
118
+ */
119
+ export const getENV = async (basePath: string) => {
120
+ const envPath = path.join(basePath, '.env');
121
+ try {
122
+ // Check if .env file exists
123
+ if (!fs.existsSync(envPath)) {
124
+ throw new Error('.env file not found');
125
+ }
126
+
127
+ // Read the .env file
128
+ const envContent = await fs.promises.readFile(envPath, { encoding: 'utf8' });
129
+
130
+ // Parse the .env file content
131
+ const envVars: { [key: string]: string } = {};
132
+ envContent.split('\n').forEach(line => {
133
+ line = line.trim();
134
+ // Skip empty lines and comments
135
+ if (line && !line.startsWith('#')) {
136
+ const [key, ...valueParts] = line.split('=');
137
+ if (key) {
138
+ const value = valueParts.join('=').trim();
139
+ // Remove quotes if present
140
+ envVars[key.trim()] = value.replace(/^["'](.*)["']$/, '$1');
141
+ }
142
+ }
143
+ });
144
+
145
+ return envVars;
146
+ } catch (error) {
147
+ console.error(clc.red(`Error reading .env file: ${error.message}`));
148
+ throw error;
149
+ }
150
+ };
package/src/index.ts CHANGED
@@ -5,21 +5,21 @@ import fs from "fs";
5
5
  import inquirer from 'inquirer';
6
6
  import { Command } from 'commander';
7
7
  import { getVersion, getHelpInfo, setupEnv } from "./constants/config";
8
-
8
+ import logger from "./services/logger";
9
9
  /**
10
10
  * Checks if the .env file exists at the current working directory
11
11
  *
12
12
  * @throws {Error} If the .env file is not found
13
13
  */
14
14
  const checkEnvFile = () => {
15
- console.log("Checking if .env file exists at current working directory");
15
+ logger.info("checkEnvFile", "Checking if .env file exists at current working directory");
16
16
  try {
17
17
  // Check if the file exists and is readable
18
18
  fs.accessSync(path.join(process.cwd(), ".env"), fs.constants.R_OK);
19
- console.log(".env file found");
19
+ logger.info("checkEnvFile", ".env file found");
20
20
  } catch (error) {
21
21
  // If the file does not exist, throw an error
22
- console.log(`Error: Couldn't find .env file at location ${process.cwd()}`);
22
+ logger.error("checkEnvFile", `Error: Couldn't find .env file at location ${process.cwd()}`);
23
23
  throw error;
24
24
  }
25
25
  };
@@ -32,9 +32,9 @@ const productionEnv = {
32
32
 
33
33
  // Commander setup
34
34
  const setupCommander = async () => {
35
- console.log("Setting up commander");
35
+ logger.info("setupCommander", "Setting up commander");
36
36
  const version = await getVersion();
37
- console.log(`Version: ${version}`);
37
+ logger.info("setupCommander", `Version: ${version}`);
38
38
  const program = new Command();
39
39
  program
40
40
  .version(version, "-V, --version")
@@ -44,7 +44,7 @@ const setupCommander = async () => {
44
44
  .option("-v, --verbose", "Enable verbose logging")
45
45
  .parse(process.argv);
46
46
 
47
- console.log("Commander setup complete");
47
+ logger.info("setupCommander", "Commander setup complete");
48
48
  return program.opts();
49
49
  };
50
50
 
@@ -57,9 +57,9 @@ const setupCommander = async () => {
57
57
  * @param env - The environment object to pass to the spawned process.
58
58
  */
59
59
  const runCommand = (commandArr: string[], env: NodeJS.ProcessEnv): void => {
60
- console.log(`Running npm command [${commandArr.join(", ")}]`);
61
- console.log(`Current working directory: ${process.cwd()}`);
62
- // console.log(`Environment variables: ${JSON.stringify(env, null, 2)}`);
60
+ logger.info("runCommand", `Running npm command [${commandArr.join(", ")}]`);
61
+ logger.info("runCommand", `Current working directory: ${process.cwd()}`);
62
+ // logger.log(`Environment variables: ${JSON.stringify(env, null, 2)}`);
63
63
 
64
64
  // Spawn the command using `npm` with the given environment and current working directory.
65
65
  spawn("npm", commandArr, {
@@ -77,15 +77,15 @@ const runCommand = (commandArr: string[], env: NodeJS.ProcessEnv): void => {
77
77
  * If false, runs the build with development environment.
78
78
  */
79
79
  const handleBuild = async (prod: boolean): Promise<void> => {
80
- console.log(`Handling build with options: production=${prod}`);
80
+ logger.info("handleBuild", `Handling build with options: production=${prod}`);
81
81
  if (prod) {
82
82
  // Set production environment
83
83
  process.env['NODE_ENV'] = 'production';
84
- console.log("Running build with production environment");
84
+ logger.info("handleBuild", "Running build with production environment");
85
85
  // Run the build command
86
86
  runCommand(['run', 'build-prod'], productionEnv);
87
87
  } else {
88
- console.log("Running build with development environment");
88
+ logger.info("handleBuild", "Running build with development environment");
89
89
  // Prompt the user to ask if they want to open the build in a browser tab
90
90
  const { openInBrowser } = await inquirer.prompt([
91
91
  {
@@ -96,7 +96,7 @@ const handleBuild = async (prod: boolean): Promise<void> => {
96
96
  },
97
97
  ]);
98
98
 
99
- console.log(`User opted for opening in browser: ${openInBrowser}`);
99
+ logger.info("handleBuild", `User opted for opening in browser: ${openInBrowser}`);
100
100
  const commandArr = ['run', 'dev'];
101
101
  if (openInBrowser) {
102
102
  // If the user wants to open the build in a browser, run the build with
@@ -104,7 +104,7 @@ const handleBuild = async (prod: boolean): Promise<void> => {
104
104
  commandArr[1] = 'dev-puppeteer';
105
105
  }
106
106
 
107
- console.log(`Running command: ${commandArr.join(', ')}`);
107
+ logger.info("handleBuild", `Running command: ${commandArr.join(', ')}`);
108
108
  // Run the build command
109
109
  runCommand(commandArr, productionEnv);
110
110
  // TO_DO: verify
@@ -119,7 +119,7 @@ const handleBuild = async (prod: boolean): Promise<void> => {
119
119
  * @returns {Promise<void>}
120
120
  */
121
121
  const executeCommand = async () => {
122
- console.log("Entering executeCommand");
122
+ logger.info("executeCommand", "Entering executeCommand");
123
123
  // Check if .env file is present
124
124
  // Get the command options
125
125
  const options = await setupCommander();
@@ -127,14 +127,14 @@ const executeCommand = async () => {
127
127
  if (options.command !== 'init')
128
128
  checkEnvFile();
129
129
 
130
- console.log(`Options: ${JSON.stringify(options)}`);
130
+ logger.info("executeCommand", `Options: ${JSON.stringify(options)}`);
131
131
  /**
132
132
  * Logs a message if verbose mode is enabled
133
133
  * @param {string} message - The message to log
134
134
  */
135
135
  const verboseLog = (message: string) => {
136
136
  if (options.verbose) {
137
- console.log(`[VERBOSE] ${message}`);
137
+ logger.info("verbose", message);
138
138
  }
139
139
  };
140
140
 
@@ -165,13 +165,13 @@ const executeCommand = async () => {
165
165
  process.exit(0);
166
166
  break;
167
167
  }
168
- console.log("Exiting executeCommand");
168
+ logger.info("executeCommand", "Exiting executeCommand");
169
169
  };
170
170
 
171
171
  // Print command help
172
172
  const printCommandHelp = async () => {
173
173
  const help = await getHelpInfo();
174
- console.log(help);
174
+ logger.info("printCommandHelp", help);
175
175
  process.exit(0);
176
176
  };
177
177
 
@@ -188,7 +188,7 @@ const main = async () => {
188
188
  await executeCommand();
189
189
  } catch (error) {
190
190
  // Log the error message if the command fails
191
- console.error(error.message);
191
+ logger.error("main", error.message);
192
192
  // Exit with code 1 if the command fails
193
193
  process.exit(1);
194
194
  }
@@ -0,0 +1,84 @@
1
+ import { getENV } from "../constants/config";
2
+
3
+ // Initialize verbose setting with a default value
4
+ let isVerbose = false;
5
+
6
+ // Set up verbose mode asynchronously
7
+ getENV(process.cwd())
8
+ .then(envVars => {
9
+ isVerbose = envVars.VERBOSE === 'true';
10
+ })
11
+ .catch(() => {
12
+ isVerbose = false;
13
+ });
14
+
15
+ const logger = {
16
+ MAX_RECORDS: 2000,
17
+ get verbose() {
18
+ return isVerbose;
19
+ },
20
+ // "debug"
21
+ log: function (tag, msg, ...rest) {
22
+ this._log("l", msg, tag, rest);
23
+ },
24
+ // "info"
25
+ info: function (tag, msg, ...rest) {
26
+ this._log("i", msg, tag, rest);
27
+ },
28
+ // "warn"
29
+ warn: function (tag, msg, ...rest) {
30
+ this._log("w", msg, tag, rest);
31
+ },
32
+ // "error"
33
+ error: function (tag, msg, ...rest) {
34
+ this._log("e", msg, tag, rest);
35
+ },
36
+ _log: function (level, msg, tag, ...rest) {
37
+ const origMsg = msg;
38
+ if (rest.length) {
39
+ msg = msg + " " + rest.join("\n")
40
+ }
41
+ let record;
42
+ tag = tag || null;
43
+ record = (
44
+ (tag != null) ? "[" + tag + "] " + msg : msg
45
+ );
46
+ const time = (new Date).toLocaleDateString() + " " + (new Date).toLocaleTimeString();
47
+ record = time + " " + record;
48
+
49
+ if(logger.verbose) {
50
+ const colors = {
51
+ reset: "\x1b[0m",
52
+ bright: "\x1b[1m",
53
+ dim: "\x1b[2m",
54
+ time: "\x1b[36m", // cyan
55
+ tag: "\x1b[35m", // magenta
56
+ message: "\x1b[37m", // white
57
+ error: "\x1b[31m", // red
58
+ warn: "\x1b[33m", // yellow
59
+ info: "\x1b[32m", // green
60
+ debug: "\x1b[34m" // blue
61
+ };
62
+
63
+ const coloredTime = `${colors.time}${time}${colors.reset}`;
64
+ const coloredTag = tag ? `${colors.tag}[${tag}]${colors.reset}` : '';
65
+
66
+ switch (level) {
67
+ case "l":
68
+ console.log(coloredTime, coloredTag, `${colors.debug}${origMsg}${colors.reset}`, rest.join(" "));
69
+ break;
70
+ case "i":
71
+ console.info(coloredTime, coloredTag, `${colors.info}${origMsg}${colors.reset}`, rest.join(" "));
72
+ break;
73
+ case "w":
74
+ console.warn(coloredTime, coloredTag, `${colors.warn}${origMsg}${colors.reset}`, rest.join(" "));
75
+ break;
76
+ case "e":
77
+ console.error(coloredTime, coloredTag, `${colors.error}${origMsg}${colors.reset}`, rest.join(" "));
78
+ break;
79
+ }
80
+ }
81
+ }
82
+ };
83
+
84
+ export default logger;