Breakerbox settings db version 1.0.0

This commit is contained in:
2023-05-29 13:06:31 -04:00
commit a9bbb934c1
20 changed files with 8869 additions and 0 deletions

136
.drone.yml Normal file
View File

@@ -0,0 +1,136 @@
kind: pipeline
type: docker
name: Test Pipeline
workspace:
path: /drone/auth
steps:
- name: yarn install
image: node:20-bullseye-slim
environment:
YARN_VERSION: 3.5.0
commands:
- yarn set version stable
- yarn install
volumes:
- name: yarnrc
path: /drone/auth/.yarnrc.yml
- name: Code Style Checks
image: node:latest
commands:
- yarn prettier
- name: Lint
image: node:latest
commands:
- yarn lint
- name: Unit Tests
image: node:latest
commands:
- yarn test
- name: Send Test Status Notification
image: plugins/webhook
settings:
urls: https://lab.mifi.dev/hooks/9p65zpagctgkmndo8nwwm4199r
content_type: application/json
template: |
{
"icon_url":"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/198/freezing-face_1f976.png",
"text": "[{{ repo.name }} - Build # {{ build.number }}] Code Quality Checks {{ build.status }} {{#success build.status}}:tada:{{else}}:poop:{{/success}}",
"username":"DroneBot"
}
when:
status:
- success
- failure
- name: Build
image: node:latest
commands:
- yarn build:production
- name: Send Build Status Notifications
image: plugins/webhook
settings:
urls: https://lab.mifi.dev/hooks/9p65zpagctgkmndo8nwwm4199r
content_type: application/json
template: |
{
"icon_url":"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/198/freezing-face_1f976.png",
"text": "[{{ repo.name }} - Build # {{ build.number }}] Build package {{ build.status }} {{#success build.status}}:tada:{{else}}:poop:{{/success}}",
"username":"DroneBot"
}
when:
status:
- success
- failure
volumes:
- name: yarnrc
host:
path: /volume1/docker/.yarnrc.yml
trigger:
branch:
- main
- develop
event:
- pull_request
---
kind: pipeline
type: docker
name: Publish Pipeline
workspace:
path: /drone/auth
steps:
- name: Build
image: node:20-bullseye-slim
environment:
YARN_VERSION: 3.5.0
commands:
- yarn set version stable
- yarn install
- yarn build:production
volumes:
- name: yarnrc
path: /drone/auth/.yarnrc.yml
- name: Publish NPM
image: node:20-bullseye-slim
commands:
- yarn npm publish
volumes:
- name: npmrc
path: /drone/auth/.npmrc
- name: yarnrc
path: /drone/auth/.yarnrc.yml
- name: Report NPM Publish Status
image: plugins/webhook
settings:
urls: https://lab.mifi.dev/hooks/ccw34hdf7tgbjmzp96nptn938r
content_type: application/json
template: |
{
"icon_url":"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/198/freezing-face_1f976.png",
"text": "[{{ repo.name }} - New npm package release {{tag}} from # {{ build.number }}] Deploy {{ build.status }} {{#success build.status}}:tada:{{else}}:poop:{{/success}}",
"username":"DroneBot"
}
when:
status:
- success
- failure
volumes:
- name: npmrc
host:
path: /volume1/docker/beethoven/labs-auth/.npmrc
- name: yarnrc
host:
path: /volume1/docker/.yarnrc.yml
depends_on:
- Test Pipeline
trigger:
event:
- tag

19
.eslintrc.js Normal file
View File

@@ -0,0 +1,19 @@
/* eslint-env node */
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:import/errors',
'plugin:prettier/recommended',
'prettier',
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
settings: {
'import/parsers': {
'@typescript-eslint/parser': ['.ts', '.tsx'],
},
'import/resolver': 'typescript',
},
root: true,
};

135
.gitignore vendored Normal file
View File

@@ -0,0 +1,135 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# Project
lib/

10
.npmignore Normal file
View File

@@ -0,0 +1,10 @@
.build.yarnrc.yml
.drone.yml
.eslintrc*
.npmrc
.prettierrc*
.yarnrc.yml
babel.config.*
jest.config.*
tsconfig*.json
tslint.json

7
.prettierrc.js Normal file
View File

@@ -0,0 +1,7 @@
module.exports = {
parser: 'typescript',
printWidth: 120,
trailingComma: 'all',
tabWidth: 4,
singleQuote: true,
};

873
.yarn/releases/yarn-3.5.1.cjs vendored Executable file

File diff suppressed because one or more lines are too long

3
.yarnrc.yml Normal file
View File

@@ -0,0 +1,3 @@
nodeLinker: node-modules
yarnPath: .yarn/releases/yarn-3.5.1.cjs

2
README.md Normal file
View File

@@ -0,0 +1,2 @@
# @mifi/auth

6
babel.config.js Normal file
View File

@@ -0,0 +1,6 @@
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
'@babel/preset-typescript',
],
};

195
jest.config.ts Normal file
View File

@@ -0,0 +1,195 @@
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/75/3cyx0pq133n7gk3ysqf0mj4r0000gn/T/jest_dx",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
// coverageProvider: "babel",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};

51
package.json Normal file
View File

@@ -0,0 +1,51 @@
{
"name": "@mifi/breakerbox-db",
"version": "1.0.0",
"author": "mifi (Mike Fitzpatrick)",
"license": "MIT",
"scripts": {
"build": "tsc",
"build:production": "tsc -p ./tsconfig.production.json",
"format": "prettier:fix && lint:fix",
"lint": "eslint --ext .ts,.tsx src/",
"lint:fix": "eslint --fix --ext .ts,.tsx src/",
"prettier": "prettier --check 'src/**/*.ts'",
"prettier:fix": "prettier --write 'src/**/*.ts'",
"test": "jest --passWithNoTests"
},
"devDependencies": {
"@babel/core": "^7.21.8",
"@babel/preset-env": "^7.21.5",
"@babel/preset-typescript": "^7.21.5",
"@tsconfig/node20": "^1.0.1",
"@types/jsonwebtoken": "^9.0.2",
"@types/node": "^18.14.0",
"@typescript-eslint/eslint-plugin": "^5.59.2",
"@typescript-eslint/parser": "^5.59.2",
"babel-jest": "^29.5.0",
"eslint": "^8.39.0",
"eslint-config-prettier": "^8.8.0",
"eslint-import-resolver-typescript": "^3.5.5",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-n": "^15.0.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-promise": "^6.0.0",
"jest": "^29.5.0",
"prettier": "^2.8.4",
"prettier-eslint": "^15.0.1",
"prettier-eslint-cli": "^7.1.0",
"reflect-metadata": "^0.1.13",
"ts-node": "^10.9.1",
"typescript": "^4.9.5"
},
"description": "",
"repository": {
"type": "git",
"url": "https://git.mifi.dev/mifi/breakerbox-db.git"
},
"packageManager": "yarn@3.5.1",
"dependencies": {
"lowdb": "^6.0.1",
"yaml": "^2.3.1"
}
}

4
src/adapters/json.ts Normal file
View File

@@ -0,0 +1,4 @@
import { JSONFile } from 'lowdb/node';
import { Fuses, Panel } from '../types/Panel';
export const jsonAdapter = <T = Fuses>(file: string) => new JSONFile<Panel<T>>(file);

26
src/adapters/yaml.ts Normal file
View File

@@ -0,0 +1,26 @@
import { TextFile } from 'lowdb/node';
import { parse, stringify } from 'yaml';
import { Fuses, Panel } from '../types/Panel';
class YAMLFile<T = Fuses> {
private adapter: TextFile;
constructor(filename: string) {
this.adapter = new TextFile(filename);
}
async read() {
const data = await this.adapter.read();
if (data === null) {
return null;
} else {
return parse(data) as Panel<T>;
}
}
write(obj: Panel<T>) {
return this.adapter.write(stringify(obj));
}
}
export const yamlAdapter = <T = Fuses>(filename: string) => new YAMLFile<Panel<T>>(filename);

85
src/index.ts Normal file
View File

@@ -0,0 +1,85 @@
import { Adapter, Low } from 'lowdb';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { jsonAdapter } from './adapters/json';
import { yamlAdapter } from './adapters/yaml';
import { Fuses, Panel } from './types/Panel';
import { ValidValues } from './types/ValidValues';
import { SettingsMeta } from './types/SettingsMeta';
export class Breakerbox {
protected db;
public static defaultStore = { fuses: {} as Fuses } as Panel;
constructor(
filename = 'settings.json',
path = fileURLToPath(import.meta.url),
defaultStore = Breakerbox.defaultStore,
storageType: 'json' | 'yaml' = 'json',
) {
const __dirname = dirname(path);
const file = join(__dirname, filename);
const adapter = storageType === 'yaml' ? yamlAdapter<Fuses>(file) : jsonAdapter<Fuses>(file);
this.db = new Low<Panel<Fuses>>(<Adapter<Panel<Fuses>>>adapter, defaultStore);
this.db.read();
}
public async delete(key: string) {
delete this.db.data.fuses[key];
await this.db.write();
return true;
}
public get(key: string) {
return this.getAll()[key];
}
public getAll() {
return this.db.data.fuses;
}
public getValue(key: string, defaultValue?: ValidValues, insert = false) {
const fuse = this.get(key);
if (fuse) {
return fuse.value;
}
if (insert && defaultValue) {
this.set(key, defaultValue);
}
return defaultValue;
}
public async set(key: string, value: ValidValues, meta = { type: typeof value }) {
if (['boolean', 'number', 'object', 'string'].includes(meta.type)) {
this.db.data.fuses[key] = { value, meta: { ...meta, type: meta.type as SettingsMeta['type'] } };
await this.db.write();
return true;
} else {
console.error('Error: Invalid type', { key, meta, value });
throw new Error('Invalid type');
}
}
public async update(key: string, value: ValidValues, meta = {} as SettingsMeta) {
const fuse = this.db.data.fuses[key];
if (!fuse) {
return this.set(key, value, meta);
}
if (fuse) {
this.db.data.fuses[key] = {
value: value ? value : fuse.value,
meta: { ...fuse.meta, ...meta },
};
await this.db.write();
return true;
}
return false;
}
}

15
src/types/Panel.ts Normal file
View File

@@ -0,0 +1,15 @@
import { SettingsMeta } from './SettingsMeta';
import { ValidValues } from './ValidValues';
export interface Panel<T = Fuses> {
fuses: T;
}
export interface Setting {
meta: SettingsMeta;
value: ValidValues;
}
export type Fuses = {
[key: string]: Setting | undefined;
};

View File

@@ -0,0 +1,4 @@
export interface SettingsMeta {
type: 'boolean' | 'number' | 'object' | 'string';
category?: string;
}

4
src/types/ValidValues.ts Normal file
View File

@@ -0,0 +1,4 @@
type Primitives = boolean | null | number | string;
type Arrays = (boolean | null | number | string)[] | KeyValue[];
export type KeyValue = { [key: string]: ValidValues };
export type ValidValues = Arrays | KeyValue | Primitives;

19
tsconfig.json Normal file
View File

@@ -0,0 +1,19 @@
{
"extends": "@tsconfig/node20/tsconfig.json",
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"module": "es2022",
"moduleResolution": "Node",
"noImplicitAny": true,
"outDir": "lib/",
"rootDirs": ["./", "src/"],
"strict": true,
"esModuleInterop": true,
"sourceMap": true,
"removeComments": false
},
"include": ["src"]
}

19
tsconfig.production.json Normal file
View File

@@ -0,0 +1,19 @@
{
"extends": "@tsconfig/node16/tsconfig.json",
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"module": "es2022",
"moduleResolution": "Node",
"noImplicitAny": true,
"outDir": "lib/",
"rootDirs": ["./", "src/"],
"strict": true,
"esModuleInterop": true,
"sourceMap": true,
"removeComments": false
},
"include": ["src"]
}

7256
yarn.lock Normal file

File diff suppressed because it is too large Load Diff