tering-serieuze-sdk 3.9.0 → 3.10.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/.prettierrc +6 -2
- package/dist/index.mjs +4 -0
- package/dist/index.mjs.map +2 -2
- package/package.json +4 -4
- package/src/api/auth.ts +17 -17
- package/src/api/base.ts +2 -2
- package/src/api/index.ts +4 -4
- package/src/api/jingle.ts +13 -13
- package/src/api/k8s.ts +1 -1
- package/src/api/user.ts +5 -5
- package/src/cache/abstractCache.ts +2 -2
- package/src/cache/cookieCache.ts +5 -5
- package/src/cache/filesystemCache.ts +6 -6
- package/src/cache/index.ts +5 -5
- package/src/cache/nullCache.ts +1 -1
- package/src/cache/onePasswordCache.ts +6 -6
- package/src/index.ts +33 -28
- package/test/api/base.test.ts +11 -11
- package/test/api/jingle.test.ts +14 -15
- package/test/cache/filesystemCache.test.ts +36 -36
- package/test/cache/nullCache.test.ts +15 -15
- package/types/environment.d.ts +1 -1
package/.prettierrc
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -388,6 +388,10 @@ var TssApi = class {
|
|
|
388
388
|
this.auth = new AuthModule(this, cacheConfiguration?.auth ?? new NullCache("auth"));
|
|
389
389
|
this.k8s = new K8sModule(this, cacheConfiguration?.k8s ?? new NullCache("k8s"));
|
|
390
390
|
this.user = new UserModule(this, cacheConfiguration?.user ?? new NullCache("user"));
|
|
391
|
+
this.fetch("/auth/verify", {
|
|
392
|
+
method: "POST",
|
|
393
|
+
yo: "lo"
|
|
394
|
+
});
|
|
391
395
|
}
|
|
392
396
|
auth;
|
|
393
397
|
jingle;
|
package/dist/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../node_modules/stack-trace/index.js", "../src/cache/abstractCache.ts", "../src/cache/cookieCache.ts", "../src/cache/filesystemCache.ts", "../src/cache/nullCache.ts", "../src/cache/onePasswordCache.ts", "../src/api/base.ts", "../src/api/auth.ts", "../src/api/jingle.ts", "../src/api/k8s.ts", "../src/api/user.ts", "../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["export function get(belowFn) {\r\n const oldLimit = Error.stackTraceLimit;\r\n Error.stackTraceLimit = Infinity;\r\n\r\n const dummyObject = {};\r\n\r\n const v8Handler = Error.prepareStackTrace;\r\n Error.prepareStackTrace = function(dummyObject, v8StackTrace) {\r\n return v8StackTrace;\r\n };\r\n Error.captureStackTrace(dummyObject, belowFn || get);\r\n\r\n const v8StackTrace = dummyObject.stack;\r\n Error.prepareStackTrace = v8Handler;\r\n Error.stackTraceLimit = oldLimit;\r\n\r\n return v8StackTrace;\r\n}\r\n\r\nexport function parse(err) {\r\n if (!err.stack) {\r\n return [];\r\n }\r\n\r\n const lines = err.stack.split('\\n').slice(1);\r\n return lines\r\n .map(function(line) {\r\n if (line.match(/^\\s*[-]{4,}$/)) {\r\n return createParsedCallSite({\r\n fileName: line,\r\n lineNumber: null,\r\n functionName: null,\r\n typeName: null,\r\n methodName: null,\r\n columnNumber: null,\r\n 'native': null,\r\n });\r\n }\r\n\r\n const lineMatch = line.match(/at (?:(.+?)\\s+\\()?(?:(.+?):(\\d+)(?::(\\d+))?|([^)]+))\\)?/);\r\n if (!lineMatch) {\r\n return;\r\n }\r\n\r\n let object = null;\r\n let method = null;\r\n let functionName = null;\r\n let typeName = null;\r\n let methodName = null;\r\n let isNative = (lineMatch[5] === 'native');\r\n\r\n if (lineMatch[1]) {\r\n functionName = lineMatch[1];\r\n let methodStart = functionName.lastIndexOf('.');\r\n if (functionName[methodStart-1] == '.')\r\n methodStart--;\r\n if (methodStart > 0) {\r\n object = functionName.substr(0, methodStart);\r\n method = functionName.substr(methodStart + 1);\r\n const objectEnd = object.indexOf('.Module');\r\n if (objectEnd > 0) {\r\n functionName = functionName.substr(objectEnd + 1);\r\n object = object.substr(0, objectEnd);\r\n }\r\n }\r\n }\r\n\r\n if (method) {\r\n typeName = object;\r\n methodName = method;\r\n }\r\n\r\n if (method === '<anonymous>') {\r\n methodName = null;\r\n functionName = null;\r\n }\r\n\r\n const properties = {\r\n fileName: lineMatch[2] || null,\r\n lineNumber: parseInt(lineMatch[3], 10) || null,\r\n functionName: functionName,\r\n typeName: typeName,\r\n methodName: methodName,\r\n columnNumber: parseInt(lineMatch[4], 10) || null,\r\n 'native': isNative,\r\n };\r\n\r\n return createParsedCallSite(properties);\r\n })\r\n .filter(function(callSite) {\r\n return !!callSite;\r\n });\r\n}\r\n\r\nfunction CallSite(properties) {\r\n for (const property in properties) {\r\n this[property] = properties[property];\r\n }\r\n}\r\n\r\nconst strProperties = [\r\n 'this',\r\n 'typeName',\r\n 'functionName',\r\n 'methodName',\r\n 'fileName',\r\n 'lineNumber',\r\n 'columnNumber',\r\n 'function',\r\n 'evalOrigin'\r\n];\r\n\r\nconst boolProperties = [\r\n 'topLevel',\r\n 'eval',\r\n 'native',\r\n 'constructor'\r\n];\r\n\r\nstrProperties.forEach(function (property) {\r\n CallSite.prototype[property] = null;\r\n CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () {\r\n return this[property];\r\n }\r\n});\r\n\r\nboolProperties.forEach(function (property) {\r\n CallSite.prototype[property] = false;\r\n CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () {\r\n return this[property];\r\n }\r\n});\r\n\r\nfunction createParsedCallSite(properties) {\r\n return new CallSite(properties);\r\n}\r\n", "import { get } from \"stack-trace\";\n\nexport enum CacheLifetime {\n Day = 60 * 60 * 24 * 1000,\n Week = 60 * 60 * 24 * 7 * 1000,\n}\n\nexport abstract class AbstractCache {\n constructor(protected cacheName: string) {}\n\n public abstract cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T>;\n\n public abstract get<T>(key: string): Promise<T | undefined>;\n\n public abstract set<T>(key: string, value: T, lifetime?: number): void;\n\n public abstract remove(key: string): void;\n\n public abstract clear(): void;\n\n public getCacheKey(): string {\n const errorMessage = \"Could not determine cache key. Please provide a key manually.\";\n const trace = get();\n if (trace.length < 3) {\n throw new Error(errorMessage);\n }\n\n const functionName = get()[2].getFunctionName();\n if (!functionName) {\n throw new Error(errorMessage);\n }\n\n return functionName;\n }\n}\n", "import { AbstractCache } from \"./abstractCache\";\n\nexport class CookieCache extends AbstractCache {\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n throw new Error(\"Not implemented, use get() and set()\");\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n if (document.cookie.includes(`${key}=`)) {\n return document.cookie.split(`${key}=`)[1]?.split(\";\")[0] as T;\n }\n\n return undefined;\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {\n const expires = lifetime ? new Date(Date.now() + lifetime).toUTCString() : \"\";\n document.cookie = `${key}=${value}; expires=${expires}; path=/; samesite=strict; secure`;\n }\n\n public remove(key: string): void {\n document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;\n }\n\n public clear(): void {\n throw new Error(\"Not implemented, use remove()\");\n }\n}\n", "import { AbstractCache } from \"./abstractCache\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport os from \"os\";\n\ntype CacheItem = {\n value: any;\n expiresAt?: number;\n};\n\nexport class FilesystemCache extends AbstractCache {\n protected initialized = false;\n\n protected state: { [key: string]: CacheItem } = {};\n\n public async cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n key = key ?? this.getCacheKey();\n\n const cachedValue = await this.get<T>(key);\n if (cachedValue) {\n return cachedValue;\n }\n\n const result = await callbackWhenEmpty();\n this.set(key, result, lifetime);\n return result;\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n if (!this.initialized) {\n await this._initialize();\n }\n\n const expires = this.state[key]?.expiresAt;\n if (Object.keys(this.state).includes(key) && (expires === undefined || expires > Date.now())) {\n return this.state[key].value;\n }\n\n return undefined;\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {\n const expiresAt = lifetime ? Date.now() + lifetime : undefined;\n const content: CacheItem = { value };\n if (expiresAt) {\n content.expiresAt = expiresAt;\n }\n this.state[key] = content;\n this.writeState();\n }\n\n public remove(key: string): void {\n delete this.state[key];\n this.writeState();\n }\n\n public clear(): void {\n this.state = {};\n if (fs.existsSync(this.getFilePath())) {\n fs.unlinkSync(this.getFilePath());\n }\n }\n\n public getFilePath() {\n return path.join(os.homedir(), \".tss\", `${this.cacheName}.json`);\n }\n\n protected _initialize() {\n this.initialized = true;\n if (fs.existsSync(this.getFilePath())) {\n this.state = JSON.parse(fs.readFileSync(this.getFilePath(), \"utf8\"));\n }\n }\n\n protected writeState() {\n if (!fs.existsSync(path.dirname(this.getFilePath()))) {\n fs.mkdirSync(path.dirname(this.getFilePath()));\n }\n\n fs.writeFileSync(this.getFilePath(), JSON.stringify(this.state));\n }\n}\n", "import { AbstractCache } from \"./abstractCache\";\n\nexport class NullCache extends AbstractCache {\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n return callbackWhenEmpty();\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n return undefined;\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {}\n\n public remove(key: string): void {}\n\n public clear(): void {}\n}\n", "import { AbstractCache } from \"./abstractCache\";\nimport util from \"util\";\nimport child_process from \"child_process\";\n\n// TODO error handling en lifetime\nexport class OnePasswordCache extends AbstractCache {\n protected asyncExec = util.promisify(child_process.exec);\n\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n throw new Error(\"Not implemented, use get() and set()\");\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n const { stdout, stderr } = await this.asyncExec(`op item get \"${key}\" --fields label=credential --format json`);\n\n if (stderr) {\n console.log(stderr);\n throw new Error(\"ERROR\");\n }\n\n return JSON.parse(stdout).value;\n }\n\n public async set<T>(key: string, value: T, lifetime?: number): Promise<void> {\n let action = `op item edit '${key}' 'credential=${value}'`;\n\n try {\n const t = await this.get(key);\n } catch (e) {\n action = `op item create --category=\"API Credential\" --title ${key} 'credential=${value}'`;\n }\n\n const { stdout, stderr } = await this.asyncExec(action);\n\n if (stderr) {\n console.log(stderr);\n throw new Error(\"ERROR\");\n }\n }\n\n public async remove(key: string): Promise<void> {\n await this.asyncExec(`op item delete '${key}'`);\n }\n\n public clear(): void {\n // Loopje maken en heel 1password leeg maken?\n }\n}\n", "import { AbstractCache } from \"../cache\";\nimport { TssApi } from \"../index\";\n\nexport class BaseModule {\n constructor(protected api: TssApi, protected cache: AbstractCache) {}\n\n public getCache() {\n return this.cache;\n }\n\n public setCache(cache: AbstractCache) {\n this.cache = cache;\n }\n}\n", "import { BaseModule } from \"./base\";\nimport { AuthenticationOptionsDto, VerificationResponseDto, type TokenContent } from \"tering-serieuze-types\";\nimport type {\n AuthenticationResponseJSON,\n PublicKeyCredentialCreationOptionsJSON,\n RegistrationResponseJSON,\n} from \"@simplewebauthn/typescript-types\";\n\nexport function parseJwt<T>(token: string): T {\n let jsonPayload;\n\n if (typeof Buffer !== \"undefined\") {\n jsonPayload = Buffer.from(token.split(\".\")[1], \"base64\").toString();\n } else {\n const base64Url = token.split(\".\")[1];\n const base64 = base64Url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n jsonPayload = decodeURIComponent(\n window\n .atob(base64)\n .split(\"\")\n .map(function (c) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\")\n );\n }\n\n return JSON.parse(jsonPayload) as T;\n}\n\nexport class AuthModule extends BaseModule {\n public static cacheKey = \"TSS-TOKEN\";\n\n async getToken(): Promise<string | undefined> {\n return process.env.TSS_TOKEN ?? this.cache.get(AuthModule.cacheKey);\n }\n\n async setToken(token: string, lifetime?: number) {\n return this.cache.set(AuthModule.cacheKey, token, lifetime);\n }\n\n async setCode(code: string) {\n // TODO any ?!\n const { accessToken } = await this.api.post<any>(`auth/setCode?code=${code}`, {}, { credentials: \"include\" });\n return accessToken;\n }\n\n async removeToken() {\n return this.cache.remove(AuthModule.cacheKey);\n }\n\n async getSessionId() {\n const token = await this.getToken();\n const { sessionId } = parseJwt<TokenContent>(token ?? \"\");\n return sessionId;\n }\n\n async removeSession(sessionId?: string) {\n const session = sessionId ?? (await this.getSessionId());\n await this.api.delete(`session/${session}`, { credentials: \"include\" });\n }\n\n async logout() {\n await this.removeSession();\n await this.removeToken();\n }\n\n async getRegistrationOptions(registrationToken: string) {\n return this.api.get<PublicKeyCredentialCreationOptionsJSON>(`auth/registration-options/${registrationToken}`);\n }\n\n async getAuthenticationOptions() {\n return this.api.get<AuthenticationOptionsDto>(\"auth/authentication-options\");\n }\n\n async verifyRegistration(registrationToken: string, registrationResponse: RegistrationResponseJSON) {\n return this.api.post<VerificationResponseDto>(\n `auth/verify-registration/${registrationToken}`,\n registrationResponse,\n { credentials: \"include\" }\n );\n }\n\n async verifyAuthentication(token: string, response: AuthenticationResponseJSON) {\n return this.api.post<VerificationResponseDto>(`auth/verify-authentication/${token}`, response, {\n credentials: \"include\",\n });\n }\n}\n", "import type { JingleFolder, Jingle, PlayJingleDto, BigBrotherItem } from \"tering-serieuze-types\";\nimport { BaseModule } from \"./base\";\nimport { CacheLifetime } from \"../cache\";\n\nexport class JingleModule extends BaseModule {\n async getGrouped(): Promise<JingleFolder[]> {\n return this.cache.cacheOrGet(\n () => {\n return this.api.get<JingleFolder[]>(\"jingle/grouped\");\n },\n \"getGrouped\",\n CacheLifetime.Day\n );\n }\n\n async getAll(): Promise<Jingle[]> {\n return this.cache.cacheOrGet(\n () => {\n return this.api.get<Jingle[]>(\"jingle\");\n },\n \"getAll\",\n CacheLifetime.Day\n );\n }\n\n async getRecentlyAdded(): Promise<Jingle[]> {\n const jingles = await this.getAll();\n return jingles.sort((a, b) => b.mtime - a.mtime).slice(0, 30);\n }\n\n async play(playJingleDto: PlayJingleDto) {\n console.log(`Playing jingle ${playJingleDto.folder}/${playJingleDto.file}`);\n return this.api.post(\"jingle/play\", playJingleDto);\n }\n\n async getBigBrotherData(): Promise<BigBrotherItem[]> {\n return this.api.get<BigBrotherItem[]>(\"jingle/bigbrother\");\n }\n\n async find(query: string, jingles: Jingle[] = []): Promise<Jingle[]> {\n jingles = jingles.length ? jingles : await this.getAll();\n\n const queryParts = query.split(\" \");\n const matches = jingles.filter((jingle) =>\n queryParts.every((queryPart) => (jingle.folder + \"/\" + jingle.file).includes(queryPart))\n );\n\n return matches.sort((a, b) => {\n const aScore = a.keywords.filter((keyword) => query.includes(keyword)).length;\n const bScore = b.keywords.filter((keyword) => query.includes(keyword)).length;\n\n return bScore - aScore;\n });\n }\n}\n", "import { BaseModule } from \"./base\";\n\nexport class K8sModule extends BaseModule {\n async deletePod(podName: string) {\n return this.api.delete(`k8s/${podName}`);\n }\n}\n", "import { BaseModule } from \"./base\";\nimport type { SetWindowStateDto, User } from \"tering-serieuze-types\";\n\nexport class UserModule extends BaseModule {\n async get(userId?: string) {\n return this.cache.cacheOrGet(() => {\n const userIdParam = userId ? `/${userId}` : \"\";\n return this.api.get<User>(`user${userIdParam}`);\n });\n }\n\n async getAll() {\n return this.cache.cacheOrGet(() => {\n return this.api.get<User[]>(\"user/all\");\n });\n }\n\n async setWindowState(setWindowStateDto: SetWindowStateDto) {\n return this.api.putPossibleEmptyResponse(\"user/windowState\", setWindowStateDto);\n }\n}\n", "import { AbstractCache, NullCache } from \"./cache\";\nimport { AuthModule, JingleModule, K8sModule, UserModule } from \"./api\";\nimport type { Dto } from \"tering-serieuze-types\";\n\nexport * from \"./api\";\nexport * from \"./cache\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\nexport interface SDKRequestInit extends RequestInit {\n method?: HttpMethod;\n}\n\nexport enum CacheType {\n jingle = \"jingle\",\n auth = \"auth\",\n k8s = \"k8s\",\n user = \"user\",\n}\n\nexport type ApiConfiguration = {\n API_URL: string;\n};\n\nexport type CacheConfiguration = {\n [key in keyof typeof CacheType]?: AbstractCache;\n};\n\nexport class ErrorResponse extends Error {\n constructor(public readonly status: number, public readonly message: string) {\n super();\n }\n}\n\nexport class TssApi {\n auth: AuthModule;\n jingle: JingleModule;\n k8s: K8sModule;\n user: UserModule;\n\n constructor(protected readonly apiConfiguration: ApiConfiguration, cacheConfiguration?: CacheConfiguration) {\n this.jingle = new JingleModule(this, cacheConfiguration?.jingle ?? new NullCache(\"jingle\"));\n this.auth = new AuthModule(this, cacheConfiguration?.auth ?? new NullCache(\"auth\"));\n this.k8s = new K8sModule(this, cacheConfiguration?.k8s ?? new NullCache(\"k8s\"));\n this.user = new UserModule(this, cacheConfiguration?.user ?? new NullCache(\"user\"));\n }\n\n async fetch(url: string, config: SDKRequestInit = {}) {\n config.method = config.method ?? \"GET\";\n config.headers = {\n ...config.headers,\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${await this.auth.getToken()}`,\n };\n\n const apiPrefix = this.apiConfiguration.API_URL;\n\n if (apiPrefix.match(/^https?:\\/\\/localhost/) !== null && typeof process !== \"undefined\" && process.env) {\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = \"0\";\n }\n\n const fullUrl = `${apiPrefix}/api/${url}`;\n console.log(\"Fetching url\", fullUrl);\n\n let response;\n try {\n response = await fetch(fullUrl, config);\n } catch (e) {\n throw new ErrorResponse(503, \"API erg dood\");\n }\n\n if (response.status >= 400) {\n const error = await response.json();\n throw new ErrorResponse(error.statusCode, error.message ?? error.error);\n }\n\n return response;\n }\n\n protected async fetchPossibleEmptyResponse<T>(\n method: HttpMethod,\n url: string,\n dto: Dto,\n config: SDKRequestInit = {}\n ) {\n return this.fetch(url, {\n method,\n ...config,\n body: JSON.stringify(dto),\n });\n }\n\n async get<T>(url: string) {\n const response = await this.fetch(url);\n return response.json() as Promise<T>;\n }\n\n async post<T>(url: string, dto: Dto, config: SDKRequestInit = {}) {\n const response = await this.fetchPossibleEmptyResponse<T>(\"POST\", url, dto, config);\n if (response === undefined) {\n throw new Error(\"Response was undefined\");\n }\n return (await response.json()) as Promise<T>;\n }\n\n async postPossibleEmptyResponse(url: string, dto: Dto) {\n return this.fetchPossibleEmptyResponse(\"POST\", url, dto);\n }\n\n async put<T>(url: string, dto: Dto) {\n const response = await this.fetchPossibleEmptyResponse<T>(\"PUT\", url, dto);\n if (response === undefined) {\n throw new Error(\"Response was undefined\");\n }\n return (await response.json()) as Promise<T>;\n }\n\n async putPossibleEmptyResponse(url: string, dto: Dto) {\n return this.fetchPossibleEmptyResponse(\"PUT\", url, dto);\n }\n\n async delete<T>(url: string, config: SDKRequestInit = {}) {\n return this.fetch(url, {\n method: \"DELETE\",\n ...config,\n });\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;AAAO,SAAS,IAAI,SAAS;AAC3B,QAAM,WAAW,MAAM;AACvB,QAAM,kBAAkB;AAExB,QAAM,cAAc,CAAC;AAErB,QAAM,YAAY,MAAM;AACxB,QAAM,oBAAoB,SAASA,cAAaC,eAAc;AAC5D,WAAOA;AAAA,EACT;AACA,QAAM,kBAAkB,aAAa,WAAW,GAAG;AAEnD,QAAM,eAAe,YAAY;AACjC,QAAM,oBAAoB;AAC1B,QAAM,kBAAkB;AAExB,SAAO;AACT;AA6EA,SAAS,SAAS,YAAY;AAC5B,aAAW,YAAY,YAAY;AACjC,SAAK,QAAQ,IAAI,WAAW,QAAQ;AAAA,EACtC;AACF;AAEA,IAAM,gBAAgB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,cAAc,QAAQ,SAAU,UAAU;AACxC,WAAS,UAAU,QAAQ,IAAI;AAC/B,WAAS,UAAU,QAAQ,SAAS,CAAC,EAAE,YAAY,IAAI,SAAS,OAAO,CAAC,CAAC,IAAI,WAAY;AACv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,WAAW,MAAM,oBAAoB,QAAQ,IAAI,UAAU,MAAM,CAAC;AAClF,SAAK,MAAM,IAAI,UAAU,MAAM,oBAAoB,OAAO,IAAI,UAAU,KAAK,CAAC;AAC9E,SAAK,OAAO,IAAI,WAAW,MAAM,oBAAoB,QAAQ,IAAI,UAAU,MAAM,CAAC;AAAA,
|
|
4
|
+
"sourcesContent": ["export function get(belowFn) {\r\n const oldLimit = Error.stackTraceLimit;\r\n Error.stackTraceLimit = Infinity;\r\n\r\n const dummyObject = {};\r\n\r\n const v8Handler = Error.prepareStackTrace;\r\n Error.prepareStackTrace = function(dummyObject, v8StackTrace) {\r\n return v8StackTrace;\r\n };\r\n Error.captureStackTrace(dummyObject, belowFn || get);\r\n\r\n const v8StackTrace = dummyObject.stack;\r\n Error.prepareStackTrace = v8Handler;\r\n Error.stackTraceLimit = oldLimit;\r\n\r\n return v8StackTrace;\r\n}\r\n\r\nexport function parse(err) {\r\n if (!err.stack) {\r\n return [];\r\n }\r\n\r\n const lines = err.stack.split('\\n').slice(1);\r\n return lines\r\n .map(function(line) {\r\n if (line.match(/^\\s*[-]{4,}$/)) {\r\n return createParsedCallSite({\r\n fileName: line,\r\n lineNumber: null,\r\n functionName: null,\r\n typeName: null,\r\n methodName: null,\r\n columnNumber: null,\r\n 'native': null,\r\n });\r\n }\r\n\r\n const lineMatch = line.match(/at (?:(.+?)\\s+\\()?(?:(.+?):(\\d+)(?::(\\d+))?|([^)]+))\\)?/);\r\n if (!lineMatch) {\r\n return;\r\n }\r\n\r\n let object = null;\r\n let method = null;\r\n let functionName = null;\r\n let typeName = null;\r\n let methodName = null;\r\n let isNative = (lineMatch[5] === 'native');\r\n\r\n if (lineMatch[1]) {\r\n functionName = lineMatch[1];\r\n let methodStart = functionName.lastIndexOf('.');\r\n if (functionName[methodStart-1] == '.')\r\n methodStart--;\r\n if (methodStart > 0) {\r\n object = functionName.substr(0, methodStart);\r\n method = functionName.substr(methodStart + 1);\r\n const objectEnd = object.indexOf('.Module');\r\n if (objectEnd > 0) {\r\n functionName = functionName.substr(objectEnd + 1);\r\n object = object.substr(0, objectEnd);\r\n }\r\n }\r\n }\r\n\r\n if (method) {\r\n typeName = object;\r\n methodName = method;\r\n }\r\n\r\n if (method === '<anonymous>') {\r\n methodName = null;\r\n functionName = null;\r\n }\r\n\r\n const properties = {\r\n fileName: lineMatch[2] || null,\r\n lineNumber: parseInt(lineMatch[3], 10) || null,\r\n functionName: functionName,\r\n typeName: typeName,\r\n methodName: methodName,\r\n columnNumber: parseInt(lineMatch[4], 10) || null,\r\n 'native': isNative,\r\n };\r\n\r\n return createParsedCallSite(properties);\r\n })\r\n .filter(function(callSite) {\r\n return !!callSite;\r\n });\r\n}\r\n\r\nfunction CallSite(properties) {\r\n for (const property in properties) {\r\n this[property] = properties[property];\r\n }\r\n}\r\n\r\nconst strProperties = [\r\n 'this',\r\n 'typeName',\r\n 'functionName',\r\n 'methodName',\r\n 'fileName',\r\n 'lineNumber',\r\n 'columnNumber',\r\n 'function',\r\n 'evalOrigin'\r\n];\r\n\r\nconst boolProperties = [\r\n 'topLevel',\r\n 'eval',\r\n 'native',\r\n 'constructor'\r\n];\r\n\r\nstrProperties.forEach(function (property) {\r\n CallSite.prototype[property] = null;\r\n CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () {\r\n return this[property];\r\n }\r\n});\r\n\r\nboolProperties.forEach(function (property) {\r\n CallSite.prototype[property] = false;\r\n CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () {\r\n return this[property];\r\n }\r\n});\r\n\r\nfunction createParsedCallSite(properties) {\r\n return new CallSite(properties);\r\n}\r\n", "import { get } from 'stack-trace';\n\nexport enum CacheLifetime {\n Day = 60 * 60 * 24 * 1000,\n Week = 60 * 60 * 24 * 7 * 1000,\n}\n\nexport abstract class AbstractCache {\n constructor(protected cacheName: string) {}\n\n public abstract cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T>;\n\n public abstract get<T>(key: string): Promise<T | undefined>;\n\n public abstract set<T>(key: string, value: T, lifetime?: number): void;\n\n public abstract remove(key: string): void;\n\n public abstract clear(): void;\n\n public getCacheKey(): string {\n const errorMessage = 'Could not determine cache key. Please provide a key manually.';\n const trace = get();\n if (trace.length < 3) {\n throw new Error(errorMessage);\n }\n\n const functionName = get()[2].getFunctionName();\n if (!functionName) {\n throw new Error(errorMessage);\n }\n\n return functionName;\n }\n}\n", "import { AbstractCache } from './abstractCache';\n\nexport class CookieCache extends AbstractCache {\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n throw new Error('Not implemented, use get() and set()');\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n if (document.cookie.includes(`${key}=`)) {\n return document.cookie.split(`${key}=`)[1]?.split(';')[0] as T;\n }\n\n return undefined;\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {\n const expires = lifetime ? new Date(Date.now() + lifetime).toUTCString() : '';\n document.cookie = `${key}=${value}; expires=${expires}; path=/; samesite=strict; secure`;\n }\n\n public remove(key: string): void {\n document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;\n }\n\n public clear(): void {\n throw new Error('Not implemented, use remove()');\n }\n}\n", "import { AbstractCache } from './abstractCache';\nimport fs from 'fs';\nimport path from 'path';\nimport os from 'os';\n\ntype CacheItem = {\n value: any;\n expiresAt?: number;\n};\n\nexport class FilesystemCache extends AbstractCache {\n protected initialized = false;\n\n protected state: { [key: string]: CacheItem } = {};\n\n public async cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n key = key ?? this.getCacheKey();\n\n const cachedValue = await this.get<T>(key);\n if (cachedValue) {\n return cachedValue;\n }\n\n const result = await callbackWhenEmpty();\n this.set(key, result, lifetime);\n return result;\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n if (!this.initialized) {\n await this._initialize();\n }\n\n const expires = this.state[key]?.expiresAt;\n if (Object.keys(this.state).includes(key) && (expires === undefined || expires > Date.now())) {\n return this.state[key].value;\n }\n\n return undefined;\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {\n const expiresAt = lifetime ? Date.now() + lifetime : undefined;\n const content: CacheItem = { value };\n if (expiresAt) {\n content.expiresAt = expiresAt;\n }\n this.state[key] = content;\n this.writeState();\n }\n\n public remove(key: string): void {\n delete this.state[key];\n this.writeState();\n }\n\n public clear(): void {\n this.state = {};\n if (fs.existsSync(this.getFilePath())) {\n fs.unlinkSync(this.getFilePath());\n }\n }\n\n public getFilePath() {\n return path.join(os.homedir(), '.tss', `${this.cacheName}.json`);\n }\n\n protected _initialize() {\n this.initialized = true;\n if (fs.existsSync(this.getFilePath())) {\n this.state = JSON.parse(fs.readFileSync(this.getFilePath(), 'utf8'));\n }\n }\n\n protected writeState() {\n if (!fs.existsSync(path.dirname(this.getFilePath()))) {\n fs.mkdirSync(path.dirname(this.getFilePath()));\n }\n\n fs.writeFileSync(this.getFilePath(), JSON.stringify(this.state));\n }\n}\n", "import { AbstractCache } from './abstractCache';\n\nexport class NullCache extends AbstractCache {\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n return callbackWhenEmpty();\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n return undefined;\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {}\n\n public remove(key: string): void {}\n\n public clear(): void {}\n}\n", "import { AbstractCache } from './abstractCache';\nimport util from 'util';\nimport child_process from 'child_process';\n\n// TODO error handling en lifetime\nexport class OnePasswordCache extends AbstractCache {\n protected asyncExec = util.promisify(child_process.exec);\n\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n throw new Error('Not implemented, use get() and set()');\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n const { stdout, stderr } = await this.asyncExec(`op item get \"${key}\" --fields label=credential --format json`);\n\n if (stderr) {\n console.log(stderr);\n throw new Error('ERROR');\n }\n\n return JSON.parse(stdout).value;\n }\n\n public async set<T>(key: string, value: T, lifetime?: number): Promise<void> {\n let action = `op item edit '${key}' 'credential=${value}'`;\n\n try {\n const t = await this.get(key);\n } catch (e) {\n action = `op item create --category=\"API Credential\" --title ${key} 'credential=${value}'`;\n }\n\n const { stdout, stderr } = await this.asyncExec(action);\n\n if (stderr) {\n console.log(stderr);\n throw new Error('ERROR');\n }\n }\n\n public async remove(key: string): Promise<void> {\n await this.asyncExec(`op item delete '${key}'`);\n }\n\n public clear(): void {\n // Loopje maken en heel 1password leeg maken?\n }\n}\n", "import { AbstractCache } from '../cache';\nimport { TssApi } from '../index';\n\nexport class BaseModule {\n constructor(protected api: TssApi, protected cache: AbstractCache) {}\n\n public getCache() {\n return this.cache;\n }\n\n public setCache(cache: AbstractCache) {\n this.cache = cache;\n }\n}\n", "import { BaseModule } from './base';\nimport { AuthenticationOptionsDto, VerificationResponseDto, type TokenContent } from 'tering-serieuze-types';\nimport type {\n AuthenticationResponseJSON,\n PublicKeyCredentialCreationOptionsJSON,\n RegistrationResponseJSON,\n} from '@simplewebauthn/types';\n\nexport function parseJwt<T>(token: string): T {\n let jsonPayload;\n\n if (typeof Buffer !== 'undefined') {\n jsonPayload = Buffer.from(token.split('.')[1], 'base64').toString();\n } else {\n const base64Url = token.split('.')[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n jsonPayload = decodeURIComponent(\n window\n .atob(base64)\n .split('')\n .map(function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n }\n\n return JSON.parse(jsonPayload) as T;\n}\n\nexport class AuthModule extends BaseModule {\n public static cacheKey = 'TSS-TOKEN';\n\n async getToken(): Promise<string | undefined> {\n return process.env.TSS_TOKEN ?? this.cache.get(AuthModule.cacheKey);\n }\n\n async setToken(token: string, lifetime?: number) {\n return this.cache.set(AuthModule.cacheKey, token, lifetime);\n }\n\n async setCode(code: string) {\n // TODO any ?!\n const { accessToken } = await this.api.post<any>(`auth/setCode?code=${code}`, {}, { credentials: 'include' });\n return accessToken;\n }\n\n async removeToken() {\n return this.cache.remove(AuthModule.cacheKey);\n }\n\n async getSessionId() {\n const token = await this.getToken();\n const { sessionId } = parseJwt<TokenContent>(token ?? '');\n return sessionId;\n }\n\n async removeSession(sessionId?: string) {\n const session = sessionId ?? (await this.getSessionId());\n await this.api.delete(`session/${session}`, { credentials: 'include' });\n }\n\n async logout() {\n await this.removeSession();\n await this.removeToken();\n }\n\n async getRegistrationOptions(registrationToken: string) {\n return this.api.get<PublicKeyCredentialCreationOptionsJSON>(`auth/registration-options/${registrationToken}`);\n }\n\n async getAuthenticationOptions() {\n return this.api.get<AuthenticationOptionsDto>('auth/authentication-options');\n }\n\n async verifyRegistration(registrationToken: string, registrationResponse: RegistrationResponseJSON) {\n return this.api.post<VerificationResponseDto>(\n `auth/verify-registration/${registrationToken}`,\n registrationResponse,\n { credentials: 'include' },\n );\n }\n\n async verifyAuthentication(token: string, response: AuthenticationResponseJSON) {\n return this.api.post<VerificationResponseDto>(`auth/verify-authentication/${token}`, response, {\n credentials: 'include',\n });\n }\n}\n", "import type { JingleFolder, Jingle, PlayJingleDto, BigBrotherItem } from 'tering-serieuze-types';\nimport { BaseModule } from './base';\nimport { CacheLifetime } from '../cache';\n\nexport class JingleModule extends BaseModule {\n async getGrouped(): Promise<JingleFolder[]> {\n return this.cache.cacheOrGet(\n () => {\n return this.api.get<JingleFolder[]>('jingle/grouped');\n },\n 'getGrouped',\n CacheLifetime.Day,\n );\n }\n\n async getAll(): Promise<Jingle[]> {\n return this.cache.cacheOrGet(\n () => {\n return this.api.get<Jingle[]>('jingle');\n },\n 'getAll',\n CacheLifetime.Day,\n );\n }\n\n async getRecentlyAdded(): Promise<Jingle[]> {\n const jingles = await this.getAll();\n return jingles.sort((a, b) => b.mtime - a.mtime).slice(0, 30);\n }\n\n async play(playJingleDto: PlayJingleDto) {\n console.log(`Playing jingle ${playJingleDto.folder}/${playJingleDto.file}`);\n return this.api.post('jingle/play', playJingleDto);\n }\n\n async getBigBrotherData(): Promise<BigBrotherItem[]> {\n return this.api.get<BigBrotherItem[]>('jingle/bigbrother');\n }\n\n async find(query: string, jingles: Jingle[] = []): Promise<Jingle[]> {\n jingles = jingles.length ? jingles : await this.getAll();\n\n const queryParts = query.split(' ');\n const matches = jingles.filter((jingle) =>\n queryParts.every((queryPart) => (jingle.folder + '/' + jingle.file).includes(queryPart)),\n );\n\n return matches.sort((a, b) => {\n const aScore = a.keywords.filter((keyword) => query.includes(keyword)).length;\n const bScore = b.keywords.filter((keyword) => query.includes(keyword)).length;\n\n return bScore - aScore;\n });\n }\n}\n", "import { BaseModule } from './base';\n\nexport class K8sModule extends BaseModule {\n async deletePod(podName: string) {\n return this.api.delete(`k8s/${podName}`);\n }\n}\n", "import { BaseModule } from './base';\nimport type { SetWindowStateDto, User } from 'tering-serieuze-types';\n\nexport class UserModule extends BaseModule {\n async get(userId?: string) {\n return this.cache.cacheOrGet(() => {\n const userIdParam = userId ? `/${userId}` : '';\n return this.api.get<User>(`user${userIdParam}`);\n });\n }\n\n async getAll() {\n return this.cache.cacheOrGet(() => {\n return this.api.get<User[]>('user/all');\n });\n }\n\n async setWindowState(setWindowStateDto: SetWindowStateDto) {\n return this.api.putPossibleEmptyResponse('user/windowState', setWindowStateDto);\n }\n}\n", "import { AbstractCache, NullCache } from './cache';\nimport { AuthModule, JingleModule, K8sModule, UserModule } from './api';\nimport type { Dto } from 'tering-serieuze-types';\n\nexport * from './api';\nexport * from './cache';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\nexport interface SDKRequestInit extends RequestInit {\n method?: HttpMethod;\n}\n\nexport enum CacheType {\n jingle = 'jingle',\n auth = 'auth',\n k8s = 'k8s',\n user = 'user',\n}\n\nexport type ApiConfiguration = {\n API_URL: string;\n};\n\nexport type CacheConfiguration = {\n [key in keyof typeof CacheType]?: AbstractCache;\n};\n\nexport class ErrorResponse extends Error {\n constructor(public readonly status: number, public readonly message: string) {\n super();\n }\n}\n\nexport class TssApi {\n auth: AuthModule;\n jingle: JingleModule;\n k8s: K8sModule;\n user: UserModule;\n\n constructor(protected readonly apiConfiguration: ApiConfiguration, cacheConfiguration?: CacheConfiguration) {\n this.jingle = new JingleModule(this, cacheConfiguration?.jingle ?? new NullCache('jingle'));\n this.auth = new AuthModule(this, cacheConfiguration?.auth ?? new NullCache('auth'));\n this.k8s = new K8sModule(this, cacheConfiguration?.k8s ?? new NullCache('k8s'));\n this.user = new UserModule(this, cacheConfiguration?.user ?? new NullCache('user'));\n\n this.fetch('/auth/verify', {\n method: 'POST',\n yo: 'lo',\n });\n }\n\n async fetch(url: string, config: SDKRequestInit = {}) {\n config.method = config.method ?? 'GET';\n config.headers = {\n ...config.headers,\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${await this.auth.getToken()}`,\n };\n\n const apiPrefix = this.apiConfiguration.API_URL;\n\n if (apiPrefix.match(/^https?:\\/\\/localhost/) !== null && typeof process !== 'undefined' && process.env) {\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';\n }\n\n const fullUrl = `${apiPrefix}/api/${url}`;\n console.log('Fetching url', fullUrl);\n\n let response;\n try {\n response = await fetch(fullUrl, config);\n } catch (e) {\n throw new ErrorResponse(503, 'API erg dood');\n }\n\n if (response.status >= 400) {\n const error = await response.json();\n throw new ErrorResponse(error.statusCode, error.message ?? error.error);\n }\n\n return response;\n }\n\n protected async fetchPossibleEmptyResponse<T>(\n method: HttpMethod,\n url: string,\n dto: Dto,\n config: SDKRequestInit = {},\n ) {\n return this.fetch(url, {\n method,\n ...config,\n body: JSON.stringify(dto),\n });\n }\n\n async get<T>(url: string) {\n const response = await this.fetch(url);\n return response.json() as Promise<T>;\n }\n\n async post<T>(url: string, dto: Dto, config: SDKRequestInit = {}) {\n const response = await this.fetchPossibleEmptyResponse<T>('POST', url, dto, config);\n if (response === undefined) {\n throw new Error('Response was undefined');\n }\n return (await response.json()) as Promise<T>;\n }\n\n async postPossibleEmptyResponse(url: string, dto: Dto) {\n return this.fetchPossibleEmptyResponse('POST', url, dto);\n }\n\n async put<T>(url: string, dto: Dto) {\n const response = await this.fetchPossibleEmptyResponse<T>('PUT', url, dto);\n if (response === undefined) {\n throw new Error('Response was undefined');\n }\n return (await response.json()) as Promise<T>;\n }\n\n async putPossibleEmptyResponse(url: string, dto: Dto) {\n return this.fetchPossibleEmptyResponse('PUT', url, dto);\n }\n\n async delete<T>(url: string, config: SDKRequestInit = {}) {\n return this.fetch(url, {\n method: 'DELETE',\n ...config,\n });\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;AAAO,SAAS,IAAI,SAAS;AAC3B,QAAM,WAAW,MAAM;AACvB,QAAM,kBAAkB;AAExB,QAAM,cAAc,CAAC;AAErB,QAAM,YAAY,MAAM;AACxB,QAAM,oBAAoB,SAASA,cAAaC,eAAc;AAC5D,WAAOA;AAAA,EACT;AACA,QAAM,kBAAkB,aAAa,WAAW,GAAG;AAEnD,QAAM,eAAe,YAAY;AACjC,QAAM,oBAAoB;AAC1B,QAAM,kBAAkB;AAExB,SAAO;AACT;AA6EA,SAAS,SAAS,YAAY;AAC5B,aAAW,YAAY,YAAY;AACjC,SAAK,QAAQ,IAAI,WAAW,QAAQ;AAAA,EACtC;AACF;AAEA,IAAM,gBAAgB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,cAAc,QAAQ,SAAU,UAAU;AACxC,WAAS,UAAU,QAAQ,IAAI;AAC/B,WAAS,UAAU,QAAQ,SAAS,CAAC,EAAE,YAAY,IAAI,SAAS,OAAO,CAAC,CAAC,IAAI,WAAY;AACvF,WAAO,KAAK,QAAQ;AAAA,EACtB;AACF,CAA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UAAM,WAAW,MAAM,KAAK,MAAM,GAAG;AACrC,WAAO,SAAS,KAAK;AAAA,EACzB;AAAA,EAEA,MAAM,KAAQ,KAAa,KAAU,SAAyB,CAAC,GAAG;AAC9D,UAAM,WAAW,MAAM,KAAK,2BAA8B,QAAQ,KAAK,KAAK,MAAM;AAClF,QAAI,aAAa,QAAW;AACxB,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC5C;AACA,WAAQ,MAAM,SAAS,KAAK;AAAA,EAChC;AAAA,EAEA,MAAM,0BAA0B,KAAa,KAAU;AACnD,WAAO,KAAK,2BAA2B,QAAQ,KAAK,GAAG;AAAA,EAC3D;AAAA,EAEA,MAAM,IAAO,KAAa,KAAU;AAChC,UAAM,WAAW,MAAM,KAAK,2BAA8B,OAAO,KAAK,GAAG;AACzE,QAAI,aAAa,QAAW;AACxB,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC5C;AACA,WAAQ,MAAM,SAAS,KAAK;AAAA,EAChC;AAAA,EAEA,MAAM,yBAAyB,KAAa,KAAU;AAClD,WAAO,KAAK,2BAA2B,OAAO,KAAK,GAAG;AAAA,EAC1D;AAAA,EAEA,MAAM,OAAU,KAAa,SAAyB,CAAC,GAAG;AACtD,WAAO,KAAK,MAAM,KAAK;AAAA,MACnB,QAAQ;AAAA,MACR,GAAG;AAAA,IACP,CAAC;AAAA,EACL;AACJ;",
|
|
6
6
|
"names": ["dummyObject", "v8StackTrace", "CacheLifetime", "CacheType"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tering-serieuze-sdk",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.10.0",
|
|
4
4
|
"description": "Teringserieuze sdk",
|
|
5
5
|
"author": "Frank",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -29,12 +29,12 @@
|
|
|
29
29
|
"stack-trace": "^1.0.0-pre2"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@simplewebauthn/
|
|
33
|
-
"@types/node": "^18.
|
|
32
|
+
"@simplewebauthn/types": "^12.0.0",
|
|
33
|
+
"@types/node": "^18.19.4",
|
|
34
34
|
"@vitest/coverage-c8": "^0.28.5",
|
|
35
35
|
"esbuild": "^0.17.12",
|
|
36
36
|
"prettier": "^2.8.1",
|
|
37
|
-
"tering-serieuze-types": "^1.
|
|
37
|
+
"tering-serieuze-types": "^1.24.0",
|
|
38
38
|
"vitest": "^0.28.5"
|
|
39
39
|
}
|
|
40
40
|
}
|
package/src/api/auth.ts
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
import { BaseModule } from
|
|
2
|
-
import { AuthenticationOptionsDto, VerificationResponseDto, type TokenContent } from
|
|
1
|
+
import { BaseModule } from './base';
|
|
2
|
+
import { AuthenticationOptionsDto, VerificationResponseDto, type TokenContent } from 'tering-serieuze-types';
|
|
3
3
|
import type {
|
|
4
4
|
AuthenticationResponseJSON,
|
|
5
5
|
PublicKeyCredentialCreationOptionsJSON,
|
|
6
6
|
RegistrationResponseJSON,
|
|
7
|
-
} from
|
|
7
|
+
} from '@simplewebauthn/types';
|
|
8
8
|
|
|
9
9
|
export function parseJwt<T>(token: string): T {
|
|
10
10
|
let jsonPayload;
|
|
11
11
|
|
|
12
|
-
if (typeof Buffer !==
|
|
13
|
-
jsonPayload = Buffer.from(token.split(
|
|
12
|
+
if (typeof Buffer !== 'undefined') {
|
|
13
|
+
jsonPayload = Buffer.from(token.split('.')[1], 'base64').toString();
|
|
14
14
|
} else {
|
|
15
|
-
const base64Url = token.split(
|
|
16
|
-
const base64 = base64Url.replace(/-/g,
|
|
15
|
+
const base64Url = token.split('.')[1];
|
|
16
|
+
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
|
|
17
17
|
jsonPayload = decodeURIComponent(
|
|
18
18
|
window
|
|
19
19
|
.atob(base64)
|
|
20
|
-
.split(
|
|
20
|
+
.split('')
|
|
21
21
|
.map(function (c) {
|
|
22
|
-
return
|
|
22
|
+
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
|
|
23
23
|
})
|
|
24
|
-
.join(
|
|
24
|
+
.join(''),
|
|
25
25
|
);
|
|
26
26
|
}
|
|
27
27
|
|
|
@@ -29,7 +29,7 @@ export function parseJwt<T>(token: string): T {
|
|
|
29
29
|
}
|
|
30
30
|
|
|
31
31
|
export class AuthModule extends BaseModule {
|
|
32
|
-
public static cacheKey =
|
|
32
|
+
public static cacheKey = 'TSS-TOKEN';
|
|
33
33
|
|
|
34
34
|
async getToken(): Promise<string | undefined> {
|
|
35
35
|
return process.env.TSS_TOKEN ?? this.cache.get(AuthModule.cacheKey);
|
|
@@ -41,7 +41,7 @@ export class AuthModule extends BaseModule {
|
|
|
41
41
|
|
|
42
42
|
async setCode(code: string) {
|
|
43
43
|
// TODO any ?!
|
|
44
|
-
const { accessToken } = await this.api.post<any>(`auth/setCode?code=${code}`, {}, { credentials:
|
|
44
|
+
const { accessToken } = await this.api.post<any>(`auth/setCode?code=${code}`, {}, { credentials: 'include' });
|
|
45
45
|
return accessToken;
|
|
46
46
|
}
|
|
47
47
|
|
|
@@ -51,13 +51,13 @@ export class AuthModule extends BaseModule {
|
|
|
51
51
|
|
|
52
52
|
async getSessionId() {
|
|
53
53
|
const token = await this.getToken();
|
|
54
|
-
const { sessionId } = parseJwt<TokenContent>(token ??
|
|
54
|
+
const { sessionId } = parseJwt<TokenContent>(token ?? '');
|
|
55
55
|
return sessionId;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
async removeSession(sessionId?: string) {
|
|
59
59
|
const session = sessionId ?? (await this.getSessionId());
|
|
60
|
-
await this.api.delete(`session/${session}`, { credentials:
|
|
60
|
+
await this.api.delete(`session/${session}`, { credentials: 'include' });
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
async logout() {
|
|
@@ -70,20 +70,20 @@ export class AuthModule extends BaseModule {
|
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
async getAuthenticationOptions() {
|
|
73
|
-
return this.api.get<AuthenticationOptionsDto>(
|
|
73
|
+
return this.api.get<AuthenticationOptionsDto>('auth/authentication-options');
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
async verifyRegistration(registrationToken: string, registrationResponse: RegistrationResponseJSON) {
|
|
77
77
|
return this.api.post<VerificationResponseDto>(
|
|
78
78
|
`auth/verify-registration/${registrationToken}`,
|
|
79
79
|
registrationResponse,
|
|
80
|
-
{ credentials:
|
|
80
|
+
{ credentials: 'include' },
|
|
81
81
|
);
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
async verifyAuthentication(token: string, response: AuthenticationResponseJSON) {
|
|
85
85
|
return this.api.post<VerificationResponseDto>(`auth/verify-authentication/${token}`, response, {
|
|
86
|
-
credentials:
|
|
86
|
+
credentials: 'include',
|
|
87
87
|
});
|
|
88
88
|
}
|
|
89
89
|
}
|
package/src/api/base.ts
CHANGED
package/src/api/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export * from
|
|
2
|
-
export * from
|
|
3
|
-
export * from
|
|
4
|
-
export * from
|
|
1
|
+
export * from './auth';
|
|
2
|
+
export * from './jingle';
|
|
3
|
+
export * from './k8s';
|
|
4
|
+
export * from './user';
|
package/src/api/jingle.ts
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import type { JingleFolder, Jingle, PlayJingleDto, BigBrotherItem } from
|
|
2
|
-
import { BaseModule } from
|
|
3
|
-
import { CacheLifetime } from
|
|
1
|
+
import type { JingleFolder, Jingle, PlayJingleDto, BigBrotherItem } from 'tering-serieuze-types';
|
|
2
|
+
import { BaseModule } from './base';
|
|
3
|
+
import { CacheLifetime } from '../cache';
|
|
4
4
|
|
|
5
5
|
export class JingleModule extends BaseModule {
|
|
6
6
|
async getGrouped(): Promise<JingleFolder[]> {
|
|
7
7
|
return this.cache.cacheOrGet(
|
|
8
8
|
() => {
|
|
9
|
-
return this.api.get<JingleFolder[]>(
|
|
9
|
+
return this.api.get<JingleFolder[]>('jingle/grouped');
|
|
10
10
|
},
|
|
11
|
-
|
|
12
|
-
CacheLifetime.Day
|
|
11
|
+
'getGrouped',
|
|
12
|
+
CacheLifetime.Day,
|
|
13
13
|
);
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
async getAll(): Promise<Jingle[]> {
|
|
17
17
|
return this.cache.cacheOrGet(
|
|
18
18
|
() => {
|
|
19
|
-
return this.api.get<Jingle[]>(
|
|
19
|
+
return this.api.get<Jingle[]>('jingle');
|
|
20
20
|
},
|
|
21
|
-
|
|
22
|
-
CacheLifetime.Day
|
|
21
|
+
'getAll',
|
|
22
|
+
CacheLifetime.Day,
|
|
23
23
|
);
|
|
24
24
|
}
|
|
25
25
|
|
|
@@ -30,19 +30,19 @@ export class JingleModule extends BaseModule {
|
|
|
30
30
|
|
|
31
31
|
async play(playJingleDto: PlayJingleDto) {
|
|
32
32
|
console.log(`Playing jingle ${playJingleDto.folder}/${playJingleDto.file}`);
|
|
33
|
-
return this.api.post(
|
|
33
|
+
return this.api.post('jingle/play', playJingleDto);
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
async getBigBrotherData(): Promise<BigBrotherItem[]> {
|
|
37
|
-
return this.api.get<BigBrotherItem[]>(
|
|
37
|
+
return this.api.get<BigBrotherItem[]>('jingle/bigbrother');
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
async find(query: string, jingles: Jingle[] = []): Promise<Jingle[]> {
|
|
41
41
|
jingles = jingles.length ? jingles : await this.getAll();
|
|
42
42
|
|
|
43
|
-
const queryParts = query.split(
|
|
43
|
+
const queryParts = query.split(' ');
|
|
44
44
|
const matches = jingles.filter((jingle) =>
|
|
45
|
-
queryParts.every((queryPart) => (jingle.folder +
|
|
45
|
+
queryParts.every((queryPart) => (jingle.folder + '/' + jingle.file).includes(queryPart)),
|
|
46
46
|
);
|
|
47
47
|
|
|
48
48
|
return matches.sort((a, b) => {
|
package/src/api/k8s.ts
CHANGED
package/src/api/user.ts
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import { BaseModule } from
|
|
2
|
-
import type { SetWindowStateDto, User } from
|
|
1
|
+
import { BaseModule } from './base';
|
|
2
|
+
import type { SetWindowStateDto, User } from 'tering-serieuze-types';
|
|
3
3
|
|
|
4
4
|
export class UserModule extends BaseModule {
|
|
5
5
|
async get(userId?: string) {
|
|
6
6
|
return this.cache.cacheOrGet(() => {
|
|
7
|
-
const userIdParam = userId ? `/${userId}` :
|
|
7
|
+
const userIdParam = userId ? `/${userId}` : '';
|
|
8
8
|
return this.api.get<User>(`user${userIdParam}`);
|
|
9
9
|
});
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
async getAll() {
|
|
13
13
|
return this.cache.cacheOrGet(() => {
|
|
14
|
-
return this.api.get<User[]>(
|
|
14
|
+
return this.api.get<User[]>('user/all');
|
|
15
15
|
});
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
async setWindowState(setWindowStateDto: SetWindowStateDto) {
|
|
19
|
-
return this.api.putPossibleEmptyResponse(
|
|
19
|
+
return this.api.putPossibleEmptyResponse('user/windowState', setWindowStateDto);
|
|
20
20
|
}
|
|
21
21
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { get } from
|
|
1
|
+
import { get } from 'stack-trace';
|
|
2
2
|
|
|
3
3
|
export enum CacheLifetime {
|
|
4
4
|
Day = 60 * 60 * 24 * 1000,
|
|
@@ -19,7 +19,7 @@ export abstract class AbstractCache {
|
|
|
19
19
|
public abstract clear(): void;
|
|
20
20
|
|
|
21
21
|
public getCacheKey(): string {
|
|
22
|
-
const errorMessage =
|
|
22
|
+
const errorMessage = 'Could not determine cache key. Please provide a key manually.';
|
|
23
23
|
const trace = get();
|
|
24
24
|
if (trace.length < 3) {
|
|
25
25
|
throw new Error(errorMessage);
|
package/src/cache/cookieCache.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import { AbstractCache } from
|
|
1
|
+
import { AbstractCache } from './abstractCache';
|
|
2
2
|
|
|
3
3
|
export class CookieCache extends AbstractCache {
|
|
4
4
|
public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {
|
|
5
|
-
throw new Error(
|
|
5
|
+
throw new Error('Not implemented, use get() and set()');
|
|
6
6
|
}
|
|
7
7
|
|
|
8
8
|
public async get<T>(key: string): Promise<T | undefined> {
|
|
9
9
|
if (document.cookie.includes(`${key}=`)) {
|
|
10
|
-
return document.cookie.split(`${key}=`)[1]?.split(
|
|
10
|
+
return document.cookie.split(`${key}=`)[1]?.split(';')[0] as T;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
return undefined;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
public set<T>(key: string, value: T, lifetime?: number): void {
|
|
17
|
-
const expires = lifetime ? new Date(Date.now() + lifetime).toUTCString() :
|
|
17
|
+
const expires = lifetime ? new Date(Date.now() + lifetime).toUTCString() : '';
|
|
18
18
|
document.cookie = `${key}=${value}; expires=${expires}; path=/; samesite=strict; secure`;
|
|
19
19
|
}
|
|
20
20
|
|
|
@@ -23,6 +23,6 @@ export class CookieCache extends AbstractCache {
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
public clear(): void {
|
|
26
|
-
throw new Error(
|
|
26
|
+
throw new Error('Not implemented, use remove()');
|
|
27
27
|
}
|
|
28
28
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { AbstractCache } from
|
|
2
|
-
import fs from
|
|
3
|
-
import path from
|
|
4
|
-
import os from
|
|
1
|
+
import { AbstractCache } from './abstractCache';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import os from 'os';
|
|
5
5
|
|
|
6
6
|
type CacheItem = {
|
|
7
7
|
value: any;
|
|
@@ -62,13 +62,13 @@ export class FilesystemCache extends AbstractCache {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
public getFilePath() {
|
|
65
|
-
return path.join(os.homedir(),
|
|
65
|
+
return path.join(os.homedir(), '.tss', `${this.cacheName}.json`);
|
|
66
66
|
}
|
|
67
67
|
|
|
68
68
|
protected _initialize() {
|
|
69
69
|
this.initialized = true;
|
|
70
70
|
if (fs.existsSync(this.getFilePath())) {
|
|
71
|
-
this.state = JSON.parse(fs.readFileSync(this.getFilePath(),
|
|
71
|
+
this.state = JSON.parse(fs.readFileSync(this.getFilePath(), 'utf8'));
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
74
|
|
package/src/cache/index.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export * from
|
|
2
|
-
export * from
|
|
3
|
-
export * from
|
|
4
|
-
export * from
|
|
5
|
-
export * from
|
|
1
|
+
export * from './abstractCache';
|
|
2
|
+
export * from './cookieCache';
|
|
3
|
+
export * from './filesystemCache';
|
|
4
|
+
export * from './nullCache';
|
|
5
|
+
export * from './onePasswordCache';
|
package/src/cache/nullCache.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { AbstractCache } from
|
|
2
|
-
import util from
|
|
3
|
-
import child_process from
|
|
1
|
+
import { AbstractCache } from './abstractCache';
|
|
2
|
+
import util from 'util';
|
|
3
|
+
import child_process from 'child_process';
|
|
4
4
|
|
|
5
5
|
// TODO error handling en lifetime
|
|
6
6
|
export class OnePasswordCache extends AbstractCache {
|
|
7
7
|
protected asyncExec = util.promisify(child_process.exec);
|
|
8
8
|
|
|
9
9
|
public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {
|
|
10
|
-
throw new Error(
|
|
10
|
+
throw new Error('Not implemented, use get() and set()');
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
public async get<T>(key: string): Promise<T | undefined> {
|
|
@@ -15,7 +15,7 @@ export class OnePasswordCache extends AbstractCache {
|
|
|
15
15
|
|
|
16
16
|
if (stderr) {
|
|
17
17
|
console.log(stderr);
|
|
18
|
-
throw new Error(
|
|
18
|
+
throw new Error('ERROR');
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
return JSON.parse(stdout).value;
|
|
@@ -34,7 +34,7 @@ export class OnePasswordCache extends AbstractCache {
|
|
|
34
34
|
|
|
35
35
|
if (stderr) {
|
|
36
36
|
console.log(stderr);
|
|
37
|
-
throw new Error(
|
|
37
|
+
throw new Error('ERROR');
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
40
|
|
package/src/index.ts
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import { AbstractCache, NullCache } from
|
|
2
|
-
import { AuthModule, JingleModule, K8sModule, UserModule } from
|
|
3
|
-
import type { Dto } from
|
|
1
|
+
import { AbstractCache, NullCache } from './cache';
|
|
2
|
+
import { AuthModule, JingleModule, K8sModule, UserModule } from './api';
|
|
3
|
+
import type { Dto } from 'tering-serieuze-types';
|
|
4
4
|
|
|
5
|
-
export * from
|
|
6
|
-
export * from
|
|
5
|
+
export * from './api';
|
|
6
|
+
export * from './cache';
|
|
7
7
|
|
|
8
|
-
export type HttpMethod =
|
|
8
|
+
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
9
9
|
|
|
10
10
|
export interface SDKRequestInit extends RequestInit {
|
|
11
11
|
method?: HttpMethod;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
export enum CacheType {
|
|
15
|
-
jingle =
|
|
16
|
-
auth =
|
|
17
|
-
k8s =
|
|
18
|
-
user =
|
|
15
|
+
jingle = 'jingle',
|
|
16
|
+
auth = 'auth',
|
|
17
|
+
k8s = 'k8s',
|
|
18
|
+
user = 'user',
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
export type ApiConfiguration = {
|
|
@@ -39,34 +39,39 @@ export class TssApi {
|
|
|
39
39
|
user: UserModule;
|
|
40
40
|
|
|
41
41
|
constructor(protected readonly apiConfiguration: ApiConfiguration, cacheConfiguration?: CacheConfiguration) {
|
|
42
|
-
this.jingle = new JingleModule(this, cacheConfiguration?.jingle ?? new NullCache(
|
|
43
|
-
this.auth = new AuthModule(this, cacheConfiguration?.auth ?? new NullCache(
|
|
44
|
-
this.k8s = new K8sModule(this, cacheConfiguration?.k8s ?? new NullCache(
|
|
45
|
-
this.user = new UserModule(this, cacheConfiguration?.user ?? new NullCache(
|
|
42
|
+
this.jingle = new JingleModule(this, cacheConfiguration?.jingle ?? new NullCache('jingle'));
|
|
43
|
+
this.auth = new AuthModule(this, cacheConfiguration?.auth ?? new NullCache('auth'));
|
|
44
|
+
this.k8s = new K8sModule(this, cacheConfiguration?.k8s ?? new NullCache('k8s'));
|
|
45
|
+
this.user = new UserModule(this, cacheConfiguration?.user ?? new NullCache('user'));
|
|
46
|
+
|
|
47
|
+
this.fetch('/auth/verify', {
|
|
48
|
+
method: 'POST',
|
|
49
|
+
yo: 'lo',
|
|
50
|
+
});
|
|
46
51
|
}
|
|
47
52
|
|
|
48
53
|
async fetch(url: string, config: SDKRequestInit = {}) {
|
|
49
|
-
config.method = config.method ??
|
|
54
|
+
config.method = config.method ?? 'GET';
|
|
50
55
|
config.headers = {
|
|
51
56
|
...config.headers,
|
|
52
|
-
|
|
57
|
+
'Content-Type': 'application/json',
|
|
53
58
|
Authorization: `Bearer ${await this.auth.getToken()}`,
|
|
54
59
|
};
|
|
55
60
|
|
|
56
61
|
const apiPrefix = this.apiConfiguration.API_URL;
|
|
57
62
|
|
|
58
|
-
if (apiPrefix.match(/^https?:\/\/localhost/) !== null && typeof process !==
|
|
59
|
-
process.env.NODE_TLS_REJECT_UNAUTHORIZED =
|
|
63
|
+
if (apiPrefix.match(/^https?:\/\/localhost/) !== null && typeof process !== 'undefined' && process.env) {
|
|
64
|
+
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
|
|
60
65
|
}
|
|
61
66
|
|
|
62
67
|
const fullUrl = `${apiPrefix}/api/${url}`;
|
|
63
|
-
console.log(
|
|
68
|
+
console.log('Fetching url', fullUrl);
|
|
64
69
|
|
|
65
70
|
let response;
|
|
66
71
|
try {
|
|
67
72
|
response = await fetch(fullUrl, config);
|
|
68
73
|
} catch (e) {
|
|
69
|
-
throw new ErrorResponse(503,
|
|
74
|
+
throw new ErrorResponse(503, 'API erg dood');
|
|
70
75
|
}
|
|
71
76
|
|
|
72
77
|
if (response.status >= 400) {
|
|
@@ -81,7 +86,7 @@ export class TssApi {
|
|
|
81
86
|
method: HttpMethod,
|
|
82
87
|
url: string,
|
|
83
88
|
dto: Dto,
|
|
84
|
-
config: SDKRequestInit = {}
|
|
89
|
+
config: SDKRequestInit = {},
|
|
85
90
|
) {
|
|
86
91
|
return this.fetch(url, {
|
|
87
92
|
method,
|
|
@@ -96,32 +101,32 @@ export class TssApi {
|
|
|
96
101
|
}
|
|
97
102
|
|
|
98
103
|
async post<T>(url: string, dto: Dto, config: SDKRequestInit = {}) {
|
|
99
|
-
const response = await this.fetchPossibleEmptyResponse<T>(
|
|
104
|
+
const response = await this.fetchPossibleEmptyResponse<T>('POST', url, dto, config);
|
|
100
105
|
if (response === undefined) {
|
|
101
|
-
throw new Error(
|
|
106
|
+
throw new Error('Response was undefined');
|
|
102
107
|
}
|
|
103
108
|
return (await response.json()) as Promise<T>;
|
|
104
109
|
}
|
|
105
110
|
|
|
106
111
|
async postPossibleEmptyResponse(url: string, dto: Dto) {
|
|
107
|
-
return this.fetchPossibleEmptyResponse(
|
|
112
|
+
return this.fetchPossibleEmptyResponse('POST', url, dto);
|
|
108
113
|
}
|
|
109
114
|
|
|
110
115
|
async put<T>(url: string, dto: Dto) {
|
|
111
|
-
const response = await this.fetchPossibleEmptyResponse<T>(
|
|
116
|
+
const response = await this.fetchPossibleEmptyResponse<T>('PUT', url, dto);
|
|
112
117
|
if (response === undefined) {
|
|
113
|
-
throw new Error(
|
|
118
|
+
throw new Error('Response was undefined');
|
|
114
119
|
}
|
|
115
120
|
return (await response.json()) as Promise<T>;
|
|
116
121
|
}
|
|
117
122
|
|
|
118
123
|
async putPossibleEmptyResponse(url: string, dto: Dto) {
|
|
119
|
-
return this.fetchPossibleEmptyResponse(
|
|
124
|
+
return this.fetchPossibleEmptyResponse('PUT', url, dto);
|
|
120
125
|
}
|
|
121
126
|
|
|
122
127
|
async delete<T>(url: string, config: SDKRequestInit = {}) {
|
|
123
128
|
return this.fetch(url, {
|
|
124
|
-
method:
|
|
129
|
+
method: 'DELETE',
|
|
125
130
|
...config,
|
|
126
131
|
});
|
|
127
132
|
}
|
package/test/api/base.test.ts
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
import { describe, expect, it } from
|
|
2
|
-
import { BaseModule } from
|
|
3
|
-
import { TssApi, NullCache } from
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { BaseModule } from '../../src/api/base';
|
|
3
|
+
import { TssApi, NullCache } from '../../src';
|
|
4
4
|
|
|
5
|
-
describe(
|
|
6
|
-
it(
|
|
7
|
-
const cache = new NullCache(
|
|
5
|
+
describe('Base module', () => {
|
|
6
|
+
it('returns the cache', () => {
|
|
7
|
+
const cache = new NullCache('base');
|
|
8
8
|
const base = new BaseModule(
|
|
9
9
|
new TssApi({
|
|
10
10
|
API_URL: process.env.API_URL,
|
|
11
11
|
}),
|
|
12
|
-
cache
|
|
12
|
+
cache,
|
|
13
13
|
);
|
|
14
14
|
expect(base.getCache()).toBe(cache);
|
|
15
15
|
});
|
|
16
16
|
|
|
17
|
-
it(
|
|
18
|
-
const cache = new NullCache(
|
|
17
|
+
it('sets the cache', () => {
|
|
18
|
+
const cache = new NullCache('base');
|
|
19
19
|
const base = new BaseModule(
|
|
20
20
|
new TssApi({
|
|
21
21
|
API_URL: process.env.API_URL,
|
|
22
22
|
}),
|
|
23
|
-
cache
|
|
23
|
+
cache,
|
|
24
24
|
);
|
|
25
|
-
const newCache = new NullCache(
|
|
25
|
+
const newCache = new NullCache('base');
|
|
26
26
|
base.setCache(newCache);
|
|
27
27
|
expect(base.getCache()).toBe(newCache);
|
|
28
28
|
});
|
package/test/api/jingle.test.ts
CHANGED
|
@@ -1,35 +1,34 @@
|
|
|
1
|
-
import { describe, expect, it } from
|
|
2
|
-
import { TssApi, NullCache, OnePasswordCache } from
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { TssApi, NullCache, OnePasswordCache } from '../../src';
|
|
3
3
|
|
|
4
|
-
describe(
|
|
4
|
+
describe('Jingle API', () => {
|
|
5
5
|
const api = new TssApi(
|
|
6
6
|
{ API_URL: process.env.API_URL },
|
|
7
7
|
{
|
|
8
|
-
jingle: new NullCache(
|
|
9
|
-
auth: new OnePasswordCache(
|
|
10
|
-
}
|
|
8
|
+
jingle: new NullCache('jingle'),
|
|
9
|
+
auth: new OnePasswordCache('TSS-TOKEN'),
|
|
10
|
+
},
|
|
11
11
|
);
|
|
12
12
|
|
|
13
|
-
it(
|
|
13
|
+
it('Retrieves jingles when calling getGrouped', async () => {
|
|
14
14
|
const items = await api.jingle.getGrouped();
|
|
15
15
|
|
|
16
16
|
expect(items.length).toBeGreaterThan(0);
|
|
17
|
-
expect(items[0].folder).not.toBe(
|
|
17
|
+
expect(items[0].folder).not.toBe('');
|
|
18
18
|
expect(items[0].jingles).toBeInstanceOf(Array);
|
|
19
|
-
expect(items[0].jingles[0].file).not.toBe(
|
|
19
|
+
expect(items[0].jingles[0].file).not.toBe('');
|
|
20
20
|
});
|
|
21
21
|
|
|
22
|
-
it(
|
|
22
|
+
it('Retrieves jingles when calling getAll', async () => {
|
|
23
23
|
const items = await api.jingle.getAll();
|
|
24
24
|
|
|
25
25
|
expect(items.length).toBeGreaterThan(0);
|
|
26
|
-
expect(items[0].folder).not.toBe(
|
|
27
|
-
expect(items[0].file).not.toBe(
|
|
26
|
+
expect(items[0].folder).not.toBe('');
|
|
27
|
+
expect(items[0].file).not.toBe('');
|
|
28
28
|
});
|
|
29
29
|
|
|
30
|
-
it(
|
|
31
|
-
const result = await api.jingle.play({ folder:
|
|
32
|
-
// TODO fix dit
|
|
30
|
+
it('Plays a jingle', async () => {
|
|
31
|
+
const result: any = await api.jingle.play({ folder: 'keeskankerkachel', file: 'aan.mp3' });
|
|
33
32
|
expect(result.success).toBe(true);
|
|
34
33
|
});
|
|
35
34
|
});
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { afterEach, beforeEach, describe, expect, it, vi } from
|
|
2
|
-
import { FilesystemCache } from
|
|
3
|
-
import { existsSync, unlinkSync, writeFileSync } from
|
|
4
|
-
import path from
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { FilesystemCache } from '../../src/cache';
|
|
3
|
+
import { existsSync, unlinkSync, writeFileSync } from 'fs';
|
|
4
|
+
import path from 'path';
|
|
5
5
|
|
|
6
|
-
describe(
|
|
6
|
+
describe('filesystemCache', () => {
|
|
7
7
|
let cache: FilesystemCache;
|
|
8
8
|
|
|
9
9
|
beforeEach(() => {
|
|
@@ -18,22 +18,22 @@ describe("filesystemCache", () => {
|
|
|
18
18
|
vi.restoreAllMocks();
|
|
19
19
|
});
|
|
20
20
|
|
|
21
|
-
it(
|
|
21
|
+
it('Should call the callback only once', async () => {
|
|
22
22
|
const callback = vi.fn(() => Promise.resolve(1));
|
|
23
|
-
const result = await cache.cacheOrGet(callback,
|
|
23
|
+
const result = await cache.cacheOrGet(callback, 'key');
|
|
24
24
|
expect(result).toBe(1);
|
|
25
25
|
expect(callback).toBeCalledTimes(1);
|
|
26
26
|
|
|
27
27
|
await Promise.all([
|
|
28
|
-
cache.cacheOrGet(callback,
|
|
29
|
-
cache.cacheOrGet(callback,
|
|
30
|
-
cache.cacheOrGet(callback,
|
|
28
|
+
cache.cacheOrGet(callback, 'key'),
|
|
29
|
+
cache.cacheOrGet(callback, 'key'),
|
|
30
|
+
cache.cacheOrGet(callback, 'key'),
|
|
31
31
|
]);
|
|
32
32
|
expect(callback).toBeCalledTimes(1);
|
|
33
33
|
});
|
|
34
34
|
|
|
35
|
-
it(
|
|
36
|
-
const key =
|
|
35
|
+
it('Should call the callback only once when using the same key', async () => {
|
|
36
|
+
const key = 'test';
|
|
37
37
|
const callback = vi.fn(() => Promise.resolve(1));
|
|
38
38
|
const result = await cache.cacheOrGet(callback, key);
|
|
39
39
|
expect(result).toBe(1);
|
|
@@ -43,9 +43,9 @@ describe("filesystemCache", () => {
|
|
|
43
43
|
expect(callback).toBeCalledTimes(1);
|
|
44
44
|
});
|
|
45
45
|
|
|
46
|
-
it(
|
|
46
|
+
it('Should call the callback twice when using different keys', async () => {
|
|
47
47
|
const callback = vi.fn(() => Promise.resolve(1));
|
|
48
|
-
const result = await cache.cacheOrGet(callback,
|
|
48
|
+
const result = await cache.cacheOrGet(callback, 'key');
|
|
49
49
|
expect(result).toBe(1);
|
|
50
50
|
expect(callback).toBeCalledTimes(1);
|
|
51
51
|
|
|
@@ -53,35 +53,35 @@ describe("filesystemCache", () => {
|
|
|
53
53
|
expect(callback).toBeCalledTimes(2);
|
|
54
54
|
});
|
|
55
55
|
|
|
56
|
-
it(
|
|
56
|
+
it('Should throw an error when no key is passed and the function name can not be determined', async () => {
|
|
57
57
|
const callback = () => Promise.resolve(1);
|
|
58
58
|
await expect(cache.cacheOrGet(callback)).rejects.toThrowError();
|
|
59
59
|
});
|
|
60
60
|
|
|
61
|
-
it(
|
|
61
|
+
it('Should use the function name as key, when no key is passed', async () => {
|
|
62
62
|
let expected: number = 0;
|
|
63
63
|
await (async function doeHet() {
|
|
64
64
|
expected = await cache.cacheOrGet(() => Promise.resolve(50));
|
|
65
65
|
})();
|
|
66
66
|
|
|
67
67
|
const nonCalledFunction = vi.fn(() => Promise.resolve(1));
|
|
68
|
-
const result = await cache.cacheOrGet(nonCalledFunction,
|
|
68
|
+
const result = await cache.cacheOrGet(nonCalledFunction, 'doeHet');
|
|
69
69
|
expect(result).toBeGreaterThan(0);
|
|
70
70
|
expect(result).toBe(expected);
|
|
71
71
|
expect(nonCalledFunction).toBeCalledTimes(0);
|
|
72
72
|
});
|
|
73
73
|
|
|
74
|
-
it(
|
|
75
|
-
const key =
|
|
74
|
+
it('Should return the set value', async () => {
|
|
75
|
+
const key = 'test';
|
|
76
76
|
const value = 1;
|
|
77
77
|
cache.set(key, value);
|
|
78
78
|
const result = await cache.cacheOrGet(() => Promise.resolve(2), key);
|
|
79
79
|
expect(result).toBe(value);
|
|
80
80
|
});
|
|
81
81
|
|
|
82
|
-
it(
|
|
83
|
-
const key =
|
|
84
|
-
const otherKey =
|
|
82
|
+
it('Should be able to remove a value', async () => {
|
|
83
|
+
const key = 'test';
|
|
84
|
+
const otherKey = 'test2';
|
|
85
85
|
const correctValue = 123;
|
|
86
86
|
const otherCorrectValue = 456;
|
|
87
87
|
cache.set(key, 1);
|
|
@@ -95,47 +95,47 @@ describe("filesystemCache", () => {
|
|
|
95
95
|
expect(cachedValue).toBe(otherCorrectValue);
|
|
96
96
|
});
|
|
97
97
|
|
|
98
|
-
it(
|
|
98
|
+
it('Should be able to clear the cache', async () => {
|
|
99
99
|
expect(existsSync(cache.getFilePath())).toBe(false);
|
|
100
|
-
cache.set(
|
|
100
|
+
cache.set('test', 1);
|
|
101
101
|
expect(existsSync(cache.getFilePath())).toBe(true);
|
|
102
102
|
cache.clear();
|
|
103
103
|
expect(existsSync(cache.getFilePath())).toBe(false);
|
|
104
104
|
});
|
|
105
105
|
|
|
106
|
-
it(
|
|
107
|
-
const instance = new FilesystemCache(
|
|
106
|
+
it('Should use the cache when making a second instance', async () => {
|
|
107
|
+
const instance = new FilesystemCache('testfile2');
|
|
108
108
|
const callback = vi.fn(() => Promise.resolve(123));
|
|
109
|
-
await instance.cacheOrGet(callback,
|
|
109
|
+
await instance.cacheOrGet(callback, 'test');
|
|
110
110
|
|
|
111
|
-
const instance2 = new FilesystemCache(
|
|
112
|
-
await instance2.cacheOrGet(callback,
|
|
111
|
+
const instance2 = new FilesystemCache('testfile2');
|
|
112
|
+
await instance2.cacheOrGet(callback, 'test');
|
|
113
113
|
|
|
114
114
|
expect(callback).toBeCalledTimes(1);
|
|
115
115
|
|
|
116
116
|
instance2.clear();
|
|
117
117
|
});
|
|
118
118
|
|
|
119
|
-
it(
|
|
120
|
-
cache.set(
|
|
119
|
+
it('Should use the cache if a cache file already exists', async () => {
|
|
120
|
+
cache.set('test', 123);
|
|
121
121
|
|
|
122
122
|
const cacheName = path.basename(cache.getFilePath(), path.extname(cache.getFilePath()));
|
|
123
123
|
const instance = new FilesystemCache(cacheName);
|
|
124
124
|
const callback = vi.fn(() => Promise.resolve(789));
|
|
125
125
|
|
|
126
|
-
const result = await instance.cacheOrGet(callback,
|
|
126
|
+
const result = await instance.cacheOrGet(callback, 'test');
|
|
127
127
|
expect(result).toBe(123);
|
|
128
128
|
|
|
129
129
|
instance.clear();
|
|
130
130
|
});
|
|
131
131
|
|
|
132
|
-
it(
|
|
133
|
-
const result = await cache.cacheOrGet(() => Promise.resolve(1),
|
|
134
|
-
const result2 = await cache.cacheOrGet(() => Promise.resolve(1),
|
|
132
|
+
it('Should be able to set a custom cache lifetime', async () => {
|
|
133
|
+
const result = await cache.cacheOrGet(() => Promise.resolve(1), 'test', 1);
|
|
134
|
+
const result2 = await cache.cacheOrGet(() => Promise.resolve(1), 'test', 1);
|
|
135
135
|
expect(result).toBe(1);
|
|
136
136
|
expect(result2).toBe(1);
|
|
137
137
|
await new Promise((resolve) => setTimeout(resolve, 1100));
|
|
138
|
-
const result3 = await cache.cacheOrGet(() => Promise.resolve(2),
|
|
138
|
+
const result3 = await cache.cacheOrGet(() => Promise.resolve(2), 'test', 1);
|
|
139
139
|
expect(result3).toBe(2);
|
|
140
140
|
});
|
|
141
141
|
});
|
|
@@ -1,39 +1,39 @@
|
|
|
1
|
-
import { describe, expect, it, vi } from
|
|
2
|
-
import { NullCache } from
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { NullCache } from '../../src/cache';
|
|
3
3
|
|
|
4
|
-
describe(
|
|
5
|
-
const cache = new NullCache(
|
|
4
|
+
describe('NullCache', () => {
|
|
5
|
+
const cache = new NullCache('nullCache');
|
|
6
6
|
|
|
7
|
-
it(
|
|
8
|
-
const input =
|
|
7
|
+
it('should return the same value', async () => {
|
|
8
|
+
const input = 'hoi';
|
|
9
9
|
const output = await cache.cacheOrGet(() => Promise.resolve(input));
|
|
10
10
|
expect(output).toBe(input);
|
|
11
11
|
});
|
|
12
12
|
|
|
13
|
-
it(
|
|
14
|
-
const input =
|
|
13
|
+
it('should return the same value when using a key', async () => {
|
|
14
|
+
const input = 'hoi';
|
|
15
15
|
const callback = vi.fn(() => Promise.resolve(input));
|
|
16
|
-
const output = await cache.cacheOrGet(callback,
|
|
16
|
+
const output = await cache.cacheOrGet(callback, 'key');
|
|
17
17
|
expect(input).toBe(output);
|
|
18
18
|
expect(callback).toBeCalledTimes(1);
|
|
19
19
|
});
|
|
20
20
|
|
|
21
|
-
it(
|
|
22
|
-
const key =
|
|
23
|
-
const input =
|
|
24
|
-
cache.set(key,
|
|
21
|
+
it('should not do anything when calling set', async () => {
|
|
22
|
+
const key = 'key';
|
|
23
|
+
const input = 'hoi';
|
|
24
|
+
cache.set(key, 'invalid value');
|
|
25
25
|
const output = await cache.cacheOrGet(() => Promise.resolve(input), key);
|
|
26
26
|
expect(input).toBe(output);
|
|
27
27
|
});
|
|
28
28
|
|
|
29
29
|
it("Can't test remove and clear", () => {
|
|
30
30
|
const coverage = 100;
|
|
31
|
-
cache.remove(
|
|
31
|
+
cache.remove('test');
|
|
32
32
|
cache.clear();
|
|
33
33
|
expect(coverage).toBe(100);
|
|
34
34
|
});
|
|
35
35
|
|
|
36
|
-
it(
|
|
36
|
+
it('Should throw an error when no key is provided', () => {
|
|
37
37
|
let catchedException = false;
|
|
38
38
|
try {
|
|
39
39
|
cache.getCacheKey();
|