@aneuhold/be-ts-lib 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +3 -0
  2. package/lib/index.d.ts +11 -0
  3. package/lib/index.d.ts.map +1 -0
  4. package/lib/index.js +48 -0
  5. package/lib/services/CLIService.d.ts +69 -0
  6. package/lib/services/CLIService.d.ts.map +1 -0
  7. package/lib/services/CLIService.js +193 -0
  8. package/lib/services/ConfigService/ConfigService.d.ts +25 -0
  9. package/lib/services/ConfigService/ConfigService.d.ts.map +1 -0
  10. package/lib/services/ConfigService/ConfigService.js +69 -0
  11. package/lib/services/ConfigService/ConfigService.spec.d.ts +2 -0
  12. package/lib/services/ConfigService/ConfigService.spec.d.ts.map +1 -0
  13. package/lib/services/ConfigService/ConfigService.spec.js +28 -0
  14. package/lib/services/applications/ChromeService.d.ts +20 -0
  15. package/lib/services/applications/ChromeService.d.ts.map +1 -0
  16. package/lib/services/applications/ChromeService.js +60 -0
  17. package/lib/services/applications/DockerService.d.ts +21 -0
  18. package/lib/services/applications/DockerService.d.ts.map +1 -0
  19. package/lib/services/applications/DockerService.js +87 -0
  20. package/lib/services/applications/ITermService.d.ts +8 -0
  21. package/lib/services/applications/ITermService.d.ts.map +1 -0
  22. package/lib/services/applications/ITermService.js +45 -0
  23. package/lib/services/applications/OSFileSystemService.d.ts +19 -0
  24. package/lib/services/applications/OSFileSystemService.d.ts.map +1 -0
  25. package/lib/services/applications/OSFileSystemService.js +90 -0
  26. package/lib/utils/CurrentEnv.d.ts +63 -0
  27. package/lib/utils/CurrentEnv.d.ts.map +1 -0
  28. package/lib/utils/CurrentEnv.js +137 -0
  29. package/lib/utils/OsaScriptBuilder.d.ts +45 -0
  30. package/lib/utils/OsaScriptBuilder.d.ts.map +1 -0
  31. package/lib/utils/OsaScriptBuilder.js +53 -0
  32. package/package.json +56 -0
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # Personal Backend TypeScript Library
2
+
3
+ This is a library meant to contain any common code between backend TypeScript projects.
package/lib/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { sleep } from '@aneuhold/core-ts-lib';
2
+ import CLIService from './services/CLIService';
3
+ import ChromeService from './services/applications/ChromeService';
4
+ import DockerService from './services/applications/DockerService';
5
+ import OSFileSystemService from './services/applications/OSFileSystemService';
6
+ import CurrentEnv, { OperatingSystemType, ShellType, TerminalType } from './utils/CurrentEnv';
7
+ import ITermService from './services/applications/ITermService';
8
+ import ConfigService from './services/ConfigService/ConfigService';
9
+ export { CLIService, CurrentEnv, ChromeService, DockerService, OSFileSystemService, sleep, OperatingSystemType, ShellType, TerminalType, ITermService, ConfigService };
10
+ export type {};
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,UAAU,MAAM,uBAAuB,CAAC;AAC/C,OAAO,aAAa,MAAM,uCAAuC,CAAC;AAClE,OAAO,aAAa,MAAM,uCAAuC,CAAC;AAClE,OAAO,mBAAmB,MAAM,6CAA6C,CAAC;AAC9E,OAAO,UAAU,EAAE,EACjB,mBAAmB,EACnB,SAAS,EACT,YAAY,EACb,MAAM,oBAAoB,CAAC;AAC5B,OAAO,YAAY,MAAM,sCAAsC,CAAC;AAChE,OAAO,aAAa,MAAM,wCAAwC,CAAC;AAGnE,OAAO,EACL,UAAU,EACV,UAAU,EACV,aAAa,EACb,aAAa,EACb,mBAAmB,EACnB,KAAK,EACL,mBAAmB,EACnB,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,aAAa,EACd,CAAC;AAGF,YAAY,EAAE,CAAC"}
package/lib/index.js ADDED
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.ConfigService = exports.ITermService = exports.TerminalType = exports.ShellType = exports.OperatingSystemType = exports.sleep = exports.OSFileSystemService = exports.DockerService = exports.ChromeService = exports.CurrentEnv = exports.CLIService = void 0;
30
+ const core_ts_lib_1 = require("@aneuhold/core-ts-lib");
31
+ Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return core_ts_lib_1.sleep; } });
32
+ const CLIService_1 = __importDefault(require("./services/CLIService"));
33
+ exports.CLIService = CLIService_1.default;
34
+ const ChromeService_1 = __importDefault(require("./services/applications/ChromeService"));
35
+ exports.ChromeService = ChromeService_1.default;
36
+ const DockerService_1 = __importDefault(require("./services/applications/DockerService"));
37
+ exports.DockerService = DockerService_1.default;
38
+ const OSFileSystemService_1 = __importDefault(require("./services/applications/OSFileSystemService"));
39
+ exports.OSFileSystemService = OSFileSystemService_1.default;
40
+ const CurrentEnv_1 = __importStar(require("./utils/CurrentEnv"));
41
+ exports.CurrentEnv = CurrentEnv_1.default;
42
+ Object.defineProperty(exports, "OperatingSystemType", { enumerable: true, get: function () { return CurrentEnv_1.OperatingSystemType; } });
43
+ Object.defineProperty(exports, "ShellType", { enumerable: true, get: function () { return CurrentEnv_1.ShellType; } });
44
+ Object.defineProperty(exports, "TerminalType", { enumerable: true, get: function () { return CurrentEnv_1.TerminalType; } });
45
+ const ITermService_1 = __importDefault(require("./services/applications/ITermService"));
46
+ exports.ITermService = ITermService_1.default;
47
+ const ConfigService_1 = __importDefault(require("./services/ConfigService/ConfigService"));
48
+ exports.ConfigService = ConfigService_1.default;
@@ -0,0 +1,69 @@
1
+ type ExecCmdReturnType = {
2
+ didComplete: boolean;
3
+ output: string;
4
+ };
5
+ /**
6
+ * A service which can be used to interact with the command line on the current
7
+ * system.
8
+ */
9
+ export default class CLIService {
10
+ private static POWERSHELL_PREFIX;
11
+ /**
12
+ * Executes the given command in a shell environment. Spins up a separate
13
+ * process to execute the command and returns a promise once it is completely
14
+ * finished.
15
+ *
16
+ * The shell environment chosen is determined by the `CurrentEnv` class.
17
+ *
18
+ * @param cmd the command to run. This is ran as a normal execution where the
19
+ * output is all returned at once after completion. For example this could be
20
+ * `ls -a`.
21
+ *
22
+ * @param logError if set to false, it will not output a log if an error
23
+ * occurs in `stderr` when executing the function. This can be useful if
24
+ * a command regularly outputs an error even when it succeeds. This only
25
+ * applies to commands ran with normal execution.
26
+ *
27
+ * @param cwd the current working directory to run the command in. If not
28
+ * provided, it will use the current working directory of the process.
29
+ *
30
+ * @param useProfile if set to true will use the current profile or zshrc of
31
+ * the shell environment. By default this is false.
32
+ *
33
+ * @returns an object that holds the output and true if the command completed
34
+ * successfully or false if it did not.
35
+ */
36
+ static execCmd(cmd: string, logError?: boolean, cwd?: string, useProfile?: boolean): Promise<ExecCmdReturnType>;
37
+ /**
38
+ * Executes the given command but fulfills the
39
+ * promise when either the command completes, or the given number of ms have
40
+ * passed. Whichever comes first.
41
+ *
42
+ * @param command the command to execute
43
+ * @param ms the number of milliseconds to wait. This is 5 seconds by default.
44
+ */
45
+ static execCmdWithTimeout(command: string, ms?: number): Promise<ExecCmdReturnType>;
46
+ /**
47
+ * Spawns a new process where the command is ran as a stream where all
48
+ * output is streamed to the console.
49
+ * This is helpful for long-running commands or commands
50
+ * that output a lot of data. For example `yarn` or `npm install`.
51
+ * All of the output from this is logged by default because of the listeners
52
+ * involved. This could be changed in the future though.
53
+ *
54
+ * @param cmd the command to run. This is the the first argument passed to the
55
+ * `spawn` function. For example this could be `npm`.
56
+ * @param args the arguments to pass to the command. For example this could be
57
+ * `['install', 'react']`.
58
+ */
59
+ static spawnCmd(cmd: string, args?: string[], currentWorkingDirectory?: string): Promise<ExecCmdReturnType>;
60
+ /**
61
+ * Gets input from the user on command line.
62
+ *
63
+ * @param promptToUser the prompt that should be provided to the user. Include
64
+ * a newline at the end if you want there to be one.
65
+ */
66
+ static getUserInput(promptToUser: string): Promise<string>;
67
+ }
68
+ export {};
69
+ //# sourceMappingURL=CLIService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CLIService.d.ts","sourceRoot":"","sources":["../../src/services/CLIService.ts"],"names":[],"mappings":"AAWA,KAAK,iBAAiB,GAAG;IAAE,WAAW,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAElE;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,UAAU;IAC7B,OAAO,CAAC,MAAM,CAAC,iBAAiB,CAA+B;IAE/D;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;WACU,OAAO,CAClB,GAAG,EAAE,MAAM,EACX,QAAQ,UAAQ,EAChB,GAAG,CAAC,EAAE,MAAM,EACZ,UAAU,UAAQ,GACjB,OAAO,CAAC,iBAAiB,CAAC;IA6C7B;;;;;;;OAOG;WACU,kBAAkB,CAC7B,OAAO,EAAE,MAAM,EACf,EAAE,SAAO,GACR,OAAO,CAAC,iBAAiB,CAAC;IAU7B;;;;;;;;;;;;OAYG;WACU,QAAQ,CACnB,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,uBAAuB,CAAC,EAAE,MAAM,GAC/B,OAAO,CAAC,iBAAiB,CAAC;IAkC7B;;;;;OAKG;WACU,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAYjE"}
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const child_process_1 = require("child_process");
30
+ const rl = __importStar(require("readline"));
31
+ const util_1 = __importDefault(require("util"));
32
+ const core_ts_lib_1 = require("@aneuhold/core-ts-lib");
33
+ const CurrentEnv_1 = __importStar(require("../utils/CurrentEnv"));
34
+ /**
35
+ * The promisified version of the {@link normalExec} function.
36
+ */
37
+ const execute = util_1.default.promisify(child_process_1.exec);
38
+ /**
39
+ * A service which can be used to interact with the command line on the current
40
+ * system.
41
+ */
42
+ class CLIService {
43
+ static POWERSHELL_PREFIX = `pwsh -NoProfile -Command `;
44
+ /**
45
+ * Executes the given command in a shell environment. Spins up a separate
46
+ * process to execute the command and returns a promise once it is completely
47
+ * finished.
48
+ *
49
+ * The shell environment chosen is determined by the `CurrentEnv` class.
50
+ *
51
+ * @param cmd the command to run. This is ran as a normal execution where the
52
+ * output is all returned at once after completion. For example this could be
53
+ * `ls -a`.
54
+ *
55
+ * @param logError if set to false, it will not output a log if an error
56
+ * occurs in `stderr` when executing the function. This can be useful if
57
+ * a command regularly outputs an error even when it succeeds. This only
58
+ * applies to commands ran with normal execution.
59
+ *
60
+ * @param cwd the current working directory to run the command in. If not
61
+ * provided, it will use the current working directory of the process.
62
+ *
63
+ * @param useProfile if set to true will use the current profile or zshrc of
64
+ * the shell environment. By default this is false.
65
+ *
66
+ * @returns an object that holds the output and true if the command completed
67
+ * successfully or false if it did not.
68
+ */
69
+ static async execCmd(cmd, logError = false, cwd, useProfile = false) {
70
+ const execOptions = {};
71
+ if (cwd) {
72
+ execOptions.cwd = cwd;
73
+ }
74
+ let commandToExecute = cmd;
75
+ // Set the powershell prefix if the current OS is Windows so that
76
+ // the profile is not ran before the command.
77
+ if (CurrentEnv_1.default.os === CurrentEnv_1.OperatingSystemType.Windows && !useProfile) {
78
+ commandToExecute = `${CLIService.POWERSHELL_PREFIX}${cmd}`;
79
+ }
80
+ else if (CurrentEnv_1.default.os === CurrentEnv_1.OperatingSystemType.Windows && useProfile) {
81
+ execOptions.shell = 'pwsh';
82
+ }
83
+ core_ts_lib_1.Logger.verbose.info(`Executing command: ${commandToExecute}`);
84
+ try {
85
+ const { stdout, stderr } = await execute(commandToExecute, execOptions);
86
+ if (stderr) {
87
+ if (logError) {
88
+ core_ts_lib_1.Logger.error(`There was an error executing ${cmd}. Details are printed below:
89
+ ${stderr}`);
90
+ }
91
+ return {
92
+ didComplete: false,
93
+ output: stderr
94
+ };
95
+ }
96
+ core_ts_lib_1.Logger.verbose.info(`Output from stdout is: ${stdout}`);
97
+ return {
98
+ didComplete: true,
99
+ output: stdout
100
+ };
101
+ }
102
+ catch (err) {
103
+ core_ts_lib_1.Logger.verbose
104
+ .error(`There was an error executing the "exec" function. Details are printed below:
105
+ ${err}`);
106
+ return {
107
+ didComplete: false,
108
+ output: err
109
+ };
110
+ }
111
+ }
112
+ /**
113
+ * Executes the given command but fulfills the
114
+ * promise when either the command completes, or the given number of ms have
115
+ * passed. Whichever comes first.
116
+ *
117
+ * @param command the command to execute
118
+ * @param ms the number of milliseconds to wait. This is 5 seconds by default.
119
+ */
120
+ static async execCmdWithTimeout(command, ms = 5000) {
121
+ const sleepPromise = (0, core_ts_lib_1.sleep)(ms).then(() => {
122
+ return {
123
+ didComplete: false,
124
+ output: `Command ended after ${ms} ms.`
125
+ };
126
+ });
127
+ return Promise.any([sleepPromise, CLIService.execCmd(command)]);
128
+ }
129
+ /**
130
+ * Spawns a new process where the command is ran as a stream where all
131
+ * output is streamed to the console.
132
+ * This is helpful for long-running commands or commands
133
+ * that output a lot of data. For example `yarn` or `npm install`.
134
+ * All of the output from this is logged by default because of the listeners
135
+ * involved. This could be changed in the future though.
136
+ *
137
+ * @param cmd the command to run. This is the the first argument passed to the
138
+ * `spawn` function. For example this could be `npm`.
139
+ * @param args the arguments to pass to the command. For example this could be
140
+ * `['install', 'react']`.
141
+ */
142
+ static async spawnCmd(cmd, args, currentWorkingDirectory) {
143
+ return new Promise((resolve) => {
144
+ let output = '';
145
+ const execOptions = {
146
+ cwd: currentWorkingDirectory
147
+ };
148
+ const spawnedCmd = (0, child_process_1.spawn)(cmd, args, execOptions);
149
+ spawnedCmd.on('error', (err) => {
150
+ core_ts_lib_1.Logger.error(`There was an error executing the "spawn" function. Details are printed below:
151
+ ${err}`);
152
+ resolve({
153
+ didComplete: false,
154
+ output: err.toString()
155
+ });
156
+ });
157
+ spawnedCmd.stdout.on('data', (data) => {
158
+ output += data;
159
+ core_ts_lib_1.Logger.info(data, true);
160
+ });
161
+ spawnedCmd.stderr.on('data', (data) => {
162
+ output += data;
163
+ core_ts_lib_1.Logger.info(data, true);
164
+ });
165
+ spawnedCmd.on('close', (exitCode) => {
166
+ core_ts_lib_1.Logger.info(`Command "${cmd}" exited with code ${exitCode}`);
167
+ resolve({
168
+ didComplete: true,
169
+ output
170
+ });
171
+ });
172
+ });
173
+ }
174
+ /**
175
+ * Gets input from the user on command line.
176
+ *
177
+ * @param promptToUser the prompt that should be provided to the user. Include
178
+ * a newline at the end if you want there to be one.
179
+ */
180
+ static async getUserInput(promptToUser) {
181
+ const readline = rl.createInterface({
182
+ input: process.stdin,
183
+ output: process.stdout
184
+ });
185
+ return new Promise((resolve) => {
186
+ readline.question(promptToUser, (input) => {
187
+ readline.close();
188
+ resolve(input);
189
+ });
190
+ });
191
+ }
192
+ }
193
+ exports.default = CLIService;
@@ -0,0 +1,25 @@
1
+ import 'dotenv/config';
2
+ export type ConfigEnv = 'local' | 'dev' | 'prod';
3
+ /**
4
+ * A class which can be used to load configuration into the local environment
5
+ * from a pre-defined location.
6
+ */
7
+ export default class ConfigService {
8
+ private static gitHub;
9
+ static useConfig(env: string): Promise<void>;
10
+ /**
11
+ * Creates a new GitHub client using `CONFIG_GITHUB_TOKEN` from the
12
+ * local environment or .env file.
13
+ */
14
+ private static getGitHubClient;
15
+ /**
16
+ * Inserts the provided configuration into the local environment.
17
+ */
18
+ private static insertPropertiesIntoEnv;
19
+ /**
20
+ * Strips JSON comments from the provided JSON string. Only `//` comments
21
+ * are supported at the moment.
22
+ */
23
+ private static stripJsonComments;
24
+ }
25
+ //# sourceMappingURL=ConfigService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConfigService.d.ts","sourceRoot":"","sources":["../../../src/services/ConfigService/ConfigService.ts"],"names":[],"mappings":"AACA,OAAO,eAAe,CAAC;AAGvB,MAAM,MAAM,SAAS,GAAG,OAAO,GAAG,KAAK,GAAG,MAAM,CAAC;AAEjD;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,aAAa;IAChC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAwB;WAEhC,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAwBlD;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,eAAe;IAY9B;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,uBAAuB;IAUtC;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,iBAAiB,CAG9B;CACH"}
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const octokit_1 = require("octokit");
4
+ require("dotenv/config");
5
+ const core_ts_lib_1 = require("@aneuhold/core-ts-lib");
6
+ /**
7
+ * A class which can be used to load configuration into the local environment
8
+ * from a pre-defined location.
9
+ */
10
+ class ConfigService {
11
+ static gitHub = null;
12
+ static async useConfig(env) {
13
+ if (!ConfigService.gitHub) {
14
+ ConfigService.gitHub = ConfigService.getGitHubClient();
15
+ }
16
+ try {
17
+ const result = await ConfigService.gitHub.rest.repos.getContent({
18
+ mediaType: {
19
+ format: 'raw'
20
+ },
21
+ owner: 'aneuhold',
22
+ repo: 'config',
23
+ path: `${env}.jsonc`
24
+ });
25
+ const strippedJson = ConfigService.stripJsonComments(result.data);
26
+ const config = JSON.parse(strippedJson);
27
+ ConfigService.insertPropertiesIntoEnv(config);
28
+ }
29
+ catch (error) {
30
+ core_ts_lib_1.Logger.error(`Failed to load ${env}.json, error: ${error}`);
31
+ throw error;
32
+ }
33
+ }
34
+ /**
35
+ * Creates a new GitHub client using `CONFIG_GITHUB_TOKEN` from the
36
+ * local environment or .env file.
37
+ */
38
+ static getGitHubClient() {
39
+ const authToken = process.env.CONFIG_GITHUB_TOKEN;
40
+ if (!authToken) {
41
+ throw new Error('No CONFIG_GITHUB_TOKEN key found in environment variables.');
42
+ }
43
+ return new octokit_1.Octokit({
44
+ auth: authToken
45
+ });
46
+ }
47
+ /**
48
+ * Inserts the provided configuration into the local environment.
49
+ */
50
+ static insertPropertiesIntoEnv(config) {
51
+ Object.entries(config).forEach(([key, value]) => {
52
+ if (typeof value === 'object') {
53
+ ConfigService.insertPropertiesIntoEnv(value);
54
+ }
55
+ else {
56
+ process.env[key] = value;
57
+ }
58
+ });
59
+ }
60
+ /**
61
+ * Strips JSON comments from the provided JSON string. Only `//` comments
62
+ * are supported at the moment.
63
+ */
64
+ static stripJsonComments = (jsonString) => {
65
+ const commentRegex = /\/\/(.*)/g;
66
+ return jsonString.replace(commentRegex, '');
67
+ };
68
+ }
69
+ exports.default = ConfigService;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ConfigService.spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConfigService.spec.d.ts","sourceRoot":"","sources":["../../../src/services/ConfigService/ConfigService.spec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const console_1 = require("console");
7
+ const core_ts_lib_1 = require("@aneuhold/core-ts-lib");
8
+ const ConfigService_1 = __importDefault(require("./ConfigService"));
9
+ describe('ConfigService', () => {
10
+ describe('useConfig', () => {
11
+ /**
12
+ * Depends upon a GitHub token being available in the local environment.
13
+ * This will be a local `.env` file with the CONFIG_GITHUB_TOKEN variable
14
+ * set.
15
+ */
16
+ it('should load configuration from GitHub', async () => {
17
+ const env = 'local';
18
+ await ConfigService_1.default.useConfig(env);
19
+ (0, console_1.assert)(process.env.SOME_KEY === 'SOME_VALUE');
20
+ });
21
+ it('should throw an error when loading configuration fails', async () => {
22
+ const env = 'invalid_env';
23
+ core_ts_lib_1.TestUtils.suppressConsole();
24
+ await expect(ConfigService_1.default.useConfig(env)).rejects.toThrow();
25
+ core_ts_lib_1.TestUtils.restoreConsole();
26
+ });
27
+ });
28
+ });
@@ -0,0 +1,20 @@
1
+ import { OperatingSystemType } from '../../utils/CurrentEnv';
2
+ /**
3
+ * A service that provides functionality for interacting with the Chrome
4
+ * browser.
5
+ */
6
+ export default class ChromeService {
7
+ /**
8
+ * Gets the path to the chrome application for the current system given the
9
+ * operating system type.
10
+ *
11
+ * This does include the quotes
12
+ */
13
+ static getChromePath(os: OperatingSystemType): string | null;
14
+ /**
15
+ * Opens and sets pinned tabs in chrome. Still trying to figure out
16
+ * how to get this to work.
17
+ */
18
+ static openAndSetPinnedTabs(): Promise<void>;
19
+ }
20
+ //# sourceMappingURL=ChromeService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChromeService.d.ts","sourceRoot":"","sources":["../../../src/services/applications/ChromeService.ts"],"names":[],"mappings":"AAAA,OAAmB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAGzE;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,aAAa;IAChC;;;;;OAKG;IACH,MAAM,CAAC,aAAa,CAAC,EAAE,EAAE,mBAAmB,GAAG,MAAM,GAAG,IAAI;IAW5D;;;OAGG;WACU,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC;CAOnD"}
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const CurrentEnv_1 = __importStar(require("../../utils/CurrentEnv"));
30
+ const CLIService_1 = __importDefault(require("../CLIService"));
31
+ /**
32
+ * A service that provides functionality for interacting with the Chrome
33
+ * browser.
34
+ */
35
+ class ChromeService {
36
+ /**
37
+ * Gets the path to the chrome application for the current system given the
38
+ * operating system type.
39
+ *
40
+ * This does include the quotes
41
+ */
42
+ static getChromePath(os) {
43
+ switch (os) {
44
+ case CurrentEnv_1.OperatingSystemType.MacOSX:
45
+ return `"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"`;
46
+ case CurrentEnv_1.OperatingSystemType.Windows:
47
+ return `& "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"`;
48
+ default:
49
+ return null;
50
+ }
51
+ }
52
+ /**
53
+ * Opens and sets pinned tabs in chrome. Still trying to figure out
54
+ * how to get this to work.
55
+ */
56
+ static async openAndSetPinnedTabs() {
57
+ await CLIService_1.default.execCmd(`${ChromeService.getChromePath(CurrentEnv_1.default.os)} --pinned-tab-count=2 https://google.com https://tonyneuhold.com`);
58
+ }
59
+ }
60
+ exports.default = ChromeService;
@@ -0,0 +1,21 @@
1
+ import { OperatingSystemType } from '../../utils/CurrentEnv';
2
+ /**
3
+ * A service that provides functionality for interacting with the Docker
4
+ * application.
5
+ */
6
+ export default class DockerService {
7
+ /**
8
+ * Starts the Docker Desktop application. If it is already running, it doesn't
9
+ * do anything.
10
+ */
11
+ static startDockerDesktop(): Promise<void>;
12
+ static checkIfDockerDesktopIsRunning(): Promise<boolean>;
13
+ /**
14
+ * Gets the path to the docker application for the current system given the
15
+ * operating system type.
16
+ *
17
+ * This does include the quotes
18
+ */
19
+ static getDockerPath(os: OperatingSystemType): string | null;
20
+ }
21
+ //# sourceMappingURL=DockerService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DockerService.d.ts","sourceRoot":"","sources":["../../../src/services/applications/DockerService.ts"],"names":[],"mappings":"AAGA,OAAmB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAGzE;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,aAAa;IAChC;;;OAGG;WACU,kBAAkB;WAgBlB,6BAA6B,IAAI,OAAO,CAAC,OAAO,CAAC;IAe9D;;;;;OAKG;IACH,MAAM,CAAC,aAAa,CAAC,EAAE,EAAE,mBAAmB,GAAG,MAAM,GAAG,IAAI;CAS7D"}
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ /* eslint-disable no-await-in-loop */
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || function (mod) {
20
+ if (mod && mod.__esModule) return mod;
21
+ var result = {};
22
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
+ __setModuleDefault(result, mod);
24
+ return result;
25
+ };
26
+ var __importDefault = (this && this.__importDefault) || function (mod) {
27
+ return (mod && mod.__esModule) ? mod : { "default": mod };
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ const core_ts_lib_1 = require("@aneuhold/core-ts-lib");
31
+ const CurrentEnv_1 = __importStar(require("../../utils/CurrentEnv"));
32
+ const CLIService_1 = __importDefault(require("../CLIService"));
33
+ /**
34
+ * A service that provides functionality for interacting with the Docker
35
+ * application.
36
+ */
37
+ class DockerService {
38
+ /**
39
+ * Starts the Docker Desktop application. If it is already running, it doesn't
40
+ * do anything.
41
+ */
42
+ static async startDockerDesktop() {
43
+ const currentOS = CurrentEnv_1.default.os;
44
+ const dockerPath = DockerService.getDockerPath(currentOS);
45
+ let dockerRunning = await DockerService.checkIfDockerDesktopIsRunning();
46
+ if (!dockerRunning && dockerPath) {
47
+ core_ts_lib_1.Logger.info('Docker desktop is not running. Starting it now...');
48
+ await CLIService_1.default.execCmdWithTimeout(dockerPath, 4000);
49
+ while (!dockerRunning) {
50
+ core_ts_lib_1.Logger.info('Waiting for Docker to start...');
51
+ await (0, core_ts_lib_1.sleep)(2000);
52
+ dockerRunning = await DockerService.checkIfDockerDesktopIsRunning();
53
+ }
54
+ }
55
+ core_ts_lib_1.Logger.info('Docker desktop is running.');
56
+ }
57
+ static async checkIfDockerDesktopIsRunning() {
58
+ const currentOS = CurrentEnv_1.default.os;
59
+ if (currentOS === CurrentEnv_1.OperatingSystemType.Windows) {
60
+ const { didComplete } = await CLIService_1.default.execCmd('Get-Process docker');
61
+ if (didComplete) {
62
+ core_ts_lib_1.Logger.verbose.info('Docker is running.');
63
+ return true;
64
+ }
65
+ core_ts_lib_1.Logger.verbose.info('Docker is not running.');
66
+ return false;
67
+ }
68
+ core_ts_lib_1.Logger.error('Docker command not defined for this OS yet.');
69
+ return false;
70
+ }
71
+ /**
72
+ * Gets the path to the docker application for the current system given the
73
+ * operating system type.
74
+ *
75
+ * This does include the quotes
76
+ */
77
+ static getDockerPath(os) {
78
+ switch (os) {
79
+ case CurrentEnv_1.OperatingSystemType.Windows:
80
+ return `& "C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe"`;
81
+ default:
82
+ core_ts_lib_1.Logger.error('Docker path not defined for this OS yet.');
83
+ return null;
84
+ }
85
+ }
86
+ }
87
+ exports.default = DockerService;
@@ -0,0 +1,8 @@
1
+ export default class ITermService {
2
+ /**
3
+ * Splits the iTerm terminal horzontally and runs each command in a separate
4
+ * pane.
5
+ */
6
+ static splitHorizontallyAndRunCommands(commands: string[], cwd?: string): Promise<void>;
7
+ }
8
+ //# sourceMappingURL=ITermService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ITermService.d.ts","sourceRoot":"","sources":["../../../src/services/applications/ITermService.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,OAAO,OAAO,YAAY;IAC/B;;;OAGG;WACU,+BAA+B,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,GAAG,SAAK;CAmC1E"}
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const core_ts_lib_1 = require("@aneuhold/core-ts-lib");
7
+ const OsaScriptBuilder_1 = __importDefault(require("../../utils/OsaScriptBuilder"));
8
+ const CLIService_1 = __importDefault(require("../CLIService"));
9
+ class ITermService {
10
+ /**
11
+ * Splits the iTerm terminal horzontally and runs each command in a separate
12
+ * pane.
13
+ */
14
+ static async splitHorizontallyAndRunCommands(commands, cwd = '') {
15
+ const terminalWindowTellBlock = {
16
+ tellCommand: `W's current session`,
17
+ sections: []
18
+ };
19
+ // Do the number of splits needed
20
+ commands.forEach(() => {
21
+ terminalWindowTellBlock.sections.push(`split horizontally with default profile`);
22
+ });
23
+ const iTermApplicationTellBlock = {
24
+ tellCommand: 'application "iTerm"',
25
+ sections: [
26
+ 'activate',
27
+ 'set W to current window',
28
+ 'if W = missing value then set W to create window with default profile',
29
+ terminalWindowTellBlock,
30
+ `set T to W's current tab`
31
+ ]
32
+ };
33
+ // Add in the commands, adding 2 to the session number because the first
34
+ // session is 1, and the second is 2.
35
+ commands.forEach((command, i) => {
36
+ iTermApplicationTellBlock.sections.push(`write T's session ${i + 2} text "cd ${cwd} && ${command}"`);
37
+ });
38
+ const osaScriptBuilder = new OsaScriptBuilder_1.default();
39
+ osaScriptBuilder.addTellBlock(iTermApplicationTellBlock);
40
+ const osaScript = osaScriptBuilder.getFullCommand();
41
+ core_ts_lib_1.Logger.verbose.info(`OsaScript: ${osaScript}`);
42
+ await CLIService_1.default.execCmd(osaScript);
43
+ }
44
+ }
45
+ exports.default = ITermService;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A service which can be used to interact with the file system application on
3
+ * the current system.
4
+ */
5
+ export default class OSFileSystemService {
6
+ static openNugetCache(): Promise<void>;
7
+ /**
8
+ * Tries to add the provided snippet of text to the path provided. If the file
9
+ * doesn't exist, it creates it. If the folders to the file don't exist, it
10
+ * creates those. If the text already exists in the file, it does nothing.
11
+ *
12
+ * @param folderPath the path to the folder which contains the file that should
13
+ * be updated
14
+ */
15
+ static findAndInsertText(folderPath: string, fileName: string, textToInsert: string): Promise<void>;
16
+ private static openWindowsNugetCache;
17
+ private static openMacNugetCache;
18
+ }
19
+ //# sourceMappingURL=OSFileSystemService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OSFileSystemService.d.ts","sourceRoot":"","sources":["../../../src/services/applications/OSFileSystemService.ts"],"names":[],"mappings":"AAMA;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,mBAAmB;WACzB,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAY5C;;;;;;;OAOG;WACU,iBAAiB,CAC5B,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC;mBAsBK,qBAAqB;mBAOrB,iBAAiB;CAMvC"}
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const promises_1 = require("fs/promises");
30
+ const path_1 = __importDefault(require("path"));
31
+ const core_ts_lib_1 = require("@aneuhold/core-ts-lib");
32
+ const CurrentEnv_1 = __importStar(require("../../utils/CurrentEnv"));
33
+ const CLIService_1 = __importDefault(require("../CLIService"));
34
+ /**
35
+ * A service which can be used to interact with the file system application on
36
+ * the current system.
37
+ */
38
+ class OSFileSystemService {
39
+ static async openNugetCache() {
40
+ if (CurrentEnv_1.default.os === CurrentEnv_1.OperatingSystemType.Windows) {
41
+ await OSFileSystemService.openWindowsNugetCache();
42
+ return;
43
+ }
44
+ if (CurrentEnv_1.default.os === CurrentEnv_1.OperatingSystemType.MacOSX) {
45
+ await OSFileSystemService.openMacNugetCache();
46
+ return;
47
+ }
48
+ core_ts_lib_1.Logger.error('Not implemented for this OS yet.');
49
+ }
50
+ /**
51
+ * Tries to add the provided snippet of text to the path provided. If the file
52
+ * doesn't exist, it creates it. If the folders to the file don't exist, it
53
+ * creates those. If the text already exists in the file, it does nothing.
54
+ *
55
+ * @param folderPath the path to the folder which contains the file that should
56
+ * be updated
57
+ */
58
+ static async findAndInsertText(folderPath, fileName, textToInsert) {
59
+ const filePath = path_1.default.join(folderPath, fileName);
60
+ await core_ts_lib_1.FileSystemService.checkOrCreateFolder(folderPath);
61
+ try {
62
+ await (0, promises_1.access)(filePath);
63
+ const fileContents = await (0, promises_1.readFile)(filePath);
64
+ if (!fileContents.includes(textToInsert)) {
65
+ await (0, promises_1.appendFile)(filePath, `\n${textToInsert}`);
66
+ core_ts_lib_1.Logger.info(`Added "${textToInsert}" to "${filePath}"`);
67
+ }
68
+ else {
69
+ core_ts_lib_1.Logger.info(`"${textToInsert}" already exists in "${filePath}"`);
70
+ }
71
+ }
72
+ catch {
73
+ core_ts_lib_1.Logger.info(`File at "${filePath}" didn't exist. Creating it now and adding "${textToInsert}" to it.`);
74
+ await (0, promises_1.writeFile)(filePath, textToInsert);
75
+ }
76
+ }
77
+ static async openWindowsNugetCache() {
78
+ await Promise.all([
79
+ CLIService_1.default.execCmd(`ii $HOME/localNuget`),
80
+ CLIService_1.default.execCmd(`ii $HOME/.nuget/packages`)
81
+ ]);
82
+ }
83
+ static async openMacNugetCache() {
84
+ await Promise.all([
85
+ CLIService_1.default.execCmd(`open $HOME/localNuget`),
86
+ CLIService_1.default.execCmd(`open $HOME/.nuget/packages`)
87
+ ]);
88
+ }
89
+ }
90
+ exports.default = OSFileSystemService;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The type of shell that the current environment is running.
3
+ */
4
+ export declare enum ShellType {
5
+ PowerShellCore = 0,
6
+ PowerShellDesktop = 1,
7
+ Bash = 2,
8
+ Zsh = 3,
9
+ CommandPrompt = 4,
10
+ Unknown = 5
11
+ }
12
+ export declare enum OperatingSystemType {
13
+ Windows = 0,
14
+ MacOSX = 1,
15
+ Linux = 2,
16
+ Unknown = 3
17
+ }
18
+ /**
19
+ * The type of terminal that the current enviornment is running.
20
+ */
21
+ export declare enum TerminalType {
22
+ WindowsTerminal = 0,
23
+ ITerm2 = 1,
24
+ Unknown = 2
25
+ }
26
+ /**
27
+ * Provides information relevant to the current environment this script is
28
+ * running in.
29
+ */
30
+ export default class CurrentEnv {
31
+ /**
32
+ * Returns the type of terminal the current environment is using.
33
+ */
34
+ static terminal(): TerminalType;
35
+ /**
36
+ * Returns the type of shell the current environment is using.
37
+ *
38
+ * This might be arbitrary because it seems that the exec command will use
39
+ * whatever the default shell is or whatever is specified as the shell
40
+ * option.
41
+ */
42
+ static shell(): Promise<ShellType>;
43
+ /**
44
+ * Gets all file names in the current directory.
45
+ */
46
+ static fileNamesInDir(): Promise<string[]>;
47
+ /**
48
+ * Runs the startup script for the current system. This command exits the
49
+ * package.
50
+ *
51
+ * The startup scripts are defined in the
52
+ * [dotfiles repo](https://github.com/aneuhold/dotfiles).
53
+ */
54
+ static runStartupScript(): Promise<void>;
55
+ /**
56
+ * Determines the type of operating system in the current environment.
57
+ *
58
+ * This looks to be O(1) complexity.
59
+ */
60
+ static get os(): OperatingSystemType;
61
+ static folderName(): string;
62
+ }
63
+ //# sourceMappingURL=CurrentEnv.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CurrentEnv.d.ts","sourceRoot":"","sources":["../../src/utils/CurrentEnv.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,oBAAY,SAAS;IACnB,cAAc,IAAA;IACd,iBAAiB,IAAA;IACjB,IAAI,IAAA;IACJ,GAAG,IAAA;IACH,aAAa,IAAA;IACb,OAAO,IAAA;CACR;AAED,oBAAY,mBAAmB;IAC7B,OAAO,IAAA;IACP,MAAM,IAAA;IACN,KAAK,IAAA;IACL,OAAO,IAAA;CACR;AAED;;GAEG;AACH,oBAAY,YAAY;IACtB,eAAe,IAAA;IACf,MAAM,IAAA;IACN,OAAO,IAAA;CACR;AAED;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,UAAU;IAC7B;;OAEG;WACW,QAAQ,IAAI,YAAY;IAYtC;;;;;;OAMG;WACiB,KAAK,IAAI,OAAO,CAAC,SAAS,CAAC;IAyB/C;;OAEG;WACiB,cAAc,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAIvD;;;;;;OAMG;WACiB,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IAsBrD;;;;OAIG;IACH,WAAkB,EAAE,IAAI,mBAAmB,CAQ1C;WAEa,UAAU,IAAI,MAAM;CAGnC"}
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TerminalType = exports.OperatingSystemType = exports.ShellType = void 0;
7
+ const promises_1 = require("fs/promises");
8
+ const path_1 = __importDefault(require("path"));
9
+ const core_ts_lib_1 = require("@aneuhold/core-ts-lib");
10
+ const CLIService_1 = __importDefault(require("../services/CLIService"));
11
+ /**
12
+ * The type of shell that the current environment is running.
13
+ */
14
+ var ShellType;
15
+ (function (ShellType) {
16
+ ShellType[ShellType["PowerShellCore"] = 0] = "PowerShellCore";
17
+ ShellType[ShellType["PowerShellDesktop"] = 1] = "PowerShellDesktop";
18
+ ShellType[ShellType["Bash"] = 2] = "Bash";
19
+ ShellType[ShellType["Zsh"] = 3] = "Zsh";
20
+ ShellType[ShellType["CommandPrompt"] = 4] = "CommandPrompt";
21
+ ShellType[ShellType["Unknown"] = 5] = "Unknown";
22
+ })(ShellType || (exports.ShellType = ShellType = {}));
23
+ var OperatingSystemType;
24
+ (function (OperatingSystemType) {
25
+ OperatingSystemType[OperatingSystemType["Windows"] = 0] = "Windows";
26
+ OperatingSystemType[OperatingSystemType["MacOSX"] = 1] = "MacOSX";
27
+ OperatingSystemType[OperatingSystemType["Linux"] = 2] = "Linux";
28
+ OperatingSystemType[OperatingSystemType["Unknown"] = 3] = "Unknown";
29
+ })(OperatingSystemType || (exports.OperatingSystemType = OperatingSystemType = {}));
30
+ /**
31
+ * The type of terminal that the current enviornment is running.
32
+ */
33
+ var TerminalType;
34
+ (function (TerminalType) {
35
+ TerminalType[TerminalType["WindowsTerminal"] = 0] = "WindowsTerminal";
36
+ TerminalType[TerminalType["ITerm2"] = 1] = "ITerm2";
37
+ TerminalType[TerminalType["Unknown"] = 2] = "Unknown";
38
+ })(TerminalType || (exports.TerminalType = TerminalType = {}));
39
+ /**
40
+ * Provides information relevant to the current environment this script is
41
+ * running in.
42
+ */
43
+ class CurrentEnv {
44
+ /**
45
+ * Returns the type of terminal the current environment is using.
46
+ */
47
+ static terminal() {
48
+ // See https://stackoverflow.com/questions/59733731/how-to-detect-if-running-in-the-new-windows-terminal
49
+ // for information on why this method was chosen.
50
+ if (process.env.WT_SESSION) {
51
+ return TerminalType.WindowsTerminal;
52
+ }
53
+ if (process.env.TERM_PROGRAM && process.env.TERM_PROGRAM === 'iTerm.app') {
54
+ return TerminalType.ITerm2;
55
+ }
56
+ return TerminalType.Unknown;
57
+ }
58
+ /**
59
+ * Returns the type of shell the current environment is using.
60
+ *
61
+ * This might be arbitrary because it seems that the exec command will use
62
+ * whatever the default shell is or whatever is specified as the shell
63
+ * option.
64
+ */
65
+ static async shell() {
66
+ const currentOs = CurrentEnv.os;
67
+ if (currentOs === OperatingSystemType.Windows) {
68
+ // Command comes from: https://stackoverflow.com/questions/34471956/how-to-determine-if-im-in-powershell-or-cmd
69
+ const { output } = await CLIService_1.default.execCmd('(dir 2>&1 *`|echo CMD);&<# rem #>echo ($PSVersionTable).PSEdition');
70
+ switch (output) {
71
+ case 'CMD':
72
+ return ShellType.CommandPrompt;
73
+ case 'Desktop':
74
+ return ShellType.PowerShellDesktop;
75
+ case 'Core':
76
+ return ShellType.PowerShellCore;
77
+ default:
78
+ core_ts_lib_1.Logger.verbose.failure(`No recognizable shell returned for Windows environment.`);
79
+ }
80
+ }
81
+ else if (currentOs === OperatingSystemType.MacOSX) {
82
+ // Mighbt want to use process.env.SHELL for Linux environments
83
+ }
84
+ return ShellType.Unknown;
85
+ }
86
+ /**
87
+ * Gets all file names in the current directory.
88
+ */
89
+ static async fileNamesInDir() {
90
+ return (0, promises_1.readdir)(path_1.default.resolve('.'));
91
+ }
92
+ /**
93
+ * Runs the startup script for the current system. This command exits the
94
+ * package.
95
+ *
96
+ * The startup scripts are defined in the
97
+ * [dotfiles repo](https://github.com/aneuhold/dotfiles).
98
+ */
99
+ static async runStartupScript() {
100
+ let cmd = '';
101
+ if (CurrentEnv.os === OperatingSystemType.Windows) {
102
+ // & says to powershell that you actually want to run the script in the
103
+ // quotes afterwards
104
+ // Also just running the startup script for now because of some infinite
105
+ // loop issues with specifying arguments
106
+ cmd = `& "$Home\\startup.ps1"`;
107
+ }
108
+ else {
109
+ cmd = 'zsh';
110
+ const args = ['startup.sh'];
111
+ await CLIService_1.default.spawnCmd(cmd, args, process.env.HOME);
112
+ return;
113
+ }
114
+ core_ts_lib_1.Logger.info(`Executing the following command: "${cmd}"`);
115
+ const { output } = await CLIService_1.default.execCmd(cmd);
116
+ core_ts_lib_1.Logger.info(output);
117
+ process.exit();
118
+ }
119
+ /**
120
+ * Determines the type of operating system in the current environment.
121
+ *
122
+ * This looks to be O(1) complexity.
123
+ */
124
+ static get os() {
125
+ if (process.platform === 'win32') {
126
+ return OperatingSystemType.Windows;
127
+ }
128
+ if (process.platform === 'darwin') {
129
+ return OperatingSystemType.MacOSX;
130
+ }
131
+ return OperatingSystemType.Unknown;
132
+ }
133
+ static folderName() {
134
+ return path_1.default.basename(path_1.default.resolve('.'));
135
+ }
136
+ }
137
+ exports.default = CurrentEnv;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * A `tell` block that can be executed in an OSA script.
3
+ */
4
+ export type OsaScriptTellBlock = {
5
+ /**
6
+ * The command that goes after the `tell` keyword in the first line of the
7
+ * block.
8
+ */
9
+ tellCommand: string;
10
+ sections: OsaScriptSection[];
11
+ };
12
+ /**
13
+ * A plain command that can be executed in an OSA script.
14
+ */
15
+ export type OsaScriptCommand = string;
16
+ export type OsaScriptSection = OsaScriptTellBlock | OsaScriptCommand;
17
+ export default class OsaScriptBuilder {
18
+ private currentScript;
19
+ /**
20
+ * There's no need to escape single quotes with this. That is already done
21
+ * in the class.
22
+ */
23
+ addCommand(command: string): void;
24
+ /**
25
+ * There's no need to escape single quotes with this. That is already done
26
+ * in the class.
27
+ */
28
+ addTellBlock(tellBlock: OsaScriptTellBlock): void;
29
+ /**
30
+ * Generates the full command that should be pasted as-is into a terminal.
31
+ *
32
+ * This will automatically escape any single quotes appropriately that were
33
+ * provided.
34
+ */
35
+ getFullCommand(): string;
36
+ private stringifySection;
37
+ /**
38
+ * Single quotes are escaped by splitting the string in two, then adding a
39
+ * single quote to the end of the first half, and combining the two halves.
40
+ *
41
+ * By putting no space inbetween the two halves, the two halves are combined.
42
+ */
43
+ private static escapeSingleQuotes;
44
+ }
45
+ //# sourceMappingURL=OsaScriptBuilder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OsaScriptBuilder.d.ts","sourceRoot":"","sources":["../../src/utils/OsaScriptBuilder.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,gBAAgB,EAAE,CAAC;CAC9B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEtC,MAAM,MAAM,gBAAgB,GAAG,kBAAkB,GAAG,gBAAgB,CAAC;AAErE,MAAM,CAAC,OAAO,OAAO,gBAAgB;IACnC,OAAO,CAAC,aAAa,CAA0B;IAE/C;;;OAGG;IACI,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAIxC;;;OAGG;IACI,YAAY,CAAC,SAAS,EAAE,kBAAkB,GAAG,IAAI;IAIxD;;;;;OAKG;IACH,cAAc,IAAI,MAAM;IAQxB,OAAO,CAAC,gBAAgB;IAcxB;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,kBAAkB;CAGlC"}
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class OsaScriptBuilder {
4
+ currentScript = [];
5
+ /**
6
+ * There's no need to escape single quotes with this. That is already done
7
+ * in the class.
8
+ */
9
+ addCommand(command) {
10
+ this.currentScript.push(command);
11
+ }
12
+ /**
13
+ * There's no need to escape single quotes with this. That is already done
14
+ * in the class.
15
+ */
16
+ addTellBlock(tellBlock) {
17
+ this.currentScript.push(tellBlock);
18
+ }
19
+ /**
20
+ * Generates the full command that should be pasted as-is into a terminal.
21
+ *
22
+ * This will automatically escape any single quotes appropriately that were
23
+ * provided.
24
+ */
25
+ getFullCommand() {
26
+ let stringifiedScript = `osascript`;
27
+ this.currentScript.forEach((section) => {
28
+ stringifiedScript += this.stringifySection(section);
29
+ });
30
+ return stringifiedScript;
31
+ }
32
+ stringifySection(section) {
33
+ if (typeof section === 'string') {
34
+ return ` -e '${OsaScriptBuilder.escapeSingleQuotes(section)}'`;
35
+ }
36
+ let stringifiedSection = ` -e 'tell ${OsaScriptBuilder.escapeSingleQuotes(section.tellCommand)}'`;
37
+ section.sections.forEach((subSection) => {
38
+ stringifiedSection += this.stringifySection(subSection);
39
+ });
40
+ stringifiedSection += ` -e 'end tell'`;
41
+ return stringifiedSection;
42
+ }
43
+ /**
44
+ * Single quotes are escaped by splitting the string in two, then adding a
45
+ * single quote to the end of the first half, and combining the two halves.
46
+ *
47
+ * By putting no space inbetween the two halves, the two halves are combined.
48
+ */
49
+ static escapeSingleQuotes(stringToEscape) {
50
+ return stringToEscape.replace(/'/g, `'\\''`);
51
+ }
52
+ }
53
+ exports.default = OsaScriptBuilder;
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@aneuhold/be-ts-lib",
3
+ "version": "1.0.1",
4
+ "description": "A backend TypeScript library used for common functionality in personal backend projects.",
5
+ "main": "lib/index.js",
6
+ "types": "lib/index.d.ts",
7
+ "author": "Anton G Neuhold Jr <agneuhold@gmail.com>",
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/aneuhold/be-ts-lib.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/aneuhold/be-ts-lib/issues"
15
+ },
16
+ "homepage": "https://github.com/aneuhold/be-ts-lib#readme",
17
+ "files": [
18
+ "lib/**/*"
19
+ ],
20
+ "keywords": [
21
+ "Scripting",
22
+ "Node.js"
23
+ ],
24
+ "scripts": {
25
+ "pushpub": "npm run build && npm version patch && git push && npm publish --access public",
26
+ "build": "tsc",
27
+ "watch": "tsc -w",
28
+ "link:local": "cd lib && yarn link",
29
+ "unlink:local": "cd lib && yarn unlink",
30
+ "upgrade:all": "yarn upgrade --latest",
31
+ "test": "jest"
32
+ },
33
+ "dependencies": {
34
+ "@aneuhold/core-ts-lib": "^1.1.5",
35
+ "node-fetch": "^2",
36
+ "octokit": "^3.1.2",
37
+ "dotenv": "^16.3.1"
38
+ },
39
+ "devDependencies": {
40
+ "@types/jest": "^29.5.8",
41
+ "@types/node": "^20.10.4",
42
+ "@types/node-fetch": "^2.6.9",
43
+ "@typescript-eslint/eslint-plugin": "^6.14.0",
44
+ "@typescript-eslint/parser": "^6.14.0",
45
+ "eslint": "^8.35.0",
46
+ "eslint-config-airbnb-base": "^15.0.0",
47
+ "eslint-config-prettier": "^9.1.0",
48
+ "eslint-plugin-import": "^2.22.1",
49
+ "eslint-plugin-prettier": "^5.0.1",
50
+ "jest": "^29.7.0",
51
+ "prettier": "^3.1.1",
52
+ "ts-jest": "^29.1.1",
53
+ "ts-node": "^10.2.1",
54
+ "typescript": "^5.3.3"
55
+ }
56
+ }