git-truck 0.5.0

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 (74) hide show
  1. package/.eslintrc.json +20 -0
  2. package/.github/workflows/test-and-build.yml +39 -0
  3. package/.husky/pre-commit +4 -0
  4. package/.truckignore +1 -0
  5. package/.vscode/extensions.json +7 -0
  6. package/.vscode/launch.json +24 -0
  7. package/.vscode/settings.json +6 -0
  8. package/LICENSE +21 -0
  9. package/README.md +60 -0
  10. package/app/README.md +46 -0
  11. package/app/entry.client.tsx +4 -0
  12. package/app/entry.server.tsx +27 -0
  13. package/app/parser/.eslintignore +3 -0
  14. package/app/parser/.eslintrc.json +18 -0
  15. package/app/parser/src/TruckIgnore.server.ts +20 -0
  16. package/app/parser/src/constants.ts +1 -0
  17. package/app/parser/src/hydrate.server.ts +199 -0
  18. package/app/parser/src/index.ts +5 -0
  19. package/app/parser/src/log.server.ts +97 -0
  20. package/app/parser/src/model.ts +77 -0
  21. package/app/parser/src/parse.server.ts +276 -0
  22. package/app/parser/src/parse.test.ts +32 -0
  23. package/app/parser/src/queue.ts +86 -0
  24. package/app/parser/src/util.test.ts +8 -0
  25. package/app/parser/src/util.ts +216 -0
  26. package/app/root.tsx +35 -0
  27. package/app/routes/index.tsx +43 -0
  28. package/app/src/authorUnionUtil.test.ts +82 -0
  29. package/app/src/authorUnionUtil.ts +52 -0
  30. package/app/src/components/AuthorDistFragment.tsx +27 -0
  31. package/app/src/components/AuthorDistOther.tsx +24 -0
  32. package/app/src/components/Chart.tsx +362 -0
  33. package/app/src/components/Details.tsx +177 -0
  34. package/app/src/components/EnumSelect.tsx +31 -0
  35. package/app/src/components/GlobalInfo.tsx +17 -0
  36. package/app/src/components/Legend.tsx +65 -0
  37. package/app/src/components/LegendFragment.tsx +29 -0
  38. package/app/src/components/LegendOther.tsx +43 -0
  39. package/app/src/components/Main.tsx +19 -0
  40. package/app/src/components/Options.tsx +24 -0
  41. package/app/src/components/Providers.tsx +121 -0
  42. package/app/src/components/SearchBar.tsx +36 -0
  43. package/app/src/components/SidePanel.tsx +25 -0
  44. package/app/src/components/Spacer.tsx +62 -0
  45. package/app/src/components/Toggle.tsx +21 -0
  46. package/app/src/components/Tooltip.tsx +131 -0
  47. package/app/src/components/util.tsx +150 -0
  48. package/app/src/const.ts +5 -0
  49. package/app/src/contexts/DataContext.ts +12 -0
  50. package/app/src/contexts/MetricContext.ts +14 -0
  51. package/app/src/contexts/OptionsContext.ts +46 -0
  52. package/app/src/contexts/SearchContext.ts +16 -0
  53. package/app/src/extension-color.ts +34 -0
  54. package/app/src/hooks.ts +17 -0
  55. package/app/src/lang-map.d.ts +3 -0
  56. package/app/src/metrics.ts +319 -0
  57. package/app/src/react-app-env.d.ts +1 -0
  58. package/app/src/reportWebVitals.ts +15 -0
  59. package/app/src/setupTests.ts +5 -0
  60. package/app/src/util.ts +33 -0
  61. package/app/styles/App.css +3 -0
  62. package/app/styles/Chart.css +26 -0
  63. package/app/styles/index.css +35 -0
  64. package/app/styles/vars.css +17 -0
  65. package/cli.js +2 -0
  66. package/package.json +99 -0
  67. package/parse.sh +26 -0
  68. package/project-statement.md +43 -0
  69. package/public/favicon.ico +0 -0
  70. package/remix.config.js +21 -0
  71. package/remix.env.d.ts +2 -0
  72. package/server.js +41 -0
  73. package/truckconfig.json +8 -0
  74. package/tsconfig.json +20 -0
package/.eslintrc.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "env": {
3
+ "browser": false,
4
+ "es2021": true
5
+ },
6
+ "extends": [
7
+ "@remix-run/eslint-config",
8
+ "eslint:recommended",
9
+ "plugin:@typescript-eslint/recommended"
10
+ ],
11
+ "parser": "@typescript-eslint/parser",
12
+ "parserOptions": {
13
+ "ecmaVersion": "latest",
14
+ "sourceType": "module"
15
+ },
16
+ "plugins": [
17
+ "@typescript-eslint"
18
+ ]
19
+ }
20
+
@@ -0,0 +1,39 @@
1
+ # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
2
+ # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
3
+
4
+ name: Test and build
5
+
6
+ on:
7
+ push:
8
+ branches: [main]
9
+ pull_request:
10
+ branches: [main]
11
+
12
+ jobs:
13
+ test-and-build:
14
+ runs-on: ubuntu-latest
15
+
16
+ strategy:
17
+ matrix:
18
+ node-version: [16.x, 17.x]
19
+ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
20
+
21
+ steps:
22
+ - uses: actions/checkout@v2
23
+ with:
24
+ fetch-depth: '0'
25
+
26
+ - name: Use Node.js ${{ matrix.node-version }}
27
+ uses: actions/setup-node@v2
28
+ with:
29
+ node-version: ${{ matrix.node-version }}
30
+ cache: 'npm'
31
+
32
+ - run: npm ci
33
+ - run: npm test
34
+ - run: npm run build
35
+
36
+ - name: Upload coverage to Codecov
37
+ uses: codecov/codecov-action@v2
38
+ with:
39
+ token: ${{ secrets.CODECOV_TOKEN }}
@@ -0,0 +1,4 @@
1
+ #!/bin/sh
2
+ . "$(dirname "$0")/_/husky.sh"
3
+
4
+ npx lint-staged
package/.truckignore ADDED
@@ -0,0 +1 @@
1
+ package-lock.json
@@ -0,0 +1,7 @@
1
+ {
2
+ "recommendations": [
3
+ "esbenp.prettier-vscode",
4
+ "styled-components.vscode-styled-components",
5
+ "Orta.vscode-jest"
6
+ ]
7
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "name": "Launch Parser on git-visual",
9
+ "program": "${workspaceFolder}/parser/dist/index.js",
10
+ "request": "launch",
11
+ "skipFiles": [
12
+ "<node_internals>/**"
13
+ ],
14
+ "type": "pwa-node"
15
+ },
16
+ {
17
+ "type": "pwa-chrome",
18
+ "request": "launch",
19
+ "name": "Launch visualization in chrome",
20
+ "url": "http://localhost:3000",
21
+ "webRoot": "${workspaceFolder}"
22
+ }
23
+ ]
24
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "editor.formatOnSave": false,
3
+ "typescript.tsserver.experimental.enableProjectDiagnostics": false,
4
+ "githubIssues.issueBranchTitle": "${issueNumber}/${sanitizedIssueTitle}",
5
+ "editor.defaultFormatter": "esbenp.prettier-vscode"
6
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 git-visual
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # Git Truck 🚛
2
+
3
+ _Visualizing a Git repository_
4
+
5
+ Get an overview over your git repo. See your folder-structure, which users have contributed most to which files, and more.
6
+
7
+ ## [Prerequisites](#prerequisites)
8
+
9
+ This projected is tested to work with:
10
+
11
+ - Node.js 16.13
12
+ - npm 6.14
13
+ - git 2.35
14
+
15
+ ## [Usage](#usage)
16
+
17
+ 1. Install dependencies with `npm install`
18
+ 2. Build the project with `npm run build`
19
+ 3. Install the tool globally by running `npm install -g .` in the root of the project
20
+ 3. Then run the app in production mode:
21
+
22
+ **Note:** If the above fails, try running `sudo npm install -g .` instead.
23
+
24
+ ```sh
25
+ git-truck [--path <path>] [--branch <name>] [--out <path>] [--log <path>]
26
+ ```
27
+
28
+ #### [Arguments](#arguments)
29
+
30
+ | arg | default value | description |
31
+ | :--------: | :----------------: | :---------------------------------------------------------------------: |
32
+ | `--path` | current directory | path to git repository |
33
+ | `--branch` | checked out branch | branch name |
34
+ | `--out` | ./data.json | output path for data file |
35
+ | `--log` | null | output log level. See [here](./app/parser/src/log.server.ts) for values |
36
+
37
+ ## [Uninstall](#uninstall)
38
+ Uninstall the tool by running `npm uninstall -g git-truck` or `sudo npm uninstall -g git-truck`
39
+
40
+ ## [Development](#development)
41
+
42
+ In the root of the project, run the following from your terminal:
43
+
44
+ ```sh
45
+ npm run dev -- <args>
46
+ ```
47
+
48
+ _or using yarn:_ `yarn dev <args>`
49
+
50
+ For arguments, see [Arguments](#arguments).
51
+
52
+ This starts the app in development mode, rebuilding assets on file changes.
53
+
54
+ ## Clean up
55
+
56
+ To clean up build artefacts, etc. run:
57
+
58
+ ```
59
+ npm run clean
60
+ ```
package/app/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # Getting Started with Create React App
2
+
3
+ This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4
+
5
+ ## Available Scripts
6
+
7
+ In the project directory, you can run:
8
+
9
+ ### `npm start`
10
+
11
+ Runs the app in the development mode.\
12
+ Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13
+
14
+ The page will reload if you make edits.\
15
+ You will also see any lint errors in the console.
16
+
17
+ ### `npm test`
18
+
19
+ Launches the test runner in the interactive watch mode.\
20
+ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21
+
22
+ ### `npm run build`
23
+
24
+ Builds the app for production to the `build` folder.\
25
+ It correctly bundles React in production mode and optimizes the build for the best performance.
26
+
27
+ The build is minified and the filenames include the hashes.\
28
+ Your app is ready to be deployed!
29
+
30
+ See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31
+
32
+ ### `npm run eject`
33
+
34
+ **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35
+
36
+ If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37
+
38
+ Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39
+
40
+ You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41
+
42
+ ## Learn More
43
+
44
+ You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45
+
46
+ To learn React, check out the [React documentation](https://reactjs.org/).
@@ -0,0 +1,4 @@
1
+ import { hydrate } from "react-dom";
2
+ import { RemixBrowser } from "remix";
3
+
4
+ hydrate(<RemixBrowser />, document);
@@ -0,0 +1,27 @@
1
+ import { renderToString } from "react-dom/server";
2
+ import { RemixServer } from "remix";
3
+ import type { EntryContext } from "remix";
4
+ import { ServerStyleSheet } from "styled-components";
5
+
6
+ export default function handleRequest(
7
+ request: Request,
8
+ responseStatusCode: number,
9
+ responseHeaders: Headers,
10
+ remixContext: EntryContext
11
+ ) {
12
+ const sheet = new ServerStyleSheet();
13
+ let markup = renderToString(
14
+ sheet.collectStyles(
15
+ <RemixServer context={remixContext} url={request.url} />
16
+ )
17
+ );
18
+
19
+ const styles = sheet.getStyleTags()
20
+ markup = markup.replace("__STYLES__", styles)
21
+ responseHeaders.set("Content-Type", "text/html");
22
+
23
+ return new Response("<!DOCTYPE html>" + markup, {
24
+ status: responseStatusCode,
25
+ headers: responseHeaders,
26
+ });
27
+ }
@@ -0,0 +1,3 @@
1
+ dist
2
+ node_modules
3
+ .github
@@ -0,0 +1,18 @@
1
+ {
2
+ "env": {
3
+ "browser": false,
4
+ "es2021": true
5
+ },
6
+ "extends": [
7
+ "eslint:recommended",
8
+ "plugin:@typescript-eslint/recommended"
9
+ ],
10
+ "parser": "@typescript-eslint/parser",
11
+ "parserOptions": {
12
+ "ecmaVersion": "latest",
13
+ "sourceType": "module"
14
+ },
15
+ "plugins": [
16
+ "@typescript-eslint"
17
+ ]
18
+ }
@@ -0,0 +1,20 @@
1
+ import { readFileSync } from "fs"
2
+ import { compile } from "gitignore-parser"
3
+ import { log } from "./log.server"
4
+
5
+ export default class TruckIgnore {
6
+ private truckignore
7
+ constructor(path: string) {
8
+ try {
9
+ const file = readFileSync(path + "/.truckignore", "utf-8")
10
+ this.truckignore = compile(file)
11
+ } catch (e) {
12
+ log.warn("No .truckignore found")
13
+ }
14
+ }
15
+
16
+ public isAccepted(fileName: string) {
17
+ if (!this.truckignore) return true
18
+ return this.truckignore.accepts(fileName)
19
+ }
20
+ }
@@ -0,0 +1 @@
1
+ export const emptyGitCommitHash = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
@@ -0,0 +1,199 @@
1
+ import { emptyGitCommitHash } from "./constants"
2
+ import isBinaryPath from "is-binary-path"
3
+ import { join } from "path"
4
+ import { log } from "./log.server"
5
+ import {
6
+ GitBlobObject,
7
+ GitCommitObject,
8
+ GitCommitObjectLight,
9
+ HydratedGitBlobObject,
10
+ HydratedGitCommitObject,
11
+ HydratedGitTreeObject,
12
+ PersonWithTime,
13
+ } from "./model"
14
+ import { parseCommitLight } from "./parse.server"
15
+ import { gitDiffNumStatParsed, lookupFileInTree } from "./util"
16
+ import { Queue } from "./queue"
17
+
18
+ const renamedFiles = new Map<string, string>()
19
+
20
+ export async function hydrateData(
21
+ repo: string,
22
+ commit: GitCommitObject
23
+ ): Promise<HydratedGitCommitObject> {
24
+ const data = commit as HydratedGitCommitObject
25
+
26
+ initially_mut(data)
27
+
28
+ const { hash: first } = data
29
+
30
+ await bfs(first, repo, data)
31
+
32
+ finally_mut(data)
33
+
34
+ return data
35
+ }
36
+
37
+ function initially_mut(data: HydratedGitCommitObject) {
38
+ data.minNoCommits = Number.MAX_VALUE
39
+ data.maxNoCommits = Number.MIN_VALUE
40
+ data.oldestLatestChangeEpoch = Number.MAX_VALUE
41
+ data.newestLatestChangeEpoch = Number.MIN_VALUE
42
+
43
+ addAuthorsField_mut(data.tree)
44
+ }
45
+
46
+ function addAuthorsField_mut(tree: HydratedGitTreeObject) {
47
+ for (const child of tree.children) {
48
+ if (child.type === "blob") {
49
+ child.authors = {}
50
+ } else {
51
+ addAuthorsField_mut(child)
52
+ }
53
+ }
54
+ }
55
+
56
+ async function bfs(first: string, repo: string, data: HydratedGitCommitObject) {
57
+ const expandedHashes = new Set<string>()
58
+ const queue = new Queue<string>()
59
+
60
+ queue.enqueue(first)
61
+
62
+ while (!queue.isEmpty()) {
63
+ const currHash = queue.dequeue()
64
+
65
+ if (expandedHashes.has(currHash)) continue
66
+
67
+ expandedHashes.add(currHash)
68
+
69
+ // don't compare the empty commit to it's parent
70
+ if (currHash == emptyGitCommitHash) continue
71
+
72
+ const currCommit = await parseCommitLight(repo, currHash)
73
+
74
+ const parentsOfCurr = parents(currCommit)
75
+
76
+ for (const parentHash of parentsOfCurr) {
77
+ switch (parentsOfCurr.size) {
78
+ case 2: // curr is a merge commit
79
+ queue.enqueue(parentHash)
80
+ break
81
+ case 1: // curr is a linear commit
82
+ diffAndUpdate_mut(data, currCommit, parentHash, repo)
83
+ queue.enqueue(parentHash)
84
+ break
85
+ default:
86
+ // curr is the root commit
87
+ diffAndUpdate_mut(data, currCommit, emptyGitCommitHash, repo)
88
+ break
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ function parents(obj: GitCommitObject | GitCommitObjectLight): Set<string> {
95
+ const parents = new Set<string>()
96
+
97
+ if (obj.parent !== null) parents.add(obj.parent)
98
+ if (obj.parent2 !== null) parents.add(obj.parent2)
99
+
100
+ return parents
101
+ }
102
+
103
+ async function diffAndUpdate_mut(
104
+ data: HydratedGitCommitObject,
105
+ currCommit: GitCommitObjectLight,
106
+ parentHash: string,
107
+ repo: string
108
+ ) {
109
+ const { author } = currCommit
110
+
111
+ const currHash = currCommit.hash
112
+
113
+ log.debug(`comparing [${currHash}] -> [${parentHash}]`)
114
+
115
+ const fileChanges = await gitDiffNumStatParsed(
116
+ repo,
117
+ parentHash,
118
+ currHash,
119
+ renamedFiles
120
+ )
121
+
122
+ for (const fileChange of fileChanges) {
123
+ const { pos, neg, file } = fileChange
124
+
125
+ const blob = await lookupFileInTree(data.tree, file)
126
+
127
+ if (file === "dev/null") continue
128
+ if (blob) {
129
+ updateBlob_mut(blob, data, author, currCommit, pos, neg)
130
+ }
131
+ }
132
+ }
133
+
134
+ function isBinaryFile(blob: GitBlobObject) {
135
+ return isBinaryPath(join(blob.path, blob.name))
136
+ }
137
+
138
+ function updateBlob_mut(
139
+ blob: GitBlobObject,
140
+ data: HydratedGitCommitObject,
141
+ author: PersonWithTime,
142
+ currCommit: GitCommitObjectLight,
143
+ pos: number,
144
+ neg: number
145
+ ) {
146
+ const noCommits = 1 + ((blob as HydratedGitBlobObject).noCommits ?? 0)
147
+
148
+ if (noCommits < data.minNoCommits) data.minNoCommits = noCommits
149
+ if (noCommits > data.maxNoCommits) data.maxNoCommits = noCommits
150
+
151
+ const isBinary = isBinaryFile(blob)
152
+
153
+ const hydratedBlob = {
154
+ ...blob,
155
+ authors: (blob as HydratedGitBlobObject).authors ?? {},
156
+ noLines: isBinary ? 0 : blob.content?.split("\n").length,
157
+ noCommits: noCommits,
158
+ isBinary: isBinary,
159
+ } as HydratedGitBlobObject
160
+
161
+ if (!isBinary) {
162
+ const current = hydratedBlob.authors?.[author.name] ?? 0
163
+
164
+ const newValue = current + pos + neg
165
+ if (newValue > 0) {
166
+ for (const coauthor of currCommit.coauthors) {
167
+ hydratedBlob.authors[coauthor.name] = newValue
168
+ }
169
+ hydratedBlob.authors[author.name] = newValue
170
+ }
171
+ }
172
+
173
+ if (!hydratedBlob.lastChangeEpoch) {
174
+ const epoch = currCommit.author.timestamp
175
+ hydratedBlob.lastChangeEpoch = epoch
176
+
177
+ if (epoch > data.newestLatestChangeEpoch)
178
+ data.newestLatestChangeEpoch = epoch
179
+
180
+ if (epoch < data.oldestLatestChangeEpoch)
181
+ data.oldestLatestChangeEpoch = epoch
182
+ }
183
+
184
+ Object.assign(blob, hydratedBlob)
185
+ }
186
+
187
+ function finally_mut(data: HydratedGitCommitObject) {
188
+ discardContentField_mut(data.tree)
189
+ }
190
+
191
+ function discardContentField_mut(tree: HydratedGitTreeObject) {
192
+ for (const child of tree.children) {
193
+ if (child.type === "blob") {
194
+ child.content = undefined
195
+ } else {
196
+ discardContentField_mut(child)
197
+ }
198
+ }
199
+ }
@@ -0,0 +1,5 @@
1
+ import "dotenv/config"
2
+ import { parse } from "./parse.server"
3
+
4
+ const args = process.argv.slice(2)
5
+ parse(args)
@@ -0,0 +1,97 @@
1
+ export enum LOG_LEVEL {
2
+ SILENT,
3
+ ERROR,
4
+ WARN,
5
+ INFO,
6
+ DEBUG,
7
+ }
8
+ export enum LOG_LEVEL_LABEL {
9
+ SILENT = "",
10
+ ERROR = "ERR",
11
+ WARN = "WRN",
12
+ INFO = "NFO",
13
+ DEBUG = "DBG",
14
+ }
15
+
16
+ const stringToLevelMap: Record<string, LOG_LEVEL> = {
17
+ SILENT: LOG_LEVEL.SILENT,
18
+ ERROR: LOG_LEVEL.ERROR,
19
+ WARN: LOG_LEVEL.WARN,
20
+ INFO: LOG_LEVEL.INFO,
21
+ DEBUG: LOG_LEVEL.DEBUG,
22
+ }
23
+
24
+ const { ERROR, WARN, INFO, DEBUG } = LOG_LEVEL_LABEL
25
+
26
+ function setIntialLogLevel() {
27
+ if (typeof process.env.LOG_LEVEL === "string")
28
+ return stringToLevelMap[process.env.LOG_LEVEL.toUpperCase()]
29
+ if (typeof process.env.LOG_LEVEL === "number") return process.env.LOG_LEVEL
30
+ return null
31
+ }
32
+
33
+ let logLevel = setIntialLogLevel()
34
+
35
+ export const getLogLevel = () => logLevel
36
+
37
+ export function setLogLevel(level: string) {
38
+ const newLevel = stringToLevelMap[level.trim().toUpperCase()]
39
+ if(typeof newLevel === "undefined") {
40
+ throw new Error(`Invalid log level: ${level}`)
41
+ }
42
+ logLevel = newLevel
43
+ }
44
+
45
+ export function error(message: Error | unknown) {
46
+ if (logLevel === null) return
47
+ if (logLevel >= LOG_LEVEL.ERROR) {
48
+ const messageString =
49
+ message instanceof Error
50
+ ? `${prefix(ERROR)}${message.message}\n${message.stack}`
51
+ : `${prefix(ERROR)}${message}`
52
+ console.error(messageString)
53
+ }
54
+ }
55
+
56
+ export function warn(message: unknown) {
57
+ if (logLevel === null) return
58
+ if (logLevel >= LOG_LEVEL.WARN) {
59
+ const messageString = `${prefix(WARN)}${message}`
60
+ console.warn(messageString)
61
+ }
62
+ }
63
+
64
+ export function info(message: unknown) {
65
+ if (logLevel === null) return
66
+ if (logLevel >= LOG_LEVEL.INFO) {
67
+ const messageString = `${prefix(INFO)}${message}`
68
+ console.info(messageString)
69
+ }
70
+ }
71
+
72
+ export function debug(message: unknown) {
73
+ if (logLevel === null) return
74
+ if (logLevel >= LOG_LEVEL.DEBUG) {
75
+ const messageString = `${prefix(DEBUG)}${message}`
76
+ console.debug(messageString)
77
+ }
78
+ }
79
+
80
+ export function raw(message: unknown) {
81
+ if (logLevel === null) return
82
+ if (logLevel >= LOG_LEVEL.INFO) {
83
+ console.info(message)
84
+ }
85
+ }
86
+
87
+ function prefix(label: LOG_LEVEL_LABEL): string {
88
+ return `[${label}] `
89
+ }
90
+
91
+ export const log = {
92
+ error,
93
+ warn,
94
+ info,
95
+ debug,
96
+ raw,
97
+ }