laplace-api 1.0.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.
package/.gitattributes ADDED
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 canturkay
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,2 @@
1
+ # laplace-api-js
2
+ Client library for Laplace API for the US stock market and BIST (Istanbul stock market) fundamental financial data.
@@ -0,0 +1,41 @@
1
+ import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
2
+ import { Logger } from 'winston';
3
+ import { LaplaceConfiguration } from '../utilities/configuration';
4
+
5
+ export class Client {
6
+ private cli: AxiosInstance;
7
+ private baseUrl: string;
8
+ private apiKey: string;
9
+ private logger: Logger;
10
+
11
+ constructor(cfg: LaplaceConfiguration, logger: Logger) {
12
+ this.cli = axios.create();
13
+ this.baseUrl = cfg.baseURL;
14
+ this.apiKey = cfg.apiKey;
15
+ this.logger = logger;
16
+ }
17
+
18
+ async sendRequest<T>(config: AxiosRequestConfig): Promise<T> {
19
+ try {
20
+ const response = await this.cli.request<T>({
21
+ ...config,
22
+ baseURL: this.baseUrl,
23
+ headers: {
24
+ ...config.headers,
25
+ Authorization: `Bearer ${this.apiKey}`,
26
+ },
27
+ });
28
+
29
+ return response.data;
30
+ } catch (error) {
31
+ if (axios.isAxiosError(error) && error.response) {
32
+ throw new Error(`Unexpected status code: ${error.response.status}, body: ${JSON.stringify(error.response.data)}`);
33
+ }
34
+ throw error;
35
+ }
36
+ }
37
+ }
38
+
39
+ export function createClient(cfg: LaplaceConfiguration, logger: Logger): Client {
40
+ return new Client(cfg, logger);
41
+ }
@@ -0,0 +1,97 @@
1
+ import { Client } from './client';
2
+ import { Stock } from './stocks';
3
+
4
+ export enum CollectionType {
5
+ Sector = 'sector',
6
+ Industry = 'industry',
7
+ Theme = 'theme',
8
+ CustomTheme = 'custom-theme',
9
+ Collection = 'collection',
10
+ }
11
+
12
+ export enum Region {
13
+ Tr = 'tr',
14
+ Us = 'us',
15
+ }
16
+
17
+ export enum Locale {
18
+ Tr = 'tr',
19
+ En = 'en',
20
+ }
21
+
22
+ export interface Collection {
23
+ id: string;
24
+ title: string;
25
+ description: string;
26
+ region: Region[];
27
+ assetClass: string;
28
+ imageUrl: string;
29
+ avatarUrl: string;
30
+ numStocks: number;
31
+ image: string;
32
+ order: number;
33
+ status?: string;
34
+ metaData?: Record<string, any>;
35
+ }
36
+
37
+ export interface CollectionDetail extends Collection {
38
+ stocks: Stock[];
39
+ }
40
+
41
+ export class CollectionClient extends Client {
42
+ private async getAllCollectionsPrivate(collectionType: CollectionType, region: Region, locale: Locale): Promise<Collection[]> {
43
+ return this.sendRequest<Collection[]>({
44
+ method: 'GET',
45
+ url: `/api/v1/${collectionType}`,
46
+ params: { region, locale },
47
+ });
48
+ }
49
+
50
+ private async getCollectionDetailPrivate(id: string, collectionType: CollectionType, region: Region, locale: Locale): Promise<CollectionDetail> {
51
+ return this.sendRequest<CollectionDetail>({
52
+ method: 'GET',
53
+ url: `/api/v1/${collectionType}/${id}`,
54
+ params: { region, locale },
55
+ });
56
+ }
57
+
58
+ async getAllSectors(region: Region, locale: Locale): Promise<Collection[]> {
59
+ return this.getAllCollectionsPrivate(CollectionType.Sector, region, locale);
60
+ }
61
+
62
+ async getAllIndustries(region: Region, locale: Locale): Promise<Collection[]> {
63
+ return this.getAllCollectionsPrivate(CollectionType.Industry, region, locale);
64
+ }
65
+
66
+ async getAllThemes(region: Region, locale: Locale): Promise<Collection[]> {
67
+ return this.getAllCollectionsPrivate(CollectionType.Theme, region, locale);
68
+ }
69
+
70
+ async getAllCustomThemes(region: Region, locale: Locale): Promise<Collection[]> {
71
+ return this.getAllCollectionsPrivate(CollectionType.CustomTheme, region, locale);
72
+ }
73
+
74
+ async getAllCollections(region: Region, locale: Locale): Promise<Collection[]> {
75
+ return this.getAllCollectionsPrivate(CollectionType.Collection, region, locale);
76
+ }
77
+
78
+ async getSectorDetail(id: string, region: Region, locale: Locale): Promise<CollectionDetail> {
79
+ return this.getCollectionDetailPrivate(id, CollectionType.Sector, region, locale);
80
+ }
81
+
82
+ async getIndustryDetail(id: string, region: Region, locale: Locale): Promise<CollectionDetail> {
83
+ return this.getCollectionDetailPrivate(id, CollectionType.Industry, region, locale);
84
+ }
85
+
86
+ async getThemeDetail(id: string, region: Region, locale: Locale): Promise<CollectionDetail> {
87
+ return this.getCollectionDetailPrivate(id, CollectionType.Theme, region, locale);
88
+ }
89
+
90
+ async getCustomThemeDetail(id: string, region: Region, locale: Locale): Promise<CollectionDetail> {
91
+ return this.getCollectionDetailPrivate(id, CollectionType.CustomTheme, region, locale);
92
+ }
93
+
94
+ async getCollectionDetail(id: string, region: Region, locale: Locale): Promise<CollectionDetail> {
95
+ return this.getCollectionDetailPrivate(id, CollectionType.Collection, region, locale);
96
+ }
97
+ }
@@ -0,0 +1,51 @@
1
+ import { Client } from './client';
2
+ import { Region, Locale } from './collections';
3
+
4
+ export enum SearchType {
5
+ Stock = 'stock',
6
+ Collection = 'collection',
7
+ Sector = 'sector',
8
+ Industry = 'industry',
9
+ }
10
+
11
+ export interface SearchResponseStock {
12
+ id: string;
13
+ name: string;
14
+ symbol: string;
15
+ region: string;
16
+ assetClass: string;
17
+ assetType: string;
18
+ }
19
+
20
+ export interface SearchResponseCollection {
21
+ id: string;
22
+ title: string;
23
+ region: string[];
24
+ assetClass: string;
25
+ imageUrl: string;
26
+ avatarUrl: string;
27
+ }
28
+
29
+ export interface SearchResponse {
30
+ stocks: SearchResponseStock[];
31
+ collections: SearchResponseCollection[];
32
+ sectors: SearchResponseCollection[];
33
+ industries: SearchResponseCollection[];
34
+ }
35
+
36
+ export class SearchClient extends Client {
37
+ async search(query: string, types: SearchType[], region: Region, locale: Locale): Promise<SearchResponse> {
38
+ const typesStr = types.join(',');
39
+
40
+ return this.sendRequest<SearchResponse>({
41
+ method: 'GET',
42
+ url: '/api/v1/search',
43
+ params: {
44
+ filter: query,
45
+ types: typesStr,
46
+ region,
47
+ locale,
48
+ },
49
+ });
50
+ }
51
+ }
@@ -0,0 +1,113 @@
1
+ import { Client } from './client';
2
+ import { Region, Locale } from './collections';
3
+
4
+ export enum AssetType {
5
+ Stock = 'stock',
6
+ Forex = 'forex',
7
+ Index = 'index',
8
+ Etf = 'etf',
9
+ Commodity = 'commodity',
10
+ }
11
+
12
+ export enum AssetClass {
13
+ Equity = 'equity',
14
+ Crypto = 'crypto',
15
+ }
16
+
17
+ export enum HistoricalPricePeriod {
18
+ OneDay = '1D',
19
+ OneWeek = '1W',
20
+ OneMonth = '1M',
21
+ ThreeMonth = '3M',
22
+ OneYear = '1Y',
23
+ TwoYear = '2Y',
24
+ ThreeYear = '3Y',
25
+ FiveYear = '5Y',
26
+ }
27
+
28
+ export interface Stock {
29
+ id: string;
30
+ assetType: AssetType;
31
+ name: string;
32
+ symbol: string;
33
+ sectorId: string;
34
+ industryId: string;
35
+ updatedDate: string;
36
+ dailyChange?: number;
37
+ }
38
+
39
+ export interface LocaleString {
40
+ [key: string]: string;
41
+ }
42
+
43
+ export interface StockDetail {
44
+ id: string;
45
+ assetType: AssetType;
46
+ assetClass: AssetClass;
47
+ name: string;
48
+ symbol: string;
49
+ description: string;
50
+ localized_description: LocaleString;
51
+ region: string;
52
+ sectorId: string;
53
+ industryId: string;
54
+ updatedDate: string;
55
+ }
56
+
57
+ export interface PriceDataPoint {
58
+ d: number;
59
+ c: number;
60
+ h: number;
61
+ l: number;
62
+ o: number;
63
+ }
64
+
65
+ export interface StockPriceGraph {
66
+ symbol: string;
67
+ '1D': PriceDataPoint[];
68
+ '1W': PriceDataPoint[];
69
+ '1M': PriceDataPoint[];
70
+ '3M': PriceDataPoint[];
71
+ '1Y': PriceDataPoint[];
72
+ '2Y': PriceDataPoint[];
73
+ '3Y': PriceDataPoint[];
74
+ '5Y': PriceDataPoint[];
75
+ }
76
+
77
+ export class StockClient extends Client {
78
+ async getAllStocks(region: Region): Promise<Stock[]> {
79
+ return this.sendRequest<Stock[]>({
80
+ method: 'GET',
81
+ url: '/api/v1/stock/all',
82
+ params: { region },
83
+ });
84
+ }
85
+
86
+ async getStockDetailById(id: string, locale: Locale): Promise<StockDetail> {
87
+ return this.sendRequest<StockDetail>({
88
+ method: 'GET',
89
+ url: `/api/v1/stock/${id}`,
90
+ params: { locale },
91
+ });
92
+ }
93
+
94
+ async getStockDetailBySymbol(symbol: string, assetClass: AssetClass, region: Region, locale: Locale): Promise<StockDetail> {
95
+ return this.sendRequest<StockDetail>({
96
+ method: 'GET',
97
+ url: '/api/v1/stock/detail',
98
+ params: { symbol, asset_class: assetClass, region, locale },
99
+ });
100
+ }
101
+
102
+ async getHistoricalPrices(symbols: string[], region: Region, keys: HistoricalPricePeriod[]): Promise<StockPriceGraph[]> {
103
+ return this.sendRequest<StockPriceGraph[]>({
104
+ method: 'GET',
105
+ url: '/api/v1/stock/price',
106
+ params: {
107
+ symbols: symbols.join(','),
108
+ region,
109
+ keys: keys.join(','),
110
+ },
111
+ });
112
+ }
113
+ }
package/jest.config.js ADDED
@@ -0,0 +1,5 @@
1
+ module.exports = {
2
+ preset: 'ts-jest',
3
+ testEnvironment: 'node',
4
+ setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
5
+ };
package/jest.setup.ts ADDED
@@ -0,0 +1,29 @@
1
+ import 'jest';
2
+
3
+ declare global {
4
+ namespace jest {
5
+ interface Matchers<R> {
6
+ toBeEmpty(): R;
7
+ }
8
+ }
9
+ }
10
+
11
+ expect.extend({
12
+ toBeEmpty(received: any) {
13
+ if (Array.isArray(received) || typeof received === 'string') {
14
+ return {
15
+ message: () => `expected ${received} to be empty`,
16
+ pass: received.length === 0,
17
+ };
18
+ } else if (typeof received === 'object' && received !== null) {
19
+ return {
20
+ message: () => `expected ${received} to be empty`,
21
+ pass: Object.keys(received).length === 0,
22
+ };
23
+ }
24
+ return {
25
+ message: () => `expected ${received} to be empty`,
26
+ pass: false,
27
+ };
28
+ },
29
+ });
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "laplace-api",
3
+ "version": "1.0.0",
4
+ "description": "Client library for Laplace API for the US stock market and BIST (Istanbul stock market) fundamental financial data.",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "build": "tsc",
8
+ "start": "node dist/index.js",
9
+ "test": "jest"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/Laplace-Analytics/laplace-api-js.git"
14
+ },
15
+ "keywords": [
16
+ "finance",
17
+ "stock",
18
+ "market",
19
+ "stock",
20
+ "price",
21
+ "financial",
22
+ "data",
23
+ "price",
24
+ "chart",
25
+ "price",
26
+ "graph",
27
+ "stock",
28
+ "data",
29
+ "BIST"
30
+ ],
31
+ "author": "Laplace Analytics",
32
+ "license": "ISC",
33
+ "bugs": {
34
+ "url": "https://github.com/Laplace-Analytics/laplace-api-js/issues"
35
+ },
36
+ "homepage": "https://github.com/Laplace-Analytics/laplace-api-js#readme",
37
+ "dependencies": {
38
+ "axios": "^1.7.7",
39
+ "dotenv": "^16.4.5",
40
+ "envalid": "^8.0.0",
41
+ "mongodb": "^6.8.0",
42
+ "winston": "^3.14.2"
43
+ },
44
+ "devDependencies": {
45
+ "@types/axios": "^0.14.0",
46
+ "@types/jest": "^29.5.12",
47
+ "@types/mongodb": "^4.0.7",
48
+ "@types/node": "^22.5.4",
49
+ "@types/winston": "^2.4.4",
50
+ "jest": "^29.7.0",
51
+ "ts-jest": "^29.2.5",
52
+ "typescript": "^5.5.4"
53
+ }
54
+ }
@@ -0,0 +1,53 @@
1
+ import { Logger } from 'winston';
2
+ import { LaplaceConfiguration } from '../utilities/configuration';
3
+ import { Client, createClient } from '../client/client';
4
+ import './client_test_suite';
5
+
6
+ // Assuming these are defined elsewhere in your project
7
+ enum Region { Tr = 'tr' }
8
+ enum Locale { Tr = 'tr' }
9
+
10
+ class LaplaceClientTestSuite {
11
+ private config: LaplaceConfiguration;
12
+
13
+ constructor(config: LaplaceConfiguration) {
14
+ this.config = config;
15
+ }
16
+
17
+ async testClient() {
18
+ const logger: Logger = {
19
+ info: jest.fn(),
20
+ error: jest.fn(),
21
+ warn: jest.fn(),
22
+ debug: jest.fn(),
23
+ } as unknown as Logger;
24
+
25
+ const client = createClient(this.config, logger);
26
+
27
+ const res = await client.sendRequest({
28
+ method: 'GET',
29
+ url: '/api/v1/industry',
30
+ params: {
31
+ region: Region.Tr,
32
+ locale: Locale.Tr,
33
+ },
34
+ });
35
+
36
+ expect(res).toBeTruthy();
37
+ expect(res).not.toEqual({});
38
+ }
39
+ }
40
+
41
+ describe('LaplaceClient', () => {
42
+ let testSuite: LaplaceClientTestSuite;
43
+
44
+ beforeAll(() => {
45
+ // Assuming global.testSuite is set up as in the previous example
46
+ const config = (global as any).testSuite.config;
47
+ testSuite = new LaplaceClientTestSuite(config);
48
+ });
49
+
50
+ it('should make a successful request', async () => {
51
+ await testSuite.testClient();
52
+ });
53
+ });
@@ -0,0 +1,51 @@
1
+ import * as path from 'path';
2
+ import * as dotenv from 'dotenv';
3
+ import { findModuleRoot } from '../utilities/fs';
4
+ import { loadGlobal, LaplaceConfiguration } from '../utilities/configuration';
5
+
6
+ const testConfig = './utilities/test.env';
7
+
8
+ class ClientTestSuite {
9
+ config: LaplaceConfiguration | null = null;
10
+
11
+ async setUp(): Promise<void> {
12
+ try {
13
+ const repoRoot = await findModuleRoot();
14
+ const configPath = path.join(repoRoot, testConfig);
15
+
16
+ dotenv.config({ path: configPath });
17
+
18
+ this.config = loadGlobal(configPath);
19
+
20
+ if (!this.config) {
21
+ throw new Error('Config is not set');
22
+ }
23
+
24
+ if (!this.config.apiKey) {
25
+ throw new Error('API key is not set');
26
+ }
27
+
28
+ if (!this.config.baseURL) {
29
+ throw new Error('API base URL is not set');
30
+ }
31
+ } catch (error) {
32
+ throw new Error(`Setup failed: ${error instanceof Error ? error.message : String(error)}`);
33
+ }
34
+ }
35
+ }
36
+
37
+ // Jest beforeAll hook to set up the test suite
38
+ beforeAll(async () => {
39
+ const suite = new ClientTestSuite();
40
+ await suite.setUp();
41
+ (global as any).testSuite = suite;
42
+ });
43
+
44
+ // Example test
45
+ test('Config is properly loaded', () => {
46
+ expect((global as any).testSuite.config).toBeTruthy();
47
+ expect((global as any).testSuite.config?.apiKey).toBeTruthy();
48
+ expect((global as any).testSuite.config?.baseURL).toBeTruthy();
49
+ });
50
+
51
+ export { ClientTestSuite };
@@ -0,0 +1,36 @@
1
+ import { Logger } from 'winston';
2
+ import { LaplaceConfiguration } from '../utilities/configuration';
3
+ import { CollectionClient, Region, Locale } from '../client/collections';
4
+ import './client_test_suite';
5
+
6
+ describe('Collections', () => {
7
+ let client: CollectionClient;
8
+
9
+ beforeAll(() => {
10
+ // Assuming global.testSuite is set up as in the previous example
11
+ const config = (global as any).testSuite.config as LaplaceConfiguration;
12
+ const logger: Logger = {
13
+ info: jest.fn(),
14
+ error: jest.fn(),
15
+ warn: jest.fn(),
16
+ debug: jest.fn(),
17
+ } as unknown as Logger;
18
+
19
+ client = new CollectionClient(config, logger);
20
+ });
21
+
22
+ test('GetAllIndustries', async () => {
23
+ const resp = await client.getAllIndustries(Region.Tr, Locale.Tr);
24
+ expect(resp).not.toBeEmpty();
25
+ });
26
+
27
+ test('GetIndustryDetails', async () => {
28
+ const resp = await client.getIndustryDetail("65533e441fa5c7b58afa0944", Region.Tr, Locale.Tr);
29
+ expect(resp).not.toBeEmpty();
30
+ });
31
+
32
+ test('GetSectorDetails', async () => {
33
+ const resp = await client.getSectorDetail("65533e047844ee7afe9941b9", Region.Tr, Locale.Tr);
34
+ expect(resp).not.toBeEmpty();
35
+ });
36
+ });
@@ -0,0 +1,43 @@
1
+ import { Logger } from 'winston';
2
+ import { LaplaceConfiguration } from '../utilities/configuration';
3
+ import { SearchClient, SearchType } from '../client/search';
4
+ import { Region, Locale } from '../client/collections';
5
+ import './client_test_suite';
6
+
7
+
8
+ describe('Search', () => {
9
+ let client: SearchClient;
10
+
11
+ beforeAll(() => {
12
+ // Assuming global.testSuite is set up as in the previous example
13
+ const config = (global as any).testSuite.config as LaplaceConfiguration;
14
+ const logger: Logger = {
15
+ info: jest.fn(),
16
+ error: jest.fn(),
17
+ warn: jest.fn(),
18
+ debug: jest.fn(),
19
+ } as unknown as Logger;
20
+
21
+ client = new SearchClient(config, logger);
22
+ });
23
+
24
+ test('SearchStock', async () => {
25
+ const resp = await client.search("TUPRS", [SearchType.Stock], Region.Tr, Locale.Tr);
26
+ expect(resp).not.toBeEmpty();
27
+ });
28
+
29
+ test('SearchIndustry', async () => {
30
+ const resp = await client.search("Hava Taşımacılığı", [SearchType.Industry], Region.Tr, Locale.Tr);
31
+ expect(resp).not.toBeEmpty();
32
+ });
33
+
34
+ test('SearchAllTypes', async () => {
35
+ const resp = await client.search("Ab", [
36
+ SearchType.Stock,
37
+ SearchType.Industry,
38
+ SearchType.Sector,
39
+ SearchType.Collection
40
+ ], Region.Us, Locale.Tr);
41
+ expect(resp).not.toBeEmpty();
42
+ });
43
+ });
@@ -0,0 +1,51 @@
1
+ import { Logger } from 'winston';
2
+ import { LaplaceConfiguration } from '../utilities/configuration';
3
+ import { StockClient, AssetClass, HistoricalPricePeriod } from '../client/stocks';
4
+ import { Region, Locale } from '../client/collections';
5
+ import './client_test_suite';
6
+
7
+
8
+ describe('Stocks', () => {
9
+ let client: StockClient;
10
+
11
+ beforeAll(() => {
12
+ // Assuming global.testSuite is set up as in the previous example
13
+ const config = (global as any).testSuite.config as LaplaceConfiguration;
14
+ const logger: Logger = {
15
+ info: jest.fn(),
16
+ error: jest.fn(),
17
+ warn: jest.fn(),
18
+ debug: jest.fn(),
19
+ } as unknown as Logger;
20
+
21
+ client = new StockClient(config, logger);
22
+ });
23
+
24
+ test('GetAllStocks', async () => {
25
+ const resp = await client.getAllStocks(Region.Tr);
26
+ expect(resp).not.toBeEmpty();
27
+ });
28
+
29
+ test('GetStockDetailByID', async () => {
30
+ const resp = await client.getStockDetailById("61dd0d6f0ec2114146342fd0", Locale.Tr);
31
+ expect(resp).not.toBeEmpty();
32
+ });
33
+
34
+ test('GetStockDetailBySymbol', async () => {
35
+ const resp = await client.getStockDetailBySymbol("TUPRS", AssetClass.Equity, Region.Tr, Locale.Tr);
36
+ expect(resp).not.toBeEmpty();
37
+ });
38
+
39
+ test('GetHistoricalPrices', async () => {
40
+ const resp = await client.getHistoricalPrices(
41
+ ["TUPRS", "SASA"],
42
+ Region.Tr,
43
+ [HistoricalPricePeriod.OneDay, HistoricalPricePeriod.OneWeek, HistoricalPricePeriod.OneMonth]
44
+ );
45
+ expect(resp).not.toBeEmpty();
46
+
47
+ for (const price of resp) {
48
+ expect(price).not.toBeEmpty();
49
+ }
50
+ });
51
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es6",
4
+ "outDir": "./dist",
5
+ "rootDir": "./src",
6
+ "strict": true,
7
+ "esModuleInterop": true,
8
+ "types": ["jest", "node"],
9
+ "typeRoots": ["./node_modules/@types", "./types"]
10
+ },
11
+ "include": ["src/**/*", "jest.setup.ts"],
12
+ "exclude": ["node_modules", "**/*.spec.ts"]
13
+ }
@@ -0,0 +1,73 @@
1
+ import * as dotenv from 'dotenv';
2
+ import * as envalid from 'envalid';
3
+ const { str } = envalid;
4
+
5
+ export interface LaplaceConfigurationInterface {
6
+ baseURL: string;
7
+ apiKey: string;
8
+ }
9
+
10
+ export class LaplaceConfiguration implements LaplaceConfigurationInterface {
11
+ baseURL: string;
12
+ apiKey: string;
13
+
14
+ constructor({ baseURL, apiKey }: LaplaceConfigurationInterface) {
15
+ this.baseURL = baseURL;
16
+ this.apiKey = apiKey;
17
+ }
18
+
19
+ validate(): null | Error {
20
+ // Add validation logic if needed
21
+ return null;
22
+ }
23
+
24
+ applyDefaults(): null | Error {
25
+ // Apply default values if needed
26
+ return null;
27
+ }
28
+ }
29
+
30
+ function loadEnvironment(filename?: string): dotenv.DotenvConfigOutput {
31
+ if (filename) {
32
+ return dotenv.config({ path: filename, override: true });
33
+ } else {
34
+ return dotenv.config({ debug: false });
35
+ }
36
+ }
37
+
38
+ type ValidationFunc = (config: LaplaceConfiguration) => null | Error;
39
+
40
+ function validationFuncRegular(config: LaplaceConfiguration): null | Error {
41
+ return config.validate();
42
+ }
43
+
44
+ export function loadGlobal(filename?: string, validationFunc: ValidationFunc = validationFuncRegular): LaplaceConfiguration {
45
+ const envLoadResult = loadEnvironment(filename);
46
+ if (envLoadResult.error) {
47
+ throw envLoadResult.error;
48
+ }
49
+
50
+ const env = envalid.cleanEnv(process.env, {
51
+ BASE_URL: str(),
52
+ API_KEY: str(),
53
+ });
54
+
55
+ const config = new LaplaceConfiguration({
56
+ baseURL: env.BASE_URL,
57
+ apiKey: env.API_KEY,
58
+ });
59
+
60
+ const defaultError = config.applyDefaults();
61
+ if (defaultError) {
62
+ throw defaultError;
63
+ }
64
+
65
+ if (validationFunc) {
66
+ const validationError = validationFunc(config);
67
+ if (validationError) {
68
+ throw validationError;
69
+ }
70
+ }
71
+
72
+ return config;
73
+ }
@@ -0,0 +1,22 @@
1
+ import * as path from 'path';
2
+ import * as fs from 'fs/promises';
3
+
4
+ // FindModuleRoot finds the relative path to the root of the project.
5
+ export async function findModuleRoot(): Promise<string> {
6
+ let currentDir = process.cwd();
7
+
8
+ while (true) {
9
+ try {
10
+ await fs.access(path.join(currentDir, 'package.json'));
11
+ // package.json found
12
+ return currentDir;
13
+ } catch (error) {
14
+ const parentDir = path.dirname(currentDir);
15
+ if (parentDir === currentDir) {
16
+ // Reached the root directory
17
+ throw new Error('package.json file not found');
18
+ }
19
+ currentDir = parentDir;
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,2 @@
1
+ BASE_URL=https://api.finfree.app
2
+ API_KEY=api-6fa6cefb-16df-4a19-8351-54f83c6bbe2f