prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import { Context, MiddlewareHandler } from 'hono' import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types' import { After, Append, AppendGlobalCode, Before, Prepend, Remove, RemoveAndKeepContent, RemoveAttribute, Replace, SetAttribute, SetInnerContent, SetStyleProperty, } from './htmlRewriterClasses' export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => { if (!options.url) { options.url = 'https://edge-api.exporio.cloud' } if (!options.apiKey) { throw new Error('Exporio middleware requires options for "apiKey"') } return async (c, next) => { const exporioInstructions = await fetchExporioInstructions(c, options) if (!exporioInstructions) { c.set('contentUrl', c.req.url) await next() } else { c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url)) await next() applyRewriterInstruction(c, exporioInstructions) applyCookieInstruction(c.res.headers, exporioInstructions) } } } const buildRequestJson = (c: Context, apiKey: string): RequestJson => { const headersInit: HeadersInit = [] c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value])) return { originalRequest: { url: c.req.url, method: c.req.method, headersInit: headersInit, }, params: { API_KEY: apiKey, }, } } const fetchExporioInstructions = async ( c: Context, options: ExporioMiddlewareOptions ): Promise<Instructions | null> => { try { const requestJson = buildRequestJson(c, options.apiKey) const exporioRequest = new Request(options.url, { method: 'POST', body: JSON.stringify(requestJson), headers: { 'Content-Type': 'application/json' }, }) const exporioResponse = await fetch(exporioRequest) return await exporioResponse.json() } catch (err) { console.error('Failed to fetch exporio instructions', err) return null } } const getContentUrl = (instructions: Instructions, defaultUrl: string): string => { const customUrlInstruction = instructions?.customUrlInstruction return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl ? customUrlInstruction.customUrl : defaultUrl } const applyRewriterInstruction = (c: Context, instructions: Instructions) => { let response = new Response(c.res.body, c.res)
instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => {
switch (method) { // Default Methods case 'After': { const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2)) response = rewriter.transform(response) break } case 'Append': { const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2)) response = rewriter.transform(response) break } case 'Before': { const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2)) response = rewriter.transform(response) break } case 'Prepend': { const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2)) response = rewriter.transform(response) break } case 'Remove': { const rewriter = new HTMLRewriter().on(selector, new Remove()) response = rewriter.transform(response) break } case 'RemoveAndKeepContent': { const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent()) response = rewriter.transform(response) break } case 'RemoveAttribute': { const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1)) response = rewriter.transform(response) break } case 'Replace': { const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2)) response = rewriter.transform(response) break } case 'SetAttribute': { const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2)) response = rewriter.transform(response) break } case 'SetInnerContent': { const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2)) response = rewriter.transform(response) break } // Custom Methods case 'AppendGlobalCode': { const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2)) response = rewriter.transform(response) break } case 'SetStyleProperty': { const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2)) response = rewriter.transform(response) break } } }) c.res = new Response(response.body, response) } const applyCookieInstruction = (headers: Headers, instructions: Instructions) => { instructions?.cookieInstruction?.cookies.forEach((cookie) => { let cookieAttributes = [`${cookie.name}=${cookie.value}`] if (cookie.domain) { cookieAttributes.push(`Domain=${cookie.domain}`) } if (cookie.path) { cookieAttributes.push(`Path=${cookie.path}`) } if (cookie.expires) { cookieAttributes.push(`Expires=${cookie.expires}`) } if (cookie.maxAge) { cookieAttributes.push(`Max-Age=${cookie.maxAge}`) } if (cookie.httpOnly) { cookieAttributes.push('HttpOnly') } if (cookie.secure) { cookieAttributes.push('Secure') } if (cookie.sameSite) { cookieAttributes.push(`SameSite=${cookie.sameSite}`) } if (cookie.partitioned) { cookieAttributes.push('Partitioned') } headers.append('Set-Cookie', cookieAttributes.join('; ')) }) }
src/index.ts
exporio-edge-sdk-hono-23bcafc
[ { "filename": "src/types/instructions.ts", "retrieved_chunk": " argument2: any\n}\ntype RewriterInstruction = {\n useRewriter: boolean\n transformations: Transformation[]\n}\ntype CustomUrlInstruction = {\n loadCustomUrl: boolean\n customUrl: string | null\n}", "score": 0.8622608184814453 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }", "score": 0.8410083651542664 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": " partitioned?: boolean\n}\ntype CookieInstruction = {\n setCookie: boolean\n cookies: Cookie[]\n}\ntype Transformation = {\n method: string\n selector: string\n argument1: any", "score": 0.8020058274269104 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'", "score": 0.7716073393821716 }, { "filename": "src/types/general.ts", "retrieved_chunk": "type ExporioMiddlewareOptions = {\n url: string\n apiKey: string\n}\ntype RequestJson = {\n originalRequest: {\n url: string\n method: string\n headersInit: HeadersInit\n }", "score": 0.7457137107849121 } ]
typescript
instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => {
import { Context, MiddlewareHandler } from 'hono' import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types' import { After, Append, AppendGlobalCode, Before, Prepend, Remove, RemoveAndKeepContent, RemoveAttribute, Replace, SetAttribute, SetInnerContent, SetStyleProperty, } from './htmlRewriterClasses' export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => { if (!options.url) { options.url = 'https://edge-api.exporio.cloud' } if (!options.apiKey) { throw new Error('Exporio middleware requires options for "apiKey"') } return async (c, next) => { const exporioInstructions = await fetchExporioInstructions(c, options) if (!exporioInstructions) { c.set('contentUrl', c.req.url) await next() } else { c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url)) await next() applyRewriterInstruction(c, exporioInstructions) applyCookieInstruction(c.res.headers, exporioInstructions) } } } const buildRequestJson = (c: Context
, apiKey: string): RequestJson => {
const headersInit: HeadersInit = [] c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value])) return { originalRequest: { url: c.req.url, method: c.req.method, headersInit: headersInit, }, params: { API_KEY: apiKey, }, } } const fetchExporioInstructions = async ( c: Context, options: ExporioMiddlewareOptions ): Promise<Instructions | null> => { try { const requestJson = buildRequestJson(c, options.apiKey) const exporioRequest = new Request(options.url, { method: 'POST', body: JSON.stringify(requestJson), headers: { 'Content-Type': 'application/json' }, }) const exporioResponse = await fetch(exporioRequest) return await exporioResponse.json() } catch (err) { console.error('Failed to fetch exporio instructions', err) return null } } const getContentUrl = (instructions: Instructions, defaultUrl: string): string => { const customUrlInstruction = instructions?.customUrlInstruction return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl ? customUrlInstruction.customUrl : defaultUrl } const applyRewriterInstruction = (c: Context, instructions: Instructions) => { let response = new Response(c.res.body, c.res) instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { switch (method) { // Default Methods case 'After': { const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2)) response = rewriter.transform(response) break } case 'Append': { const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2)) response = rewriter.transform(response) break } case 'Before': { const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2)) response = rewriter.transform(response) break } case 'Prepend': { const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2)) response = rewriter.transform(response) break } case 'Remove': { const rewriter = new HTMLRewriter().on(selector, new Remove()) response = rewriter.transform(response) break } case 'RemoveAndKeepContent': { const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent()) response = rewriter.transform(response) break } case 'RemoveAttribute': { const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1)) response = rewriter.transform(response) break } case 'Replace': { const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2)) response = rewriter.transform(response) break } case 'SetAttribute': { const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2)) response = rewriter.transform(response) break } case 'SetInnerContent': { const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2)) response = rewriter.transform(response) break } // Custom Methods case 'AppendGlobalCode': { const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2)) response = rewriter.transform(response) break } case 'SetStyleProperty': { const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2)) response = rewriter.transform(response) break } } }) c.res = new Response(response.body, response) } const applyCookieInstruction = (headers: Headers, instructions: Instructions) => { instructions?.cookieInstruction?.cookies.forEach((cookie) => { let cookieAttributes = [`${cookie.name}=${cookie.value}`] if (cookie.domain) { cookieAttributes.push(`Domain=${cookie.domain}`) } if (cookie.path) { cookieAttributes.push(`Path=${cookie.path}`) } if (cookie.expires) { cookieAttributes.push(`Expires=${cookie.expires}`) } if (cookie.maxAge) { cookieAttributes.push(`Max-Age=${cookie.maxAge}`) } if (cookie.httpOnly) { cookieAttributes.push('HttpOnly') } if (cookie.secure) { cookieAttributes.push('Secure') } if (cookie.sameSite) { cookieAttributes.push(`SameSite=${cookie.sameSite}`) } if (cookie.partitioned) { cookieAttributes.push('Partitioned') } headers.append('Set-Cookie', cookieAttributes.join('; ')) }) }
src/index.ts
exporio-edge-sdk-hono-23bcafc
[ { "filename": "src/types/general.ts", "retrieved_chunk": "type ExporioMiddlewareOptions = {\n url: string\n apiKey: string\n}\ntype RequestJson = {\n originalRequest: {\n url: string\n method: string\n headersInit: HeadersInit\n }", "score": 0.8430843353271484 }, { "filename": "src/types/general.ts", "retrieved_chunk": " params: {\n API_KEY: string\n [key: string]: any\n }\n}\nexport { ExporioMiddlewareOptions, RequestJson }", "score": 0.8190698027610779 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'", "score": 0.8075956106185913 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": " partitioned?: boolean\n}\ntype CookieInstruction = {\n setCookie: boolean\n cookies: Cookie[]\n}\ntype Transformation = {\n method: string\n selector: string\n argument1: any", "score": 0.7889541387557983 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }", "score": 0.7835835218429565 } ]
typescript
, apiKey: string): RequestJson => {
/* * Copyright (c) AXA Group Operations Spain S.A. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { NlpManager } from '../nlp'; import MemoryConversationContext from './memory-conversation-context'; /** * Microsoft Bot Framework compatible recognizer for nlp.js. */ class Recognizer { private readonly nlpManager: NlpManager; private readonly threshold: number; private readonly conversationContext: MemoryConversationContext; /** * Constructor of the class. * @param {Object} settings Settings for the instance. */ constructor(private readonly settings: { nlpManager?: NlpManager; container?: any; nerThreshold?: number; threshold?: number; conversationContext?: MemoryConversationContext; }) { this.nlpManager = this.settings.nlpManager || new NlpManager({ container: this.settings.container, ner: { threshold: this.settings.nerThreshold || 1 }, }); this.threshold = this.settings.threshold || 0.7; this.conversationContext = this.settings.conversationContext || new MemoryConversationContext({}); } /** * Train the NLP manager. */ public async train(): Promise<void> { await this.nlpManager.train(); } /** * Loads the model from a file. * @param {String} filename Name of the file. */ public load(filename: string): void { this.nlpManager.load(filename); } /** * Saves the model into a file. * @param {String} filename Name of the file. */ public save(filename: string): void { this.nlpManager.save(filename); } /** * Loads the NLP manager from an excel. * @param {String} filename Name of the file. */ public async loadExcel(filename: string): Promise<void> { this.nlpManager.loadExcel(filename); await this.train(); this.save(filename); } /** * Process an utterance using the NLP manager. This is done using a given context * as the context object. * @param {Object} srcContext Source context * @param {String} locale Locale of the utterance. * @param {String} utterance Locale of the utterance. */ public async process( srcContext: Record<string, unknown>, locale?: string, utterance?: string ): Promise<string> { const context = srcContext || {}; const response = await (locale
? this.nlpManager.process(locale, utterance, context) : this.nlpManager.process(utterance, undefined, context));
if (response.score < this.threshold || response.intent === 'None') { response.answer = undefined; return response; } for (let i = 0; i < response.entities.length; i += 1) { const entity = response.entities[i]; context[entity.entity] = entity.option; } if (response.slotFill) { context.slotFill = response.slotFill; } else { delete context.slotFill; } return response; } /** * Given an utterance and the locale, returns the recognition of the utterance. * @param {String} utterance Utterance to be recognized. * @param {String} model Model of the utterance. * @param {Function} cb Callback Function. */ public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> { const response = await this.process( model, model ? model.locale : undefined, utterance ); return cb(null, response); } } export default Recognizer;
src/recognizer/recognizer.ts
Leoglme-node-nlp-typescript-fbee5fd
[ { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " async train(): Promise<void> {\n return this.nlp.train();\n }\n classify(locale: string, utterance: string, settings?: Record<string, unknown>): Promise<any> {\n return this.nlp.classify(locale, utterance, settings);\n }\n async process(locale?: string, utterance?: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {\n const result = await this.nlp.process(locale, utterance, context, settings);\n if (this.settings.processTransformer) {\n return this.settings.processTransformer(result);", "score": 0.8772976398468018 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " }\n return result;\n }\n extractEntities(locale: string, utterance: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {\n return this.nlp.extractEntities(locale, utterance, context, settings);\n }\n toObj(): any {\n return this.nlp.toJSON();\n }\n fromObj(obj: any): any {", "score": 0.8375251889228821 }, { "filename": "src/sentiment/sentiment-analyzer.ts", "retrieved_chunk": " this.container.use(Nlu);\n }\n async getSentiment(utterance: string, locale = 'en', settings: [key: string]) {\n const input = {\n utterance,\n locale,\n ...settings,\n };\n const result = await this.process(input);\n return result.sentiment;", "score": 0.8282669186592102 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " return this.nlp.addAnswer(locale, intent, answer, opts);\n }\n removeAnswer(locale: string, intent: string, answer: string, opts?: any): boolean {\n return this.nlp.removeAnswer(locale, intent, answer, opts);\n }\n findAllAnswers(locale: string, intent: string): string[] {\n return this.nlp.findAllAnswers(locale, intent);\n }\n async getSentiment(locale: string, utterance: string): Promise<{ numHits: number; score: number; comparative: number; language: string; numWords: number; type: string; vote: any }> {\n const sentiment = await this.nlp.getSentiment(locale, utterance);", "score": 0.8215302228927612 }, { "filename": "src/types/@nlpjs/nlu.d.ts", "retrieved_chunk": " settings: NluNeuralSettings;\n train(corpus: any[], settings?: NluNeuralSettings): Promise<void>;\n process(utterance: string, context?: any): Promise<{\n classifications: Array<{\n intent: string;\n score: number;\n }>;\n }>;\n }\n export class NluNeuralManager {", "score": 0.818453311920166 } ]
typescript
? this.nlpManager.process(locale, utterance, context) : this.nlpManager.process(utterance, undefined, context));
import { Context, MiddlewareHandler } from 'hono' import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types' import { After, Append, AppendGlobalCode, Before, Prepend, Remove, RemoveAndKeepContent, RemoveAttribute, Replace, SetAttribute, SetInnerContent, SetStyleProperty, } from './htmlRewriterClasses' export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => { if (!options.url) { options.url = 'https://edge-api.exporio.cloud' } if (!options.apiKey) { throw new Error('Exporio middleware requires options for "apiKey"') } return async (c, next) => { const exporioInstructions = await fetchExporioInstructions(c, options) if (!exporioInstructions) { c.set('contentUrl', c.req.url) await next() } else { c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url)) await next() applyRewriterInstruction(c, exporioInstructions) applyCookieInstruction(c.res.headers, exporioInstructions) } } } const buildRequestJson = (c: Context, apiKey: string): RequestJson => { const headersInit: HeadersInit = [] c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value])) return { originalRequest: { url: c.req.url, method: c.req.method, headersInit: headersInit, }, params: { API_KEY: apiKey, }, } } const fetchExporioInstructions = async ( c: Context, options: ExporioMiddlewareOptions ): Promise<Instructions | null> => { try { const requestJson = buildRequestJson(c, options.apiKey) const exporioRequest = new Request(options.url, { method: 'POST', body: JSON.stringify(requestJson), headers: { 'Content-Type': 'application/json' }, }) const exporioResponse = await fetch(exporioRequest) return await exporioResponse.json() } catch (err) { console.error('Failed to fetch exporio instructions', err) return null } } const getContentUrl = (instructions: Instructions, defaultUrl: string): string => { const customUrlInstruction = instructions?.customUrlInstruction return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl ? customUrlInstruction.customUrl : defaultUrl } const applyRewriterInstruction = (c: Context, instructions: Instructions) => { let response = new Response(c.res.body, c.res) instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { switch (method) { // Default Methods case 'After': { const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2)) response = rewriter.transform(response) break } case 'Append': { const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2)) response = rewriter.transform(response) break } case 'Before': { const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2)) response = rewriter.transform(response) break } case 'Prepend': { const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2)) response = rewriter.transform(response) break } case 'Remove': { const rewriter = new HTMLRewriter().on(selector, new Remove()) response = rewriter.transform(response) break } case 'RemoveAndKeepContent': { const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent()) response = rewriter.transform(response) break } case 'RemoveAttribute': { const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1)) response = rewriter.transform(response) break } case 'Replace': { const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2)) response = rewriter.transform(response) break } case 'SetAttribute': { const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2)) response = rewriter.transform(response) break } case 'SetInnerContent': { const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2)) response = rewriter.transform(response) break } // Custom Methods case 'AppendGlobalCode': { const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2)) response = rewriter.transform(response) break } case 'SetStyleProperty': { const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2)) response = rewriter.transform(response) break } } }) c.res = new Response(response.body, response) } const applyCookieInstruction = (headers: Headers, instructions: Instructions) => { instructions
?.cookieInstruction?.cookies.forEach((cookie) => {
let cookieAttributes = [`${cookie.name}=${cookie.value}`] if (cookie.domain) { cookieAttributes.push(`Domain=${cookie.domain}`) } if (cookie.path) { cookieAttributes.push(`Path=${cookie.path}`) } if (cookie.expires) { cookieAttributes.push(`Expires=${cookie.expires}`) } if (cookie.maxAge) { cookieAttributes.push(`Max-Age=${cookie.maxAge}`) } if (cookie.httpOnly) { cookieAttributes.push('HttpOnly') } if (cookie.secure) { cookieAttributes.push('Secure') } if (cookie.sameSite) { cookieAttributes.push(`SameSite=${cookie.sameSite}`) } if (cookie.partitioned) { cookieAttributes.push('Partitioned') } headers.append('Set-Cookie', cookieAttributes.join('; ')) }) }
src/index.ts
exporio-edge-sdk-hono-23bcafc
[ { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }", "score": 0.8266538381576538 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": " partitioned?: boolean\n}\ntype CookieInstruction = {\n setCookie: boolean\n cookies: Cookie[]\n}\ntype Transformation = {\n method: string\n selector: string\n argument1: any", "score": 0.8167707324028015 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": " argument2: any\n}\ntype RewriterInstruction = {\n useRewriter: boolean\n transformations: Transformation[]\n}\ntype CustomUrlInstruction = {\n loadCustomUrl: boolean\n customUrl: string | null\n}", "score": 0.7897758483886719 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Cookie = {\n name: string\n value: string\n domain?: string\n path?: string\n expires?: string\n maxAge?: string\n httpOnly?: boolean\n secure?: boolean\n sameSite?: string", "score": 0.7661134004592896 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'", "score": 0.7635158896446228 } ]
typescript
?.cookieInstruction?.cookies.forEach((cookie) => {
import { Context, MiddlewareHandler } from 'hono' import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types' import { After, Append, AppendGlobalCode, Before, Prepend, Remove, RemoveAndKeepContent, RemoveAttribute, Replace, SetAttribute, SetInnerContent, SetStyleProperty, } from './htmlRewriterClasses' export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => { if (!options.url) { options.url = 'https://edge-api.exporio.cloud' } if (!options.apiKey) { throw new Error('Exporio middleware requires options for "apiKey"') } return async (c, next) => { const exporioInstructions = await fetchExporioInstructions(c, options) if (!exporioInstructions) { c.set('contentUrl', c.req.url) await next() } else { c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url)) await next() applyRewriterInstruction(c, exporioInstructions) applyCookieInstruction(c.res.headers, exporioInstructions) } } } const buildRequestJson = (c: Context, apiKey: string): RequestJson => { const headersInit: HeadersInit = [] c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value])) return { originalRequest: { url: c.req.url, method: c.req.method, headersInit: headersInit, }, params: { API_KEY: apiKey, }, } } const fetchExporioInstructions = async ( c: Context, options: ExporioMiddlewareOptions )
: Promise<Instructions | null> => {
try { const requestJson = buildRequestJson(c, options.apiKey) const exporioRequest = new Request(options.url, { method: 'POST', body: JSON.stringify(requestJson), headers: { 'Content-Type': 'application/json' }, }) const exporioResponse = await fetch(exporioRequest) return await exporioResponse.json() } catch (err) { console.error('Failed to fetch exporio instructions', err) return null } } const getContentUrl = (instructions: Instructions, defaultUrl: string): string => { const customUrlInstruction = instructions?.customUrlInstruction return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl ? customUrlInstruction.customUrl : defaultUrl } const applyRewriterInstruction = (c: Context, instructions: Instructions) => { let response = new Response(c.res.body, c.res) instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { switch (method) { // Default Methods case 'After': { const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2)) response = rewriter.transform(response) break } case 'Append': { const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2)) response = rewriter.transform(response) break } case 'Before': { const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2)) response = rewriter.transform(response) break } case 'Prepend': { const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2)) response = rewriter.transform(response) break } case 'Remove': { const rewriter = new HTMLRewriter().on(selector, new Remove()) response = rewriter.transform(response) break } case 'RemoveAndKeepContent': { const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent()) response = rewriter.transform(response) break } case 'RemoveAttribute': { const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1)) response = rewriter.transform(response) break } case 'Replace': { const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2)) response = rewriter.transform(response) break } case 'SetAttribute': { const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2)) response = rewriter.transform(response) break } case 'SetInnerContent': { const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2)) response = rewriter.transform(response) break } // Custom Methods case 'AppendGlobalCode': { const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2)) response = rewriter.transform(response) break } case 'SetStyleProperty': { const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2)) response = rewriter.transform(response) break } } }) c.res = new Response(response.body, response) } const applyCookieInstruction = (headers: Headers, instructions: Instructions) => { instructions?.cookieInstruction?.cookies.forEach((cookie) => { let cookieAttributes = [`${cookie.name}=${cookie.value}`] if (cookie.domain) { cookieAttributes.push(`Domain=${cookie.domain}`) } if (cookie.path) { cookieAttributes.push(`Path=${cookie.path}`) } if (cookie.expires) { cookieAttributes.push(`Expires=${cookie.expires}`) } if (cookie.maxAge) { cookieAttributes.push(`Max-Age=${cookie.maxAge}`) } if (cookie.httpOnly) { cookieAttributes.push('HttpOnly') } if (cookie.secure) { cookieAttributes.push('Secure') } if (cookie.sameSite) { cookieAttributes.push(`SameSite=${cookie.sameSite}`) } if (cookie.partitioned) { cookieAttributes.push('Partitioned') } headers.append('Set-Cookie', cookieAttributes.join('; ')) }) }
src/index.ts
exporio-edge-sdk-hono-23bcafc
[ { "filename": "src/types/general.ts", "retrieved_chunk": "type ExporioMiddlewareOptions = {\n url: string\n apiKey: string\n}\ntype RequestJson = {\n originalRequest: {\n url: string\n method: string\n headersInit: HeadersInit\n }", "score": 0.8300166130065918 }, { "filename": "src/types/general.ts", "retrieved_chunk": " params: {\n API_KEY: string\n [key: string]: any\n }\n}\nexport { ExporioMiddlewareOptions, RequestJson }", "score": 0.8295754194259644 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'", "score": 0.8182456493377686 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }", "score": 0.7609260082244873 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": " partitioned?: boolean\n}\ntype CookieInstruction = {\n setCookie: boolean\n cookies: Cookie[]\n}\ntype Transformation = {\n method: string\n selector: string\n argument1: any", "score": 0.7578349113464355 } ]
typescript
: Promise<Instructions | null> => {
import { Context, MiddlewareHandler } from 'hono' import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types' import { After, Append, AppendGlobalCode, Before, Prepend, Remove, RemoveAndKeepContent, RemoveAttribute, Replace, SetAttribute, SetInnerContent, SetStyleProperty, } from './htmlRewriterClasses' export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => { if (!options.url) { options.url = 'https://edge-api.exporio.cloud' } if (!options.apiKey) { throw new Error('Exporio middleware requires options for "apiKey"') } return async (c, next) => { const exporioInstructions = await fetchExporioInstructions(c, options) if (!exporioInstructions) { c.set('contentUrl', c.req.url) await next() } else { c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url)) await next() applyRewriterInstruction(c, exporioInstructions) applyCookieInstruction(c.res.headers, exporioInstructions) } } } const buildRequestJson = (c: Context, apiKey: string): RequestJson => { const headersInit: HeadersInit = [] c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value])) return { originalRequest: { url: c.req.url, method: c.req.method, headersInit: headersInit, }, params: { API_KEY: apiKey, }, } } const fetchExporioInstructions = async ( c: Context, options: ExporioMiddlewareOptions ): Promise<Instructions | null> => { try { const requestJson = buildRequestJson(c, options.apiKey) const exporioRequest = new Request(options.url, { method: 'POST', body: JSON.stringify(requestJson), headers: { 'Content-Type': 'application/json' }, }) const exporioResponse = await fetch(exporioRequest) return await exporioResponse.json() } catch (err) { console.error('Failed to fetch exporio instructions', err) return null } } const getContentUrl = (instructions: Instructions, defaultUrl: string): string => { const customUrlInstruction = instructions?.customUrlInstruction return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl ? customUrlInstruction.customUrl : defaultUrl } const applyRewriterInstruction = (c: Context, instructions: Instructions) => { let response = new Response(c.res.body, c.res) instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { switch (method) { // Default Methods case 'After': { const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2)) response = rewriter.transform(response) break } case 'Append': { const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2)) response = rewriter.transform(response) break } case 'Before': { const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2)) response = rewriter.transform(response) break } case 'Prepend': { const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2)) response = rewriter.transform(response) break } case 'Remove': { const rewriter = new HTMLRewriter().on(selector, new Remove()) response = rewriter.transform(response) break } case 'RemoveAndKeepContent': { const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent()) response = rewriter.transform(response) break } case 'RemoveAttribute': { const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1)) response = rewriter.transform(response) break } case 'Replace': { const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2)) response = rewriter.transform(response) break } case 'SetAttribute': { const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2)) response = rewriter.transform(response) break } case 'SetInnerContent': { const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2)) response = rewriter.transform(response) break } // Custom Methods case 'AppendGlobalCode': { const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2)) response = rewriter.transform(response) break } case 'SetStyleProperty': { const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2)) response = rewriter.transform(response) break } } }) c.res = new Response(response.body, response) } const applyCookieInstruction = (headers: Headers, instructions: Instructions) => {
instructions?.cookieInstruction?.cookies.forEach((cookie) => {
let cookieAttributes = [`${cookie.name}=${cookie.value}`] if (cookie.domain) { cookieAttributes.push(`Domain=${cookie.domain}`) } if (cookie.path) { cookieAttributes.push(`Path=${cookie.path}`) } if (cookie.expires) { cookieAttributes.push(`Expires=${cookie.expires}`) } if (cookie.maxAge) { cookieAttributes.push(`Max-Age=${cookie.maxAge}`) } if (cookie.httpOnly) { cookieAttributes.push('HttpOnly') } if (cookie.secure) { cookieAttributes.push('Secure') } if (cookie.sameSite) { cookieAttributes.push(`SameSite=${cookie.sameSite}`) } if (cookie.partitioned) { cookieAttributes.push('Partitioned') } headers.append('Set-Cookie', cookieAttributes.join('; ')) }) }
src/index.ts
exporio-edge-sdk-hono-23bcafc
[ { "filename": "src/types/instructions.ts", "retrieved_chunk": " partitioned?: boolean\n}\ntype CookieInstruction = {\n setCookie: boolean\n cookies: Cookie[]\n}\ntype Transformation = {\n method: string\n selector: string\n argument1: any", "score": 0.8428493142127991 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }", "score": 0.8200032711029053 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": " argument2: any\n}\ntype RewriterInstruction = {\n useRewriter: boolean\n transformations: Transformation[]\n}\ntype CustomUrlInstruction = {\n loadCustomUrl: boolean\n customUrl: string | null\n}", "score": 0.7999684810638428 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Cookie = {\n name: string\n value: string\n domain?: string\n path?: string\n expires?: string\n maxAge?: string\n httpOnly?: boolean\n secure?: boolean\n sameSite?: string", "score": 0.7798967361450195 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'", "score": 0.7643141746520996 } ]
typescript
instructions?.cookieInstruction?.cookies.forEach((cookie) => {
/* * Copyright (c) AXA Group Operations Spain S.A. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { NlpManager } from '../nlp'; import MemoryConversationContext from './memory-conversation-context'; /** * Microsoft Bot Framework compatible recognizer for nlp.js. */ class Recognizer { private readonly nlpManager: NlpManager; private readonly threshold: number; private readonly conversationContext: MemoryConversationContext; /** * Constructor of the class. * @param {Object} settings Settings for the instance. */ constructor(private readonly settings: { nlpManager?: NlpManager; container?: any; nerThreshold?: number; threshold?: number; conversationContext?: MemoryConversationContext; }) { this.nlpManager = this.settings.nlpManager || new NlpManager({ container: this.settings.container, ner: { threshold: this.settings.nerThreshold || 1 }, }); this.threshold = this.settings.threshold || 0.7; this.conversationContext = this.settings.conversationContext || new MemoryConversationContext({}); } /** * Train the NLP manager. */ public async train(): Promise<void> { await this.nlpManager.train(); } /** * Loads the model from a file. * @param {String} filename Name of the file. */ public load(filename: string): void { this.nlpManager.load(filename); } /** * Saves the model into a file. * @param {String} filename Name of the file. */ public save(filename: string): void {
this.nlpManager.save(filename);
} /** * Loads the NLP manager from an excel. * @param {String} filename Name of the file. */ public async loadExcel(filename: string): Promise<void> { this.nlpManager.loadExcel(filename); await this.train(); this.save(filename); } /** * Process an utterance using the NLP manager. This is done using a given context * as the context object. * @param {Object} srcContext Source context * @param {String} locale Locale of the utterance. * @param {String} utterance Locale of the utterance. */ public async process( srcContext: Record<string, unknown>, locale?: string, utterance?: string ): Promise<string> { const context = srcContext || {}; const response = await (locale ? this.nlpManager.process(locale, utterance, context) : this.nlpManager.process(utterance, undefined, context)); if (response.score < this.threshold || response.intent === 'None') { response.answer = undefined; return response; } for (let i = 0; i < response.entities.length; i += 1) { const entity = response.entities[i]; context[entity.entity] = entity.option; } if (response.slotFill) { context.slotFill = response.slotFill; } else { delete context.slotFill; } return response; } /** * Given an utterance and the locale, returns the recognition of the utterance. * @param {String} utterance Utterance to be recognized. * @param {String} model Model of the utterance. * @param {Function} cb Callback Function. */ public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> { const response = await this.process( model, model ? model.locale : undefined, utterance ); return cb(null, response); } } export default Recognizer;
src/recognizer/recognizer.ts
Leoglme-node-nlp-typescript-fbee5fd
[ { "filename": "src/nlp/nlp-excel-reader.ts", "retrieved_chunk": "import { XDoc } from '@nlpjs/xtables';\nimport NlpManager from './nlp-manager';\nclass NlpExcelReader {\n private manager: NlpManager;\n private xdoc: XDoc;\n constructor(manager: NlpManager) {\n this.manager = manager;\n this.xdoc = new XDoc();\n }\n load(filename: string): void {", "score": 0.8642600774765015 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " * Save the NLP manager information into a file.\n * @param {String} srcFileName Filename for saving the NLP manager.\n * @param minified\n */\n save(srcFileName?: string, minified = false): void {\n const fileName = srcFileName || 'model.nlp';\n fs.writeFileSync(fileName, this.export(minified), 'utf8');\n }\n /**\n * Load the NLP manager information from a file.", "score": 0.8576832413673401 }, { "filename": "src/nlp/nlp-excel-reader.ts", "retrieved_chunk": " this.xdoc.read(filename);\n this.loadSettings();\n this.loadLanguages();\n this.loadNamedEntities();\n this.loadRegexEntities();\n this.loadIntents();\n this.loadResponses();\n }\n loadSettings(): void {}\n loadLanguages(): void {", "score": 0.8423787355422974 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " * @param srcFileName\n */\n load(srcFileName?: string): void {\n const fileName = srcFileName || 'model.nlp';\n const data = fs.readFileSync(fileName, 'utf8');\n this.import(data);\n }\n /**\n * Load the NLP manager information from an Excel file.\n * @param fileName", "score": 0.8262865543365479 }, { "filename": "src/types/@nlpjs/nlu.d.ts", "retrieved_chunk": "declare module '@nlpjs/nlu' {\n import { EventEmitter } from 'events';\n import { Container } from '@nlpjs/core';\n export interface INluOptions {\n container?: Container;\n containerName?: string;\n autoSave?: boolean;\n autoLoad?: boolean;\n persist?: boolean;\n persistFilename?: string;", "score": 0.8112133741378784 } ]
typescript
this.nlpManager.save(filename);
/* * Copyright (c) AXA Group Operations Spain S.A. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import SentimentAnalyzer from './sentiment-analyzer'; /** * Class for the sentiment analysis manager, able to manage * several languages at the same time. */ class SentimentManager { private readonly settings: any private languages: {} private analyzer: SentimentAnalyzer /** * Constructor of the class. */ constructor(settings?: any) { this.settings = settings || {}; this.languages = {}; this.analyzer = new SentimentAnalyzer(); } addLanguage() { // do nothing } translate(sentiment: {score: number, average: number, type: string, numHits: number, numWords: number, locale: string}) { let vote; if (sentiment.score > 0) { vote = 'positive'; } else if (sentiment.score < 0) { vote = 'negative'; } else { vote = 'neutral'; } return { score: sentiment.score, comparative: sentiment.average, vote, numWords: sentiment.numWords, numHits: sentiment.numHits, type: sentiment.type, language: sentiment.locale, }; } /** * Process a phrase of a given locale, calculating the sentiment analysis. * @param {String} locale Locale of the phrase. * @param {String} phrase Phrase to calculate the sentiment. * @returns {Promise Object} Promise sentiment analysis of the phrase. */ async process(locale: string, phrase: string) {
const sentiment = await this.analyzer.getSentiment( phrase, locale, this.settings );
return this.translate(sentiment); } } export default SentimentManager
src/sentiment/sentiment-manager.ts
Leoglme-node-nlp-typescript-fbee5fd
[ { "filename": "src/sentiment/sentiment-analyzer.ts", "retrieved_chunk": " this.container.use(Nlu);\n }\n async getSentiment(utterance: string, locale = 'en', settings: [key: string]) {\n const input = {\n utterance,\n locale,\n ...settings,\n };\n const result = await this.process(input);\n return result.sentiment;", "score": 0.8659523129463196 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " return this.nlp.addAnswer(locale, intent, answer, opts);\n }\n removeAnswer(locale: string, intent: string, answer: string, opts?: any): boolean {\n return this.nlp.removeAnswer(locale, intent, answer, opts);\n }\n findAllAnswers(locale: string, intent: string): string[] {\n return this.nlp.findAllAnswers(locale, intent);\n }\n async getSentiment(locale: string, utterance: string): Promise<{ numHits: number; score: number; comparative: number; language: string; numWords: number; type: string; vote: any }> {\n const sentiment = await this.nlp.getSentiment(locale, utterance);", "score": 0.8310399055480957 }, { "filename": "src/recognizer/recognizer.ts", "retrieved_chunk": " locale?: string,\n utterance?: string\n ): Promise<string> {\n const context = srcContext || {};\n const response = await (locale\n ? this.nlpManager.process(locale, utterance, context)\n : this.nlpManager.process(utterance, undefined, context));\n if (response.score < this.threshold || response.intent === 'None') {\n response.answer = undefined;\n return response;", "score": 0.8196910619735718 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " async train(): Promise<void> {\n return this.nlp.train();\n }\n classify(locale: string, utterance: string, settings?: Record<string, unknown>): Promise<any> {\n return this.nlp.classify(locale, utterance, settings);\n }\n async process(locale?: string, utterance?: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {\n const result = await this.nlp.process(locale, utterance, context, settings);\n if (this.settings.processTransformer) {\n return this.settings.processTransformer(result);", "score": 0.8194607496261597 }, { "filename": "src/recognizer/recognizer.ts", "retrieved_chunk": " return response;\n }\n /**\n * Given an utterance and the locale, returns the recognition of the utterance.\n * @param {String} utterance Utterance to be recognized.\n * @param {String} model Model of the utterance.\n * @param {Function} cb Callback Function.\n */\n public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> {\n const response = await this.process(", "score": 0.8002542853355408 } ]
typescript
const sentiment = await this.analyzer.getSentiment( phrase, locale, this.settings );
import { RiTranslate } from "react-icons/ri"; import { MdHighQuality } from "react-icons/md"; import { BsGlobe2 } from "react-icons/bs"; import { HiOutlineDocumentText, HiUserGroup } from "react-icons/hi"; import { BsFillBookmarkHeartFill } from "react-icons/bs"; import TextAnimation from "../animation/text"; import PopAnimation from "../animation/pop"; const Features = () => { const perks = [ { icon: ( <BsGlobe2 className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Multilingual Meeting Support", desc: "Our app allows users who speak different languages to communicate with each other. The app translates the text and speaks it out to other participants in the language they have selected.", }, { icon: ( <RiTranslate className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Real-time Translation", desc: "Our app provides real-time translation, so you can focus on the conversation without worrying about the language barrier. The translation is done quickly and accurately, ensuring smooth communication.", }, { icon: ( <HiOutlineDocumentText className="h-10 w-10" style={{ stroke: "url(#gradient)" }} /> ), title: "Meeting Minutes", desc: "Our app automatically generates a summary of the entire meeting or conference. This feature saves time and helps ensure that all participants are on the same page.", }, { icon: ( <HiUserGroup className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Large Capacity", desc: "Our app can support up to 100 concurrent users. This means that even large meetings and conferences can be easily accommodated, making it ideal for businesses, schools, and other organizations.", }, { icon: ( <MdHighQuality className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "HQ video and Screen Sharing", desc: "Our app provides high-quality video and screen sharing, ensuring that everyone can see and hear each other clearly. This feature helps to ensure that the meeting is productive and engaging.", }, { icon: ( <BsFillBookmarkHeartFill className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "User friendly Interface", desc: "Our app has a user-friendly interface that is easy to navigate. This ensures that everyone can participate in the meeting or conference without any technical difficulties, making it ideal for users of all skill levels.", }, ]; return ( <section id="about" className="bg-gray-900/10 text-white transition-colors duration-500" > <svg width="0" height="0"> <linearGradient id="gradient" x1="100%" y1="100%" x2="0%" y2="0%"> <stop stopColor="#6366f1" offset="0%" /> <stop stopColor="#a855f7" offset="50%" /> <stop stopColor="#ec4899" offset="100%" /> </linearGradient> </svg> <div className="mx-auto max-w-screen-xl px-4 py-16 sm:px-6 lg:px-28"> <div> <div className="mx-auto max-w-lg text-center"> <TextAnimation text="What makes us special!" textStyle="heading text-2xl font-bold lg:text-4xl" className="flex justify-center" /> </div> </div> <div> <div className="mt-8 grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3"> {perks.map((perk, index) => ( <a key={index} className="block rounded-xl border border-primary p-8 shadow-xl transition-all duration-300 hover:scale-[1.05] hover:border-secondary hover:shadow-primary/25" >
<PopAnimation>{perk.icon}</PopAnimation> <TextAnimation textStyle="text-xl font-bold text-white" text={perk.title}
className="mt-4" /> <p className="mt-1 text-sm text-gray-200">{perk.desc}</p> </a> ))} </div> </div> </div> </section> ); }; export default Features;
src/components/features/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " <ul className=\"flex flex-wrap justify-center gap-6 md:gap-8 lg:gap-12\">\n {links.map((link) => (\n <li key={link.path}>\n <Link\n className=\"text-white transition hover:text-gray-400\"\n href={link.path}\n >\n <TextAnimation text={link.label} />\n </Link>\n </li>", "score": 0.8706337213516235 }, { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " <CharacterAnimation\n text=\"Jab We Meet\"\n textStyle=\"text-xl font-bold text-white\"\n />\n </Link>\n <div className=\"hidden space-x-6 text-white lg:flex lg:items-center\">\n {links.map((link) => (\n <Link\n className=\"transition-colors duration-300 hover:text-gray-400\"\n key={link.path}", "score": 0.8593084812164307 }, { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " href={link.path}\n >\n <CharacterAnimation\n text={link.label}\n textStyle=\"text-lg font-medium\"\n />\n </Link>\n ))}\n <PopAnimation>\n <button", "score": 0.8422085046768188 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " </PopAnimation>\n <p className=\"mx-auto mt-6 max-w-md text-center leading-relaxed text-white\">\n <TextAnimation text=\"Jab We Meet\" className=\"flex justify-center\" />\n <TextAnimation\n text=\"Multilingual Video Conferencing App\"\n className=\"flex justify-center\"\n textStyle=\"text-xs text-gray-300\"\n />\n </p>\n <nav className=\"mt-12\">", "score": 0.8392148017883301 }, { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " {links.map((link) => (\n <Link\n key={link.path}\n href={link.path}\n className=\"block py-2 px-4 text-sm hover:bg-white\"\n >\n {link.label}\n </Link>\n ))}\n <div className=\"flex items-center space-x-4\">", "score": 0.8348214626312256 } ]
typescript
<PopAnimation>{perk.icon}</PopAnimation> <TextAnimation textStyle="text-xl font-bold text-white" text={perk.title}
import React, { useState } from "react"; import Modal from "../modal"; import { IoDocumentTextOutline } from "react-icons/io5"; import PopAnimation from "../animation/pop"; import TextAnimation from "../animation/text"; function Card({ room, }: { room: { name: string; slug: string | null; createdAt: Date; }; }) { let [isOpen, setIsOpen] = useState(false) return ( <div className="m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10"> <div key={room.name}> <TextAnimation textStyle="text-xl font-bold text-white" text="Room" /> <div className="gradient-text">{room.slug || room.name}</div> <div className="text-sm font-bold text-gray-100 text-opacity-50"> {room.createdAt.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", })}{" "} at{" "} {room.createdAt.toLocaleTimeString("en-US", { hour: "numeric", minute: "numeric", hour12: true, })} </div> <PopAnimation className="flex flex-row items-center justify-center"> <button onClick={() => setIsOpen(true)} className="mt-5 flex flex-row items-center justify-center space-x-2 rounded-lg bg-gray-100 bg-opacity-5 p-2 backdrop-blur-lg backdrop-filter hover:bg-gray-100 hover:bg-opacity-10" > <IoDocumentTextOutline className="text-2xl text-gray-100" size={15} /> <div>Details</div> </button> </PopAnimation> {isOpen && ( <
Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} /> )}
</div> </div> ); } export default Card;
src/components/card/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/modal/index.tsx", "retrieved_chunk": "};\nconst Modal: FunctionComponent<ModalProps> = ({\n setIsOpen,\n roomName,\n visible,\n}) => {\n const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({\n roomName,\n });\n console.log(data);", "score": 0.8656395673751831 }, { "filename": "src/components/join/index.tsx", "retrieved_chunk": " />\n </label>\n <button\n disabled={!roomName}\n className={`lk-button ${\n !roomName && \"pointer-events-none cursor-not-allowed\"\n }`}\n onClick={() => router.push(`/rooms/${roomName}`)}\n >\n <CharacterAnimation text=\"Join\" textStyle=\"text-sm\"/>", "score": 0.8619887232780457 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " textStyle=\"text-sm\"\n />\n </>\n )}\n </button>\n {!roomLoading && <JoinRoom />}\n </div>\n </div>\n <div className=\"flex w-full max-w-md items-center justify-center\">\n <Hero className=\"h-[40vh] w-full md:h-screen\" />", "score": 0.8578895926475525 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " />\n <div className=\"flex flex-col items-center justify-center space-y-4 lg:flex-row lg:space-y-0 lg:space-x-4\">\n <button onClick={createRoomHandler} className=\"lk-button h-fit\">\n {roomLoading ? (\n <Loader />\n ) : (\n <>\n <AiOutlineVideoCameraAdd />\n <CharacterAnimation\n text=\"Create Room\"", "score": 0.854279100894928 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": " <div className=\"mt-10 flex flex-col bg-black p-10 text-gray-100 lg:p-20\">\n <div className=\"my-5 flex items-center justify-center\">\n <h2 className=\"text-center text-2xl font-bold text-white\">\n Hello {session?.user.name}!👋🏻\n </h2>\n </div>\n <div className=\"flex flex-col items-center justify-center\">\n <TextAnimation\n textStyle=\"text-lg font-bold text-secondary\"\n text=\"Your Rooms\"", "score": 0.8439645767211914 } ]
typescript
Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} /> )}
import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { env } from "~/env.mjs"; import { prisma } from "~/server/db"; /** * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` * object and keep type safety. * * @see https://next-auth.js.org/getting-started/typescript#module-augmentation */ declare module "next-auth" { interface Session extends DefaultSession { user: { id: string; // ...other properties // role: UserRole; } & DefaultSession["user"]; } // interface User { // // ...other properties // // role: UserRole; // } } /** * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. * * @see https://next-auth.js.org/configuration/options */ export const authOptions: NextAuthOptions = { callbacks: { session({ session, user }) { if (session.user) { session.user.id = user.id; // session.user.role = user.role; <-- put other properties on the session here } return session; }, }, adapter: PrismaAdapter(prisma), providers: [ GoogleProvider({
clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
/** * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. * * @see https://next-auth.js.org/configuration/nextjs */ export const getServerAuthSession = (ctx: { req: GetServerSidePropsContext["req"]; res: GetServerSidePropsContext["res"]; }) => { return getServerSession(ctx.req, ctx.res, authOptions); };
src/server/auth.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/db.ts", "retrieved_chunk": "import { PrismaClient } from \"@prisma/client\";\nimport { env } from \"~/env.mjs\";\nconst globalForPrisma = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma =\n globalForPrisma.prisma ||\n new PrismaClient({\n log:\n env.NODE_ENV === \"development\" ? [\"query\", \"error\", \"warn\"] : [\"error\"],\n });\nif (env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;", "score": 0.8856109380722046 }, { "filename": "src/utils/api.ts", "retrieved_chunk": " ],\n };\n },\n /**\n * Whether tRPC should await queries when server rendering pages.\n *\n * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false\n */\n ssr: false,\n});", "score": 0.8231953382492065 }, { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": "import { createNextApiHandler } from \"@trpc/server/adapters/next\";\nimport { env } from \"~/env.mjs\";\nimport { createTRPCContext } from \"~/server/api/trpc\";\nimport { appRouter } from \"~/server/api/root\";\n// export API handler\nexport default createNextApiHandler({\n router: appRouter,\n createContext: createTRPCContext,\n onError:\n env.NODE_ENV === \"development\"", "score": 0.8050100803375244 }, { "filename": "src/utils/pusher.ts", "retrieved_chunk": "import Pusher from \"pusher\";\nexport const pusher = new Pusher({\n appId: process.env.PUSHER_APP_ID as string,\n key: process.env.PUSHER_KEY as string,\n secret: process.env.PUSHER_SECRET as string,\n cluster: process.env.PUSHER_CLUSTER as string,\n useTLS: true,\n});", "score": 0.8030766248703003 }, { "filename": "src/pages/api/auth/[...nextauth].ts", "retrieved_chunk": "import NextAuth from \"next-auth\";\nimport { authOptions } from \"~/server/auth\";\nexport default NextAuth(authOptions);", "score": 0.7935926914215088 } ]
typescript
clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant); const result: TokenResult = { identity, accessToken: token, }; try { // check if user is already in room console.log("here"); const participant = await ctx.prisma.participant.findUnique({ where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order const transcripts = await ctx.prisma.transcript.findMany({ where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, });
const chatLog = transcripts.map((transcript) => ({
speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " dynacast: true,\n };\n }, [userChoices, hq]);\n const [transcriptionQueue, setTranscriptionQueue] = useState<\n {\n sender: string;\n message: string;\n senderId: string;\n isFinal: boolean;\n }[]", "score": 0.7990917563438416 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 0.7965312600135803 }, { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " <h2 className=\"gradient-text\">{transcription?.speaker}</h2>\n <p className=\"font-lg text-white\">\n {transcription.utterance}\n </p>\n <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {transcription.timestamp}\n </div>\n </div>\n );\n })}", "score": 0.7923863530158997 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": "const useTranscribe = ({\n roomName,\n audioEnabled,\n languageCode,\n}: UseTranscribeProps) => {\n const {\n transcript,\n resetTranscript,\n finalTranscript,\n browserSupportsSpeechRecognition,", "score": 0.7921570539474487 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": "}) => {\n const [caption, setCaption] = useState<{ sender: string; message: string }>();\n useEffect(() => {\n async function translateText() {\n console.info(\"transcriptionQueue\", transcriptionQueue);\n if (transcriptionQueue.length > 0) {\n const res = await translate(transcriptionQueue[0]?.message as string, {\n // @ts-ignore\n to: languageCode.split(\"-\")[0],\n });", "score": 0.7900030612945557 } ]
typescript
const chatLog = transcripts.map((transcript) => ({
import React, { useState } from "react"; import Modal from "../modal"; import { IoDocumentTextOutline } from "react-icons/io5"; import PopAnimation from "../animation/pop"; import TextAnimation from "../animation/text"; function Card({ room, }: { room: { name: string; slug: string | null; createdAt: Date; }; }) { let [isOpen, setIsOpen] = useState(false) return ( <div className="m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10"> <div key={room.name}> <TextAnimation textStyle="text-xl font-bold text-white" text="Room" /> <div className="gradient-text">{room.slug || room.name}</div> <div className="text-sm font-bold text-gray-100 text-opacity-50"> {room.createdAt.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", })}{" "} at{" "} {room.createdAt.toLocaleTimeString("en-US", { hour: "numeric", minute: "numeric", hour12: true, })} </div> <PopAnimation className="flex flex-row items-center justify-center"> <button onClick={() => setIsOpen(true)} className="mt-5 flex flex-row items-center justify-center space-x-2 rounded-lg bg-gray-100 bg-opacity-5 p-2 backdrop-blur-lg backdrop-filter hover:bg-gray-100 hover:bg-opacity-10" > <IoDocumentTextOutline className="text-2xl text-gray-100" size={15} /> <div>Details</div> </button> </PopAnimation> {isOpen && (
<Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} /> )}
</div> </div> ); } export default Card;
src/components/card/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/modal/index.tsx", "retrieved_chunk": "};\nconst Modal: FunctionComponent<ModalProps> = ({\n setIsOpen,\n roomName,\n visible,\n}) => {\n const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({\n roomName,\n });\n console.log(data);", "score": 0.8649409413337708 }, { "filename": "src/components/join/index.tsx", "retrieved_chunk": " />\n </label>\n <button\n disabled={!roomName}\n className={`lk-button ${\n !roomName && \"pointer-events-none cursor-not-allowed\"\n }`}\n onClick={() => router.push(`/rooms/${roomName}`)}\n >\n <CharacterAnimation text=\"Join\" textStyle=\"text-sm\"/>", "score": 0.8590711355209351 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " />\n <div className=\"flex flex-col items-center justify-center space-y-4 lg:flex-row lg:space-y-0 lg:space-x-4\">\n <button onClick={createRoomHandler} className=\"lk-button h-fit\">\n {roomLoading ? (\n <Loader />\n ) : (\n <>\n <AiOutlineVideoCameraAdd />\n <CharacterAnimation\n text=\"Create Room\"", "score": 0.8537847399711609 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " textStyle=\"text-sm\"\n />\n </>\n )}\n </button>\n {!roomLoading && <JoinRoom />}\n </div>\n </div>\n <div className=\"flex w-full max-w-md items-center justify-center\">\n <Hero className=\"h-[40vh] w-full md:h-screen\" />", "score": 0.8536200523376465 }, { "filename": "src/components/modal/index.tsx", "retrieved_chunk": "import { Dispatch, SetStateAction, type FunctionComponent } from \"react\";\nimport { api } from \"~/utils/api\";\nimport { Dialog, Transition } from \"@headlessui/react\";\nimport { Fragment, useState } from \"react\";\nimport Loader from \"../loader\";\nimport Tabs from \"../tabs\";\ntype ModalProps = {\n setIsOpen: Dispatch<SetStateAction<boolean>>;\n roomName: string;\n visible: boolean;", "score": 0.8425268530845642 } ]
typescript
<Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} /> )}
import { RiTranslate } from "react-icons/ri"; import { MdHighQuality } from "react-icons/md"; import { BsGlobe2 } from "react-icons/bs"; import { HiOutlineDocumentText, HiUserGroup } from "react-icons/hi"; import { BsFillBookmarkHeartFill } from "react-icons/bs"; import TextAnimation from "../animation/text"; import PopAnimation from "../animation/pop"; const Features = () => { const perks = [ { icon: ( <BsGlobe2 className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Multilingual Meeting Support", desc: "Our app allows users who speak different languages to communicate with each other. The app translates the text and speaks it out to other participants in the language they have selected.", }, { icon: ( <RiTranslate className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Real-time Translation", desc: "Our app provides real-time translation, so you can focus on the conversation without worrying about the language barrier. The translation is done quickly and accurately, ensuring smooth communication.", }, { icon: ( <HiOutlineDocumentText className="h-10 w-10" style={{ stroke: "url(#gradient)" }} /> ), title: "Meeting Minutes", desc: "Our app automatically generates a summary of the entire meeting or conference. This feature saves time and helps ensure that all participants are on the same page.", }, { icon: ( <HiUserGroup className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Large Capacity", desc: "Our app can support up to 100 concurrent users. This means that even large meetings and conferences can be easily accommodated, making it ideal for businesses, schools, and other organizations.", }, { icon: ( <MdHighQuality className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "HQ video and Screen Sharing", desc: "Our app provides high-quality video and screen sharing, ensuring that everyone can see and hear each other clearly. This feature helps to ensure that the meeting is productive and engaging.", }, { icon: ( <BsFillBookmarkHeartFill className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "User friendly Interface", desc: "Our app has a user-friendly interface that is easy to navigate. This ensures that everyone can participate in the meeting or conference without any technical difficulties, making it ideal for users of all skill levels.", }, ]; return ( <section id="about" className="bg-gray-900/10 text-white transition-colors duration-500" > <svg width="0" height="0"> <linearGradient id="gradient" x1="100%" y1="100%" x2="0%" y2="0%"> <stop stopColor="#6366f1" offset="0%" /> <stop stopColor="#a855f7" offset="50%" /> <stop stopColor="#ec4899" offset="100%" /> </linearGradient> </svg> <div className="mx-auto max-w-screen-xl px-4 py-16 sm:px-6 lg:px-28"> <div> <div className="mx-auto max-w-lg text-center"> <TextAnimation text="What makes us special!" textStyle="heading text-2xl font-bold lg:text-4xl" className="flex justify-center" /> </div> </div> <div> <div className="mt-8 grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3"> {perks.map((perk, index) => ( <a key={index} className="block rounded-xl border border-primary p-8 shadow-xl transition-all duration-300 hover:scale-[1.05] hover:border-secondary hover:shadow-primary/25" > <
PopAnimation>{perk.icon}</PopAnimation> <TextAnimation textStyle="text-xl font-bold text-white" text={perk.title}
className="mt-4" /> <p className="mt-1 text-sm text-gray-200">{perk.desc}</p> </a> ))} </div> </div> </div> </section> ); }; export default Features;
src/components/features/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " <CharacterAnimation\n text=\"Jab We Meet\"\n textStyle=\"text-xl font-bold text-white\"\n />\n </Link>\n <div className=\"hidden space-x-6 text-white lg:flex lg:items-center\">\n {links.map((link) => (\n <Link\n className=\"transition-colors duration-300 hover:text-gray-400\"\n key={link.path}", "score": 0.8630317449569702 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " <ul className=\"flex flex-wrap justify-center gap-6 md:gap-8 lg:gap-12\">\n {links.map((link) => (\n <li key={link.path}>\n <Link\n className=\"text-white transition hover:text-gray-400\"\n href={link.path}\n >\n <TextAnimation text={link.label} />\n </Link>\n </li>", "score": 0.8620519638061523 }, { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " href={link.path}\n >\n <CharacterAnimation\n text={link.label}\n textStyle=\"text-lg font-medium\"\n />\n </Link>\n ))}\n <PopAnimation>\n <button", "score": 0.8415539860725403 }, { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " {links.map((link) => (\n <Link\n key={link.path}\n href={link.path}\n className=\"block py-2 px-4 text-sm hover:bg-white\"\n >\n {link.label}\n </Link>\n ))}\n <div className=\"flex items-center space-x-4\">", "score": 0.8408305644989014 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " </PopAnimation>\n <p className=\"mx-auto mt-6 max-w-md text-center leading-relaxed text-white\">\n <TextAnimation text=\"Jab We Meet\" className=\"flex justify-center\" />\n <TextAnimation\n text=\"Multilingual Video Conferencing App\"\n className=\"flex justify-center\"\n textStyle=\"text-xs text-gray-300\"\n />\n </p>\n <nav className=\"mt-12\">", "score": 0.836073637008667 } ]
typescript
PopAnimation>{perk.icon}</PopAnimation> <TextAnimation textStyle="text-xl font-bold text-white" text={perk.title}
import { LiveKitRoom, PreJoin, LocalUserChoices, VideoConference, formatChatMessageLinks, } from "@livekit/components-react"; import { LogLevel, RoomOptions, VideoPresets } from "livekit-client"; import type { NextPage } from "next"; import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { DebugMode } from "../../lib/Debug"; import { api } from "~/utils/api"; import { signIn, useSession } from "next-auth/react"; import Pusher from "pusher-js"; import useTranscribe from "~/hooks/useTranscribe"; import Captions from "~/components/captions"; import SplashScreen from "~/components/splashScreen"; import { AiFillSetting } from "react-icons/ai"; const Home: NextPage = () => { const router = useRouter(); const { name: roomName } = router.query; const { data: session, status } = useSession(); const [preJoinChoices, setPreJoinChoices] = useState< LocalUserChoices | undefined >(undefined); const [selectedCode, setSelectedCode] = useState("en"); if (status === "loading") return <SplashScreen />; if (!session) signIn("google"); const languageCodes = [ { language: "English", code: "en-US", }, { language: "Hindi", code: "hi-IN", }, { language: "Japanese", code: "ja-JP", }, { language: "French", code: "fr-FR", }, { language: "Deutsch", code: "de-DE", }, ]; return ( <main data-lk-theme="default"> {roomName && !Array.isArray(roomName) && preJoinChoices ? ( <> <ActiveRoom roomName={roomName} userChoices={preJoinChoices} onLeave={() => setPreJoinChoices(undefined)} userId={session?.user.id as string} selectedLanguage={selectedCode} ></ActiveRoom> <div className="lk-prejoin" style={{ width: "100%", }} > <label className="flex items-center justify-center gap-2"> <span className="flex items-center space-x-2 text-center text-xs lg:text-sm"> <AiFillSetting /> <a>Switch Language</a> </span> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} defaultValue={selectedCode} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </label> </div> </> ) : ( <div className="flex h-screen flex-col items-center justify-center"> <div className="lk-prejoin flex flex-col gap-3"> <div className="text-2xl font-bold">Hey, {session?.user.name}!</div> <div className="text-sm font-normal"> You are joining{" "} <span className="gradient-text font-semibold">{roomName}</span> </div> <label> <span>Choose your Language</span> </label> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </div> <PreJoin onError={(err) => console.log("Error while setting up prejoin", err) } defaults={{ username: session?.user.name as string, videoEnabled: true, audioEnabled: true, }} onSubmit={(values) => { console.log("Joining with: ", values); setPreJoinChoices(values); }} ></PreJoin> </div> )} </main> ); }; export default Home; type ActiveRoomProps = { userChoices: LocalUserChoices; roomName: string; region?: string; onLeave?: () => void; userId: string; selectedLanguage: string; }; const ActiveRoom = ({ roomName, userChoices, onLeave, userId, selectedLanguage, }: ActiveRoomProps) => { const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName }); const router = useRouter(); const { region, hq } = router.query; // const liveKitUrl = useServerUrl(region as string | undefined); const roomOptions = useMemo((): RoomOptions => { return { videoCaptureDefaults: { deviceId: userChoices.videoDeviceId ?? undefined, resolution: hq === "true" ? VideoPresets.h2160 : VideoPresets.h720, }, publishDefaults: { videoSimulcastLayers: hq === "true" ? [VideoPresets.h1080, VideoPresets.h720] : [VideoPresets.h540, VideoPresets.h216], }, audioCaptureDefaults: { deviceId: userChoices.audioDeviceId ?? undefined, }, adaptiveStream: { pixelDensity: "screen" }, dynacast: true, }; }, [userChoices, hq]); const [transcriptionQueue, setTranscriptionQueue] = useState< { sender: string; message: string; senderId: string; isFinal: boolean; }[] >([]); useTranscribe({ roomName, audioEnabled: userChoices.audioEnabled, languageCode: selectedLanguage, }); useEffect(() => { const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, { cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string, }); const channel = pusher.subscribe(roomName); channel.bind( "transcribe-event", function (data: { sender: string; message: string; senderId: string; isFinal: boolean; }) { if (data.isFinal && userId !== data.senderId) { setTranscriptionQueue((prev) => { return [...prev, data]; }); } } ); return () => { pusher.unsubscribe(roomName); }; }, []); return ( <> {data && ( <LiveKitRoom token={data.accessToken} serverUrl={process.env.NEXT_PUBLIC_LIVEKIT_API_HOST} options={roomOptions} video={userChoices.videoEnabled} audio={userChoices.audioEnabled} onDisconnected={onLeave} >
<Captions transcriptionQueue={transcriptionQueue}
setTranscriptionQueue={setTranscriptionQueue} languageCode={selectedLanguage} /> <VideoConference chatMessageFormatter={formatChatMessageLinks} /> <DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )} </> ); };
src/pages/rooms/[name].tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/captions/index.tsx", "retrieved_chunk": " }, [transcriptionQueue]);\n return (\n <div className=\"closed-captions-wrapper z-50\">\n <div className=\"closed-captions-container\">\n {caption?.message ? (\n <>\n <div className=\"closed-captions-username\">{caption.sender}</div>\n <span>:&nbsp;</span>\n </>\n ) : null}", "score": 0.8573434352874756 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": "};\ninterface Props {\n transcriptionQueue: Transcription[];\n setTranscriptionQueue: Dispatch<SetStateAction<Transcription[]>>;\n languageCode: string;\n}\nconst Captions: React.FC<Props> = ({\n transcriptionQueue,\n setTranscriptionQueue,\n languageCode,", "score": 0.8406214714050293 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " />\n <div className=\"flex flex-col items-center justify-center space-y-4 lg:flex-row lg:space-y-0 lg:space-x-4\">\n <button onClick={createRoomHandler} className=\"lk-button h-fit\">\n {roomLoading ? (\n <Loader />\n ) : (\n <>\n <AiOutlineVideoCameraAdd />\n <CharacterAnimation\n text=\"Create Room\"", "score": 0.8364177346229553 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": "const useTranscribe = ({\n roomName,\n audioEnabled,\n languageCode,\n}: UseTranscribeProps) => {\n const {\n transcript,\n resetTranscript,\n finalTranscript,\n browserSupportsSpeechRecognition,", "score": 0.834900975227356 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": "import { useEffect } from \"react\";\nimport SpeechRecognition, {\n useSpeechRecognition,\n} from \"react-speech-recognition\";\nimport { api } from \"~/utils/api\";\ntype UseTranscribeProps = {\n roomName: string;\n audioEnabled: boolean;\n languageCode?: string;\n};", "score": 0.8299241662025452 } ]
typescript
<Captions transcriptionQueue={transcriptionQueue}
import { LiveKitRoom, PreJoin, LocalUserChoices, VideoConference, formatChatMessageLinks, } from "@livekit/components-react"; import { LogLevel, RoomOptions, VideoPresets } from "livekit-client"; import type { NextPage } from "next"; import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { DebugMode } from "../../lib/Debug"; import { api } from "~/utils/api"; import { signIn, useSession } from "next-auth/react"; import Pusher from "pusher-js"; import useTranscribe from "~/hooks/useTranscribe"; import Captions from "~/components/captions"; import SplashScreen from "~/components/splashScreen"; import { AiFillSetting } from "react-icons/ai"; const Home: NextPage = () => { const router = useRouter(); const { name: roomName } = router.query; const { data: session, status } = useSession(); const [preJoinChoices, setPreJoinChoices] = useState< LocalUserChoices | undefined >(undefined); const [selectedCode, setSelectedCode] = useState("en"); if (status === "loading") return <SplashScreen />; if (!session) signIn("google"); const languageCodes = [ { language: "English", code: "en-US", }, { language: "Hindi", code: "hi-IN", }, { language: "Japanese", code: "ja-JP", }, { language: "French", code: "fr-FR", }, { language: "Deutsch", code: "de-DE", }, ]; return ( <main data-lk-theme="default"> {roomName && !Array.isArray(roomName) && preJoinChoices ? ( <> <ActiveRoom roomName={roomName} userChoices={preJoinChoices} onLeave={() => setPreJoinChoices(undefined)} userId={session?.user.id as string} selectedLanguage={selectedCode} ></ActiveRoom> <div className="lk-prejoin" style={{ width: "100%", }} > <label className="flex items-center justify-center gap-2"> <span className="flex items-center space-x-2 text-center text-xs lg:text-sm"> <AiFillSetting /> <a>Switch Language</a> </span> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} defaultValue={selectedCode} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </label> </div> </> ) : ( <div className="flex h-screen flex-col items-center justify-center"> <div className="lk-prejoin flex flex-col gap-3"> <div className="text-2xl font-bold">Hey, {session?.user.name}!</div> <div className="text-sm font-normal"> You are joining{" "} <span className="gradient-text font-semibold">{roomName}</span> </div> <label> <span>Choose your Language</span> </label> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </div> <PreJoin onError={(err) => console.log("Error while setting up prejoin", err) } defaults={{ username: session?.user.name as string, videoEnabled: true, audioEnabled: true, }} onSubmit={(values) => { console.log("Joining with: ", values); setPreJoinChoices(values); }} ></PreJoin> </div> )} </main> ); }; export default Home; type ActiveRoomProps = { userChoices: LocalUserChoices; roomName: string; region?: string; onLeave?: () => void; userId: string; selectedLanguage: string; }; const ActiveRoom = ({ roomName, userChoices, onLeave, userId, selectedLanguage, }: ActiveRoomProps) => { const { data, error, isLoading } =
api.rooms.joinRoom.useQuery({ roomName });
const router = useRouter(); const { region, hq } = router.query; // const liveKitUrl = useServerUrl(region as string | undefined); const roomOptions = useMemo((): RoomOptions => { return { videoCaptureDefaults: { deviceId: userChoices.videoDeviceId ?? undefined, resolution: hq === "true" ? VideoPresets.h2160 : VideoPresets.h720, }, publishDefaults: { videoSimulcastLayers: hq === "true" ? [VideoPresets.h1080, VideoPresets.h720] : [VideoPresets.h540, VideoPresets.h216], }, audioCaptureDefaults: { deviceId: userChoices.audioDeviceId ?? undefined, }, adaptiveStream: { pixelDensity: "screen" }, dynacast: true, }; }, [userChoices, hq]); const [transcriptionQueue, setTranscriptionQueue] = useState< { sender: string; message: string; senderId: string; isFinal: boolean; }[] >([]); useTranscribe({ roomName, audioEnabled: userChoices.audioEnabled, languageCode: selectedLanguage, }); useEffect(() => { const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, { cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string, }); const channel = pusher.subscribe(roomName); channel.bind( "transcribe-event", function (data: { sender: string; message: string; senderId: string; isFinal: boolean; }) { if (data.isFinal && userId !== data.senderId) { setTranscriptionQueue((prev) => { return [...prev, data]; }); } } ); return () => { pusher.unsubscribe(roomName); }; }, []); return ( <> {data && ( <LiveKitRoom token={data.accessToken} serverUrl={process.env.NEXT_PUBLIC_LIVEKIT_API_HOST} options={roomOptions} video={userChoices.videoEnabled} audio={userChoices.audioEnabled} onDisconnected={onLeave} > <Captions transcriptionQueue={transcriptionQueue} setTranscriptionQueue={setTranscriptionQueue} languageCode={selectedLanguage} /> <VideoConference chatMessageFormatter={formatChatMessageLinks} /> <DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )} </> ); };
src/pages/rooms/[name].tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/modal/index.tsx", "retrieved_chunk": "};\nconst Modal: FunctionComponent<ModalProps> = ({\n setIsOpen,\n roomName,\n visible,\n}) => {\n const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({\n roomName,\n });\n console.log(data);", "score": 0.8800022006034851 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": " const { data: rooms, isLoading, error } = api.rooms.getRoomsByUser.useQuery();\n if (status === \"loading\") return <SplashScreen />;\n if (!session && status === \"unauthenticated\") return signIn(\"google\");\n const ownedRooms =\n rooms?.filter((room) => room.OwnerId === session?.user.id) || [];\n const joinedRooms =\n rooms?.filter((room) => room.OwnerId !== session?.user.id) || [];\n return (\n <>\n <Navbar status={status} session={session} />", "score": 0.8575125932693481 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " });\n const [roomLoading, setRoomLoading] = React.useState(false);\n const createRoomHandler = async () => {\n if (status === \"unauthenticated\") signIn(\"google\");\n else {\n setRoomLoading(true);\n const data = await createRoom.mutateAsync();\n setRoomLoading(false);\n router.push(`/rooms/${data.roomName}`);\n }", "score": 0.85096275806427 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " slug: string | null;\n createdAt: Date;\n };\n}) {\n let [isOpen, setIsOpen] = useState(false)\n return (\n <div className=\"m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10\">\n <div key={room.name}>\n <TextAnimation textStyle=\"text-xl font-bold text-white\" text=\"Room\" />\n <div className=\"gradient-text\">{room.slug || room.name}</div>", "score": 0.8445113897323608 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const createRoom = api.rooms.createRoom.useMutation();\n const router = useRouter();\n const { RiveComponent: Hero } = useRive({\n src: `hero.riv`,\n stateMachines: [\"State Machine 1\"],\n autoplay: true,\n layout: new Layout({\n fit: Fit.FitWidth,\n alignment: Alignment.Center,\n }),", "score": 0.8416485786437988 } ]
typescript
api.rooms.joinRoom.useQuery({ roomName });
import Image from "next/image"; import Link from "next/link"; import CharacterAnimation from "../animation/character"; import { BiMenuAltRight as MenuIcon } from "react-icons/bi"; import { AiOutlineClose as XIcon } from "react-icons/ai"; import { useState } from "react"; import { signIn, signOut } from "next-auth/react"; import { Session } from "next-auth"; import { FcGoogle } from "react-icons/fc"; import PopAnimation from "../animation/pop"; import Loader from "../loader"; const Navbar = ({ status, session, }: { status: "loading" | "authenticated" | "unauthenticated"; session: Session | null; }) => { const links = [ { label: "Home", path: "#", }, { label: "About", path: "#about", }, { label: "Contact", path: "#contact", }, ]; const [isMenuOpen, setIsMenuOpen] = useState(false); const toggleMenu = () => { setIsMenuOpen(!isMenuOpen); }; return ( <nav className="fixed top-0 z-10 w-full border-b border-gray-400/20 bg-white bg-opacity-5 backdrop-blur-lg backdrop-filter"> <div className="mx-auto max-w-5xl px-4"> <div className="flex h-16 items-center justify-between"> <Link href="/" className="flex items-center space-x-2"> <
PopAnimation> <Image src="/logo.png" alt="Logo" width={40}
height={40} priority /> </PopAnimation> <CharacterAnimation text="Jab We Meet" textStyle="text-xl font-bold text-white" /> </Link> <div className="hidden space-x-6 text-white lg:flex lg:items-center"> {links.map((link) => ( <Link className="transition-colors duration-300 hover:text-gray-400" key={link.path} href={link.path} > <CharacterAnimation text={link.label} textStyle="text-lg font-medium" /> </Link> ))} <PopAnimation> <button className="lk-button" onClick={() => { if (status === "authenticated") { signOut(); } else { signIn("google"); } }} > {status === "authenticated" ? ( "Sign Out" ) : ( <div className="flex items-center space-x-2"> <FcGoogle /> <div>Sign In</div> </div> )} </button> </PopAnimation> <PopAnimation> <select className="lk-button"> <option value="en">English</option> </select> </PopAnimation> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> <div className="flex items-center space-x-4 lg:hidden"> {isMenuOpen ? ( <XIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> ) : ( <MenuIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> )} </div> </div> {isMenuOpen && ( <div className="flex flex-col space-y-2 p-5 text-white lg:hidden"> {links.map((link) => ( <Link key={link.path} href={link.path} className="block py-2 px-4 text-sm hover:bg-white" > {link.label} </Link> ))} <div className="flex items-center space-x-4"> <button className="lk-button" onClick={() => { if (status === "authenticated") { signIn("google"); } else { signOut(); } }} > {status === "authenticated" ? "Sign Out" : "Sign In"} </button> <select className="lk-button"> <option value="en">English</option> </select> </div> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> )} </div> </nav> ); }; export default Navbar;
src/components/navbar/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " <footer id=\"contact\" className=\"bg-gray-900\">\n <div className=\"mx-auto max-w-5xl px-4 py-16 sm:px-6 lg:px-8\">\n <PopAnimation className=\"flex justify-center text-primary\">\n <Image\n src=\"/logo.png\"\n alt=\"Logo\"\n width={100}\n height={100}\n className=\"h-12 w-auto\"\n />", "score": 0.9138274192810059 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " </PopAnimation>\n <p className=\"mx-auto mt-6 max-w-md text-center leading-relaxed text-white\">\n <TextAnimation text=\"Jab We Meet\" className=\"flex justify-center\" />\n <TextAnimation\n text=\"Multilingual Video Conferencing App\"\n className=\"flex justify-center\"\n textStyle=\"text-xs text-gray-300\"\n />\n </p>\n <nav className=\"mt-12\">", "score": 0.8890275955200195 }, { "filename": "src/components/modal/index.tsx", "retrieved_chunk": " <div className=\"fixed inset-0 overflow-y-auto\">\n <div className=\"flex min-h-full items-center justify-center p-4 text-center\">\n <Transition.Child\n as={Fragment}\n enter=\"ease-out duration-300\"\n enterFrom=\"opacity-0 scale-95\"\n enterTo=\"opacity-100 scale-100\"\n leave=\"ease-in duration-200\"\n leaveFrom=\"opacity-100 scale-100\"\n leaveTo=\"opacity-0 scale-95\"", "score": 0.8767170310020447 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Link from \"next/link\";\nimport PopAnimation from \"../animation/pop\";\nimport TextAnimation from \"../animation/text\";\nconst Footer = () => {\n const links = [\n {\n label: \"Home\",\n path: \"#\",\n },", "score": 0.8687028288841248 }, { "filename": "src/components/modal/index.tsx", "retrieved_chunk": " as={Fragment}\n enter=\"ease-out duration-300\"\n enterFrom=\"opacity-0\"\n enterTo=\"opacity-100\"\n leave=\"ease-in duration-200\"\n leaveFrom=\"opacity-100\"\n leaveTo=\"opacity-0\"\n >\n <div className=\"fixed inset-0 bg-black bg-opacity-25\" />\n </Transition.Child>", "score": 0.8537739515304565 } ]
typescript
PopAnimation> <Image src="/logo.png" alt="Logo" width={40}
// @refresh reset import type { NextPage } from "next"; import { signIn, useSession } from "next-auth/react"; import { useRouter } from "next/router"; import React from "react"; import Typing from "~/components/animation/typing"; import Navbar from "~/components/navbar"; import { api } from "~/utils/api"; import { AiOutlineVideoCameraAdd } from "react-icons/ai"; import JoinRoom from "~/components/join"; import Image from "next/image"; import Features from "~/components/features"; import CharacterAnimation from "~/components/animation/character"; import { useRive, Layout, Fit, Alignment } from "@rive-app/react-canvas"; import TextAnimation from "~/components/animation/text"; import Loader from "~/components/loader"; import Footer from "~/components/footer"; import SplashScreen from "~/components/splashScreen"; function ConnectionTab() { const { data: session, status } = useSession(); const createRoom = api.rooms.createRoom.useMutation(); const router = useRouter(); const { RiveComponent: Hero } = useRive({ src: `hero.riv`, stateMachines: ["State Machine 1"], autoplay: true, layout: new Layout({ fit: Fit.FitWidth, alignment: Alignment.Center, }), }); const [roomLoading, setRoomLoading] = React.useState(false); const createRoomHandler = async () => { if (status === "unauthenticated") signIn("google"); else { setRoomLoading(true); const data = await createRoom.mutateAsync(); setRoomLoading(false); router.push(`/rooms/${data.roomName}`); } }; if (status === "loading") return <SplashScreen />; return ( <> <Navbar status={status} session={session} /> <div className="isolate overflow-x-hidden"> <div className="flex h-screen w-screen flex-col items-center justify-center space-y-4 p-5 text-center md:flex-row"> <div className="absolute inset-x-0 top-[-10rem] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[-20rem]"> <svg className="relative left-[calc(50%-11rem)] -z-10 h-[21.1875rem] max-w-none -translate-x-1/2 rotate-[30deg] sm:left-[calc(50%-30rem)] sm:h-[42.375rem]" viewBox="0 0 1155 678" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fill="url(#45de2b6b-92d5-4d68-a6a0-9b9b2abad533)" fillOpacity=".3" d="M317.219 518.975L203.852 678 0 438.341l317.219 80.634 204.172-286.402c1.307 132.337 45.083 346.658 209.733 145.248C936.936 126.058 882.053-94.234 1031.02 41.331c119.18 108.451 130.68 295.337 121.53 375.223L855 299l21.173 362.054-558.954-142.079z" /> <defs> <linearGradient id="45de2b6b-92d5-4d68-a6a0-9b9b2abad533" x1="1155.49" x2="-78.208" y1=".177" y2="474.645" gradientUnits="userSpaceOnUse" > <stop stopColor="#9089FC" /> <stop offset={1} stopColor="#FF80B5" /> </linearGradient> </defs> </svg> </div> <div className="w-full max-w-md space-y-4"> <Typing /> <TextAnimation className="flex justify-center" textStyle="text-sm text-gray-400" text="Multilingual Video Conferencing App" /> <div className="flex flex-col items-center justify-center space-y-4 lg:flex-row lg:space-y-0 lg:space-x-4"> <button onClick={createRoomHandler} className="lk-button h-fit"> {roomLoading ? ( <Loader /> ) : ( <> <AiOutlineVideoCameraAdd /> <CharacterAnimation text="Create Room" textStyle="text-sm" /> </> )} </button> {!
roomLoading && <JoinRoom />}
</div> </div> <div className="flex w-full max-w-md items-center justify-center"> <Hero className="h-[40vh] w-full md:h-screen" /> </div> </div> <Features /> <Footer /> <div className="absolute inset-x-0 top-[calc(100%-13rem)] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[calc(100%-30rem)]"> <svg className="relative left-[calc(50%+3rem)] h-[21.1875rem] max-w-none -translate-x-1/2 sm:left-[calc(50%+36rem)] sm:h-[42.375rem]" viewBox="0 0 1155 678" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fill="url(#ecb5b0c9-546c-4772-8c71-4d3f06d544bc)" fillOpacity=".3" d="M317.219 518.975L203.852 678 0 438.341l317.219 80.634 204.172-286.402c1.307 132.337 45.083 346.658 209.733 145.248C936.936 126.058 882.053-94.234 1031.02 41.331c119.18 108.451 130.68 295.337 121.53 375.223L855 299l21.173 362.054-558.954-142.079z" /> <defs> <linearGradient id="ecb5b0c9-546c-4772-8c71-4d3f06d544bc" x1="1155.49" x2="-78.208" y1=".177" y2="474.645" gradientUnits="userSpaceOnUse" > <stop stopColor="#9089FC" /> <stop offset={1} stopColor="#FF80B5" /> </linearGradient> </defs> </svg> </div> </div> </> ); } const Home: NextPage = () => { return ( <> <main data-lk-theme="default"> <ConnectionTab /> </main> </> ); }; export default Home;
src/pages/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/join/index.tsx", "retrieved_chunk": " />\n </label>\n <button\n disabled={!roomName}\n className={`lk-button ${\n !roomName && \"pointer-events-none cursor-not-allowed\"\n }`}\n onClick={() => router.push(`/rooms/${roomName}`)}\n >\n <CharacterAnimation text=\"Join\" textStyle=\"text-sm\"/>", "score": 0.895809531211853 }, { "filename": "src/components/join/index.tsx", "retrieved_chunk": " </button>\n </div>\n );\n};\nexport default JoinRoom;", "score": 0.8615627884864807 }, { "filename": "src/components/join/index.tsx", "retrieved_chunk": "import { useRouter } from \"next/router\";\nimport { useState } from \"react\";\nimport { BsKeyboard } from \"react-icons/bs\";\nimport CharacterAnimation from \"../animation/character\";\nconst JoinRoom = () => {\n const [roomName, setRoomName] = useState<string>(\"\");\n const router = useRouter();\n return (\n <div className=\"flex items-center space-x-4 p-2 text-white\">\n <label className=\"relative\">", "score": 0.8601050972938538 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " slug: string | null;\n createdAt: Date;\n };\n}) {\n let [isOpen, setIsOpen] = useState(false)\n return (\n <div className=\"m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10\">\n <div key={room.name}>\n <TextAnimation textStyle=\"text-xl font-bold text-white\" text=\"Room\" />\n <div className=\"gradient-text\">{room.slug || room.name}</div>", "score": 0.8496518135070801 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": " })}\n </div>\n </div>\n <div className=\"flex flex-col items-center justify-center\">\n <TextAnimation\n textStyle=\"text-lg font-bold text-secondary\"\n text=\"Rooms you are a part of\"\n />\n {joinedRooms.length === 0 && (\n <p className=\"mt-2 text-xs font-light text-white\">", "score": 0.8423405289649963 } ]
typescript
roomLoading && <JoinRoom />}
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant);
const result: TokenResult = {
identity, accessToken: token, }; try { // check if user is already in room console.log("here"); const participant = await ctx.prisma.participant.findUnique({ where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order const transcripts = await ctx.prisma.transcript.findMany({ where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, }); const chatLog = transcripts.map((transcript) => ({ speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " .input(\n z.object({\n message: string(),\n roomName: string(),\n isFinal: z.boolean(),\n })\n )\n .mutation(async ({ input, ctx }) => {\n const { message } = input;\n const { user } = ctx.session;", "score": 0.819931149482727 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 0.8178108930587769 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const response = await pusher.trigger(\n input.roomName,\n \"transcribe-event\",\n {\n message,\n sender: user.name,\n isFinal: input.isFinal,\n senderId: user.id,\n }\n );", "score": 0.813002347946167 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName });\n const router = useRouter();\n const { region, hq } = router.query;\n // const liveKitUrl = useServerUrl(region as string | undefined);\n const roomOptions = useMemo((): RoomOptions => {\n return {\n videoCaptureDefaults: {\n deviceId: userChoices.videoDeviceId ?? undefined,\n resolution: hq === \"true\" ? VideoPresets.h2160 : VideoPresets.h720,\n },", "score": 0.812730073928833 }, { "filename": "src/lib/type.ts", "retrieved_chunk": "export interface TokenResult {\n identity: string;\n accessToken: string;\n}", "score": 0.7983589768409729 } ]
typescript
const result: TokenResult = {
import Image from "next/image"; import Link from "next/link"; import CharacterAnimation from "../animation/character"; import { BiMenuAltRight as MenuIcon } from "react-icons/bi"; import { AiOutlineClose as XIcon } from "react-icons/ai"; import { useState } from "react"; import { signIn, signOut } from "next-auth/react"; import { Session } from "next-auth"; import { FcGoogle } from "react-icons/fc"; import PopAnimation from "../animation/pop"; import Loader from "../loader"; const Navbar = ({ status, session, }: { status: "loading" | "authenticated" | "unauthenticated"; session: Session | null; }) => { const links = [ { label: "Home", path: "#", }, { label: "About", path: "#about", }, { label: "Contact", path: "#contact", }, ]; const [isMenuOpen, setIsMenuOpen] = useState(false); const toggleMenu = () => { setIsMenuOpen(!isMenuOpen); }; return ( <nav className="fixed top-0 z-10 w-full border-b border-gray-400/20 bg-white bg-opacity-5 backdrop-blur-lg backdrop-filter"> <div className="mx-auto max-w-5xl px-4"> <div className="flex h-16 items-center justify-between"> <Link href="/" className="flex items-center space-x-2"> <PopAnimation> <Image src="/logo.png" alt="Logo" width={40} height={40} priority /> </PopAnimation> <CharacterAnimation text="Jab We Meet" textStyle="text-xl font-bold text-white" /> </Link> <div className="hidden space-x-6 text-white lg:flex lg:items-center"> {links.map((link) => ( <Link className="transition-colors duration-300 hover:text-gray-400" key={link.path} href={link.path} > <CharacterAnimation text={link.label} textStyle="text-lg font-medium" /> </Link> ))} <PopAnimation> <button className="lk-button" onClick={() => { if (status === "authenticated") { signOut(); } else { signIn("google"); } }} > {status === "authenticated" ? ( "Sign Out" ) : ( <div className="flex items-center space-x-2"> <FcGoogle /> <div>Sign In</div> </div> )} </button> </PopAnimation> <PopAnimation> <select className="lk-button"> <option value="en">English</option> </select> </PopAnimation> <PopAnimation> <Link href="/profile"> {status === "loading" ? (
<Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string}
width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> <div className="flex items-center space-x-4 lg:hidden"> {isMenuOpen ? ( <XIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> ) : ( <MenuIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> )} </div> </div> {isMenuOpen && ( <div className="flex flex-col space-y-2 p-5 text-white lg:hidden"> {links.map((link) => ( <Link key={link.path} href={link.path} className="block py-2 px-4 text-sm hover:bg-white" > {link.label} </Link> ))} <div className="flex items-center space-x-4"> <button className="lk-button" onClick={() => { if (status === "authenticated") { signIn("google"); } else { signOut(); } }} > {status === "authenticated" ? "Sign Out" : "Sign In"} </button> <select className="lk-button"> <option value="en">English</option> </select> </div> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> )} </div> </nav> ); }; export default Navbar;
src/components/navbar/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " ))}\n </select>\n </label>\n </div>\n </>\n ) : (\n <div className=\"flex h-screen flex-col items-center justify-center\">\n <div className=\"lk-prejoin flex flex-col gap-3\">\n <div className=\"text-2xl font-bold\">Hey, {session?.user.name}!</div>\n <div className=\"text-sm font-normal\">", "score": 0.8623049259185791 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": "import { signIn, useSession } from \"next-auth/react\";\nimport TextAnimation from \"~/components/animation/text\";\nimport Card from \"~/components/card\";\nimport Footer from \"~/components/footer\";\nimport Loader from \"~/components/loader\";\nimport Navbar from \"~/components/navbar\";\nimport SplashScreen from \"~/components/splashScreen\";\nimport { api } from \"~/utils/api\";\nfunction profile() {\n const { data: session, status } = useSession();", "score": 0.8487482666969299 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " <AiFillSetting />\n <a>Switch Language</a>\n </span>\n <select\n className=\"lk-button\"\n onChange={(e) => setSelectedCode(e.target.value)}\n defaultValue={selectedCode}\n >\n {languageCodes.map((language) => (\n <option value={language.code}>{language.language}</option>", "score": 0.8403890132904053 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Link from \"next/link\";\nimport PopAnimation from \"../animation/pop\";\nimport TextAnimation from \"../animation/text\";\nconst Footer = () => {\n const links = [\n {\n label: \"Home\",\n path: \"#\",\n },", "score": 0.833432674407959 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " hour12: true,\n })}\n </div>\n <PopAnimation className=\"flex flex-row items-center justify-center\">\n <button\n onClick={() => setIsOpen(true)}\n className=\"mt-5 flex flex-row items-center justify-center space-x-2 rounded-lg bg-gray-100 bg-opacity-5 p-2 backdrop-blur-lg backdrop-filter hover:bg-gray-100 hover:bg-opacity-10\"\n >\n <IoDocumentTextOutline\n className=\"text-2xl text-gray-100\"", "score": 0.8320310115814209 } ]
typescript
<Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string}
import { LiveKitRoom, PreJoin, LocalUserChoices, VideoConference, formatChatMessageLinks, } from "@livekit/components-react"; import { LogLevel, RoomOptions, VideoPresets } from "livekit-client"; import type { NextPage } from "next"; import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { DebugMode } from "../../lib/Debug"; import { api } from "~/utils/api"; import { signIn, useSession } from "next-auth/react"; import Pusher from "pusher-js"; import useTranscribe from "~/hooks/useTranscribe"; import Captions from "~/components/captions"; import SplashScreen from "~/components/splashScreen"; import { AiFillSetting } from "react-icons/ai"; const Home: NextPage = () => { const router = useRouter(); const { name: roomName } = router.query; const { data: session, status } = useSession(); const [preJoinChoices, setPreJoinChoices] = useState< LocalUserChoices | undefined >(undefined); const [selectedCode, setSelectedCode] = useState("en"); if (status === "loading") return <SplashScreen />; if (!session) signIn("google"); const languageCodes = [ { language: "English", code: "en-US", }, { language: "Hindi", code: "hi-IN", }, { language: "Japanese", code: "ja-JP", }, { language: "French", code: "fr-FR", }, { language: "Deutsch", code: "de-DE", }, ]; return ( <main data-lk-theme="default"> {roomName && !Array.isArray(roomName) && preJoinChoices ? ( <> <ActiveRoom roomName={roomName} userChoices={preJoinChoices} onLeave={() => setPreJoinChoices(undefined)} userId={session?.user.id as string} selectedLanguage={selectedCode} ></ActiveRoom> <div className="lk-prejoin" style={{ width: "100%", }} > <label className="flex items-center justify-center gap-2"> <span className="flex items-center space-x-2 text-center text-xs lg:text-sm"> <AiFillSetting /> <a>Switch Language</a> </span> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} defaultValue={selectedCode} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </label> </div> </> ) : ( <div className="flex h-screen flex-col items-center justify-center"> <div className="lk-prejoin flex flex-col gap-3"> <div className="text-2xl font-bold">Hey, {session?.user.name}!</div> <div className="text-sm font-normal"> You are joining{" "} <span className="gradient-text font-semibold">{roomName}</span> </div> <label> <span>Choose your Language</span> </label> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </div> <PreJoin onError={(err) => console.log("Error while setting up prejoin", err) } defaults={{ username: session?.user.name as string, videoEnabled: true, audioEnabled: true, }} onSubmit={(values) => { console.log("Joining with: ", values); setPreJoinChoices(values); }} ></PreJoin> </div> )} </main> ); }; export default Home; type ActiveRoomProps = { userChoices: LocalUserChoices; roomName: string; region?: string; onLeave?: () => void; userId: string; selectedLanguage: string; }; const ActiveRoom = ({ roomName, userChoices, onLeave, userId, selectedLanguage, }: ActiveRoomProps) => { const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName }); const router = useRouter(); const { region, hq } = router.query; // const liveKitUrl = useServerUrl(region as string | undefined); const roomOptions = useMemo((): RoomOptions => { return { videoCaptureDefaults: { deviceId: userChoices.videoDeviceId ?? undefined, resolution: hq === "true" ? VideoPresets.h2160 : VideoPresets.h720, }, publishDefaults: { videoSimulcastLayers: hq === "true" ? [VideoPresets.h1080, VideoPresets.h720] : [VideoPresets.h540, VideoPresets.h216], }, audioCaptureDefaults: { deviceId: userChoices.audioDeviceId ?? undefined, }, adaptiveStream: { pixelDensity: "screen" }, dynacast: true, }; }, [userChoices, hq]); const [transcriptionQueue, setTranscriptionQueue] = useState< { sender: string; message: string; senderId: string; isFinal: boolean; }[] >([]); useTranscribe({ roomName, audioEnabled: userChoices.audioEnabled, languageCode: selectedLanguage, }); useEffect(() => { const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, { cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string, }); const channel = pusher.subscribe(roomName); channel.bind( "transcribe-event", function (data: { sender: string; message: string; senderId: string; isFinal: boolean; }) { if (data.isFinal && userId !== data.senderId) { setTranscriptionQueue((prev) => { return [...prev, data]; }); } } ); return () => { pusher.unsubscribe(roomName); }; }, []); return ( <> {data && ( <LiveKitRoom token={data.accessToken} serverUrl={process.env.NEXT_PUBLIC_LIVEKIT_API_HOST} options={roomOptions} video={userChoices.videoEnabled} audio={userChoices.audioEnabled} onDisconnected={onLeave} > <Captions transcriptionQueue={transcriptionQueue} setTranscriptionQueue={setTranscriptionQueue} languageCode={selectedLanguage} /> <VideoConference chatMessageFormatter={formatChatMessageLinks} />
<DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )}
</> ); };
src/pages/rooms/[name].tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/captions/index.tsx", "retrieved_chunk": " }, [transcriptionQueue]);\n return (\n <div className=\"closed-captions-wrapper z-50\">\n <div className=\"closed-captions-container\">\n {caption?.message ? (\n <>\n <div className=\"closed-captions-username\">{caption.sender}</div>\n <span>:&nbsp;</span>\n </>\n ) : null}", "score": 0.86436927318573 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": "};\ninterface Props {\n transcriptionQueue: Transcription[];\n setTranscriptionQueue: Dispatch<SetStateAction<Transcription[]>>;\n languageCode: string;\n}\nconst Captions: React.FC<Props> = ({\n transcriptionQueue,\n setTranscriptionQueue,\n languageCode,", "score": 0.8504146337509155 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " />\n <div className=\"flex flex-col items-center justify-center space-y-4 lg:flex-row lg:space-y-0 lg:space-x-4\">\n <button onClick={createRoomHandler} className=\"lk-button h-fit\">\n {roomLoading ? (\n <Loader />\n ) : (\n <>\n <AiOutlineVideoCameraAdd />\n <CharacterAnimation\n text=\"Create Room\"", "score": 0.8426468372344971 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " textStyle=\"text-sm\"\n />\n </>\n )}\n </button>\n {!roomLoading && <JoinRoom />}\n </div>\n </div>\n <div className=\"flex w-full max-w-md items-center justify-center\">\n <Hero className=\"h-[40vh] w-full md:h-screen\" />", "score": 0.8296099305152893 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": "}) => {\n const [caption, setCaption] = useState<{ sender: string; message: string }>();\n useEffect(() => {\n async function translateText() {\n console.info(\"transcriptionQueue\", transcriptionQueue);\n if (transcriptionQueue.length > 0) {\n const res = await translate(transcriptionQueue[0]?.message as string, {\n // @ts-ignore\n to: languageCode.split(\"-\")[0],\n });", "score": 0.8260902166366577 } ]
typescript
<DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )}
import { Dispatch, SetStateAction, type FunctionComponent } from "react"; import { api } from "~/utils/api"; import { Dialog, Transition } from "@headlessui/react"; import { Fragment, useState } from "react"; import Loader from "../loader"; import Tabs from "../tabs"; type ModalProps = { setIsOpen: Dispatch<SetStateAction<boolean>>; roomName: string; visible: boolean; }; const Modal: FunctionComponent<ModalProps> = ({ setIsOpen, roomName, visible, }) => { const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({ roomName, }); console.log(data); // input array // output array-> contents [0].utterance return ( <Transition appear show={visible} as={Fragment}> <Dialog as="div" className="relative z-10" onClose={() => setIsOpen(false)} > <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-center justify-center p-4 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-200" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white bg-opacity-10 p-6 text-left align-middle shadow-xl backdrop-blur-2xl backdrop-filter transition-all"> <Dialog.Title as="h3" className="gradient-text text-lg font-medium leading-6" > Meeting Details </Dialog.Title> <div className=""> {isLoading ? ( <Loader /> ) : data ? ( <div className="text-sm text-gray-100 text-opacity-50"> {data.output[0].contents.length > 1 && (
<Tabs summary={data.output[0].contents[1]?.utterance}
transcriptions={data.input} /> )} </div> ) : ( <div className="text-sm text-gray-100 text-opacity-50"> No summary available </div> )} </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Modal;
src/components/modal/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " </Tab>\n </Tab.List>\n <Tab.Panels className=\"mt-2 space-x-10\">\n <Tab.Panel>\n <p className=\"text-lg text-white\">{summary}</p>\n </Tab.Panel>\n <Tab.Panel>\n {transcriptions.map((transcription: any, index) => {\n return (\n <div className=\"bg-white-opacity-5 w-full p-2\" key={index}>", "score": 0.8395811319351196 }, { "filename": "src/components/splashScreen/index.tsx", "retrieved_chunk": " className=\"h-12 w-auto\"\n priority\n />\n <div className=\"flex flex-col items-center justify-center\">\n <h1 className=\"gradient-text text-4xl font-bold\">Jab We Meet</h1>\n <div className=\"text-center text-gray-300\">\n Loading your experience...\n <Loader />\n </div>\n </div>", "score": 0.805793285369873 }, { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " <h2 className=\"gradient-text\">{transcription?.speaker}</h2>\n <p className=\"font-lg text-white\">\n {transcription.utterance}\n </p>\n <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {transcription.timestamp}\n </div>\n </div>\n );\n })}", "score": 0.805695652961731 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Features from \"~/components/features\";\nimport CharacterAnimation from \"~/components/animation/character\";\nimport { useRive, Layout, Fit, Alignment } from \"@rive-app/react-canvas\";\nimport TextAnimation from \"~/components/animation/text\";\nimport Loader from \"~/components/loader\";\nimport Footer from \"~/components/footer\";\nimport SplashScreen from \"~/components/splashScreen\";\nfunction ConnectionTab() {\n const { data: session, status } = useSession();", "score": 0.8035951852798462 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " >\n <Captions\n transcriptionQueue={transcriptionQueue}\n setTranscriptionQueue={setTranscriptionQueue}\n languageCode={selectedLanguage}\n />\n <VideoConference chatMessageFormatter={formatChatMessageLinks} />\n <DebugMode logLevel={LogLevel.info} />\n </LiveKitRoom>\n )}", "score": 0.8021296262741089 } ]
typescript
<Tabs summary={data.output[0].contents[1]?.utterance}
import Image from "next/image"; import Link from "next/link"; import CharacterAnimation from "../animation/character"; import { BiMenuAltRight as MenuIcon } from "react-icons/bi"; import { AiOutlineClose as XIcon } from "react-icons/ai"; import { useState } from "react"; import { signIn, signOut } from "next-auth/react"; import { Session } from "next-auth"; import { FcGoogle } from "react-icons/fc"; import PopAnimation from "../animation/pop"; import Loader from "../loader"; const Navbar = ({ status, session, }: { status: "loading" | "authenticated" | "unauthenticated"; session: Session | null; }) => { const links = [ { label: "Home", path: "#", }, { label: "About", path: "#about", }, { label: "Contact", path: "#contact", }, ]; const [isMenuOpen, setIsMenuOpen] = useState(false); const toggleMenu = () => { setIsMenuOpen(!isMenuOpen); }; return ( <nav className="fixed top-0 z-10 w-full border-b border-gray-400/20 bg-white bg-opacity-5 backdrop-blur-lg backdrop-filter"> <div className="mx-auto max-w-5xl px-4"> <div className="flex h-16 items-center justify-between"> <Link href="/" className="flex items-center space-x-2"> <PopAnimation> <Image src="/logo.png" alt="Logo" width={40} height={40} priority /> </PopAnimation> <CharacterAnimation text="Jab We Meet" textStyle="text-xl font-bold text-white" /> </Link> <div className="hidden space-x-6 text-white lg:flex lg:items-center"> {links.map((link) => ( <Link className="transition-colors duration-300 hover:text-gray-400" key={link.path} href={link.path} > <CharacterAnimation text={link.label} textStyle="text-lg font-medium" /> </Link> ))} <PopAnimation> <button className="lk-button" onClick={() => { if (status === "authenticated") { signOut(); } else { signIn("google"); } }} > {status === "authenticated" ? ( "Sign Out" ) : ( <div className="flex items-center space-x-2"> <FcGoogle /> <div>Sign In</div> </div> )} </button> </PopAnimation> <PopAnimation> <select className="lk-button"> <option value="en">English</option> </select> </PopAnimation> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <
Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string}
width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> <div className="flex items-center space-x-4 lg:hidden"> {isMenuOpen ? ( <XIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> ) : ( <MenuIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> )} </div> </div> {isMenuOpen && ( <div className="flex flex-col space-y-2 p-5 text-white lg:hidden"> {links.map((link) => ( <Link key={link.path} href={link.path} className="block py-2 px-4 text-sm hover:bg-white" > {link.label} </Link> ))} <div className="flex items-center space-x-4"> <button className="lk-button" onClick={() => { if (status === "authenticated") { signIn("google"); } else { signOut(); } }} > {status === "authenticated" ? "Sign Out" : "Sign In"} </button> <select className="lk-button"> <option value="en">English</option> </select> </div> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> )} </div> </nav> ); }; export default Navbar;
src/components/navbar/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " ))}\n </select>\n </label>\n </div>\n </>\n ) : (\n <div className=\"flex h-screen flex-col items-center justify-center\">\n <div className=\"lk-prejoin flex flex-col gap-3\">\n <div className=\"text-2xl font-bold\">Hey, {session?.user.name}!</div>\n <div className=\"text-sm font-normal\">", "score": 0.8627252578735352 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": "import { signIn, useSession } from \"next-auth/react\";\nimport TextAnimation from \"~/components/animation/text\";\nimport Card from \"~/components/card\";\nimport Footer from \"~/components/footer\";\nimport Loader from \"~/components/loader\";\nimport Navbar from \"~/components/navbar\";\nimport SplashScreen from \"~/components/splashScreen\";\nimport { api } from \"~/utils/api\";\nfunction profile() {\n const { data: session, status } = useSession();", "score": 0.847635805606842 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Link from \"next/link\";\nimport PopAnimation from \"../animation/pop\";\nimport TextAnimation from \"../animation/text\";\nconst Footer = () => {\n const links = [\n {\n label: \"Home\",\n path: \"#\",\n },", "score": 0.83760666847229 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " };\n if (status === \"loading\") return <SplashScreen />;\n return (\n <>\n <Navbar status={status} session={session} />\n <div className=\"isolate overflow-x-hidden\">\n <div className=\"flex h-screen w-screen flex-col items-center justify-center space-y-4 p-5 text-center md:flex-row\">\n <div className=\"absolute inset-x-0 top-[-10rem] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[-20rem]\">\n <svg\n className=\"relative left-[calc(50%-11rem)] -z-10 h-[21.1875rem] max-w-none -translate-x-1/2 rotate-[30deg] sm:left-[calc(50%-30rem)] sm:h-[42.375rem]\"", "score": 0.8357223272323608 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " hour12: true,\n })}\n </div>\n <PopAnimation className=\"flex flex-row items-center justify-center\">\n <button\n onClick={() => setIsOpen(true)}\n className=\"mt-5 flex flex-row items-center justify-center space-x-2 rounded-lg bg-gray-100 bg-opacity-5 p-2 backdrop-blur-lg backdrop-filter hover:bg-gray-100 hover:bg-opacity-10\"\n >\n <IoDocumentTextOutline\n className=\"text-2xl text-gray-100\"", "score": 0.833768904209137 } ]
typescript
Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string}
// @refresh reset import type { NextPage } from "next"; import { signIn, useSession } from "next-auth/react"; import { useRouter } from "next/router"; import React from "react"; import Typing from "~/components/animation/typing"; import Navbar from "~/components/navbar"; import { api } from "~/utils/api"; import { AiOutlineVideoCameraAdd } from "react-icons/ai"; import JoinRoom from "~/components/join"; import Image from "next/image"; import Features from "~/components/features"; import CharacterAnimation from "~/components/animation/character"; import { useRive, Layout, Fit, Alignment } from "@rive-app/react-canvas"; import TextAnimation from "~/components/animation/text"; import Loader from "~/components/loader"; import Footer from "~/components/footer"; import SplashScreen from "~/components/splashScreen"; function ConnectionTab() { const { data: session, status } = useSession(); const createRoom = api.rooms.createRoom.useMutation(); const router = useRouter(); const { RiveComponent: Hero } = useRive({ src: `hero.riv`, stateMachines: ["State Machine 1"], autoplay: true, layout: new Layout({ fit: Fit.FitWidth, alignment: Alignment.Center, }), }); const [roomLoading, setRoomLoading] = React.useState(false); const createRoomHandler = async () => { if (status === "unauthenticated") signIn("google"); else { setRoomLoading(true); const data = await createRoom.mutateAsync(); setRoomLoading(false); router.push(`/rooms/${data.roomName}`); } }; if (status === "loading") return <SplashScreen />; return ( <> <Navbar status={status} session={session} /> <div className="isolate overflow-x-hidden"> <div className="flex h-screen w-screen flex-col items-center justify-center space-y-4 p-5 text-center md:flex-row"> <div className="absolute inset-x-0 top-[-10rem] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[-20rem]"> <svg className="relative left-[calc(50%-11rem)] -z-10 h-[21.1875rem] max-w-none -translate-x-1/2 rotate-[30deg] sm:left-[calc(50%-30rem)] sm:h-[42.375rem]" viewBox="0 0 1155 678" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fill="url(#45de2b6b-92d5-4d68-a6a0-9b9b2abad533)" fillOpacity=".3" d="M317.219 518.975L203.852 678 0 438.341l317.219 80.634 204.172-286.402c1.307 132.337 45.083 346.658 209.733 145.248C936.936 126.058 882.053-94.234 1031.02 41.331c119.18 108.451 130.68 295.337 121.53 375.223L855 299l21.173 362.054-558.954-142.079z" /> <defs> <linearGradient id="45de2b6b-92d5-4d68-a6a0-9b9b2abad533" x1="1155.49" x2="-78.208" y1=".177" y2="474.645" gradientUnits="userSpaceOnUse" > <stop stopColor="#9089FC" /> <stop offset={1} stopColor="#FF80B5" /> </linearGradient> </defs> </svg> </div> <div className="w-full max-w-md space-y-4"> <Typing /> <TextAnimation className="flex justify-center" textStyle="text-sm text-gray-400" text="Multilingual Video Conferencing App" /> <div className="flex flex-col items-center justify-center space-y-4 lg:flex-row lg:space-y-0 lg:space-x-4"> <button onClick={createRoomHandler} className="lk-button h-fit"> {roomLoading ? ( <Loader /> ) : ( <> <AiOutlineVideoCameraAdd /> <CharacterAnimation text="Create Room" textStyle="text-sm" /> </> )} </button>
{!roomLoading && <JoinRoom />}
</div> </div> <div className="flex w-full max-w-md items-center justify-center"> <Hero className="h-[40vh] w-full md:h-screen" /> </div> </div> <Features /> <Footer /> <div className="absolute inset-x-0 top-[calc(100%-13rem)] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[calc(100%-30rem)]"> <svg className="relative left-[calc(50%+3rem)] h-[21.1875rem] max-w-none -translate-x-1/2 sm:left-[calc(50%+36rem)] sm:h-[42.375rem]" viewBox="0 0 1155 678" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fill="url(#ecb5b0c9-546c-4772-8c71-4d3f06d544bc)" fillOpacity=".3" d="M317.219 518.975L203.852 678 0 438.341l317.219 80.634 204.172-286.402c1.307 132.337 45.083 346.658 209.733 145.248C936.936 126.058 882.053-94.234 1031.02 41.331c119.18 108.451 130.68 295.337 121.53 375.223L855 299l21.173 362.054-558.954-142.079z" /> <defs> <linearGradient id="ecb5b0c9-546c-4772-8c71-4d3f06d544bc" x1="1155.49" x2="-78.208" y1=".177" y2="474.645" gradientUnits="userSpaceOnUse" > <stop stopColor="#9089FC" /> <stop offset={1} stopColor="#FF80B5" /> </linearGradient> </defs> </svg> </div> </div> </> ); } const Home: NextPage = () => { return ( <> <main data-lk-theme="default"> <ConnectionTab /> </main> </> ); }; export default Home;
src/pages/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/join/index.tsx", "retrieved_chunk": " />\n </label>\n <button\n disabled={!roomName}\n className={`lk-button ${\n !roomName && \"pointer-events-none cursor-not-allowed\"\n }`}\n onClick={() => router.push(`/rooms/${roomName}`)}\n >\n <CharacterAnimation text=\"Join\" textStyle=\"text-sm\"/>", "score": 0.8933725953102112 }, { "filename": "src/components/join/index.tsx", "retrieved_chunk": " </button>\n </div>\n );\n};\nexport default JoinRoom;", "score": 0.8618765473365784 }, { "filename": "src/components/join/index.tsx", "retrieved_chunk": "import { useRouter } from \"next/router\";\nimport { useState } from \"react\";\nimport { BsKeyboard } from \"react-icons/bs\";\nimport CharacterAnimation from \"../animation/character\";\nconst JoinRoom = () => {\n const [roomName, setRoomName] = useState<string>(\"\");\n const router = useRouter();\n return (\n <div className=\"flex items-center space-x-4 p-2 text-white\">\n <label className=\"relative\">", "score": 0.8604748249053955 }, { "filename": "src/components/join/index.tsx", "retrieved_chunk": " <input\n value={roomName}\n onChange={(e) => setRoomName(e.target.value)}\n type=\"text\"\n placeholder=\"Enter Room Name\"\n className=\"rounded-md bg-white bg-opacity-30 p-2 text-white\"\n />\n <BsKeyboard\n size={20}\n className=\"absolute top-1/2 right-2 -translate-y-1/2 transform text-white\"", "score": 0.8399508595466614 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " slug: string | null;\n createdAt: Date;\n };\n}) {\n let [isOpen, setIsOpen] = useState(false)\n return (\n <div className=\"m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10\">\n <div key={room.name}>\n <TextAnimation textStyle=\"text-xl font-bold text-white\" text=\"Room\" />\n <div className=\"gradient-text\">{room.slug || room.name}</div>", "score": 0.8394613265991211 } ]
typescript
{!roomLoading && <JoinRoom />}
import { Dispatch, SetStateAction, type FunctionComponent } from "react"; import { api } from "~/utils/api"; import { Dialog, Transition } from "@headlessui/react"; import { Fragment, useState } from "react"; import Loader from "../loader"; import Tabs from "../tabs"; type ModalProps = { setIsOpen: Dispatch<SetStateAction<boolean>>; roomName: string; visible: boolean; }; const Modal: FunctionComponent<ModalProps> = ({ setIsOpen, roomName, visible, }) => { const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({ roomName, }); console.log(data); // input array // output array-> contents [0].utterance return ( <Transition appear show={visible} as={Fragment}> <Dialog as="div" className="relative z-10" onClose={() => setIsOpen(false)} > <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-center justify-center p-4 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-200" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white bg-opacity-10 p-6 text-left align-middle shadow-xl backdrop-blur-2xl backdrop-filter transition-all"> <Dialog.Title as="h3" className="gradient-text text-lg font-medium leading-6" > Meeting Details </Dialog.Title> <div className=""> {isLoading ? ( <Loader /> ) : data ? ( <div className="text-sm text-gray-100 text-opacity-50"> {data.output[0].contents.length > 1 && ( <
Tabs summary={data.output[0].contents[1]?.utterance}
transcriptions={data.input} /> )} </div> ) : ( <div className="text-sm text-gray-100 text-opacity-50"> No summary available </div> )} </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Modal;
src/components/modal/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " </Tab>\n </Tab.List>\n <Tab.Panels className=\"mt-2 space-x-10\">\n <Tab.Panel>\n <p className=\"text-lg text-white\">{summary}</p>\n </Tab.Panel>\n <Tab.Panel>\n {transcriptions.map((transcription: any, index) => {\n return (\n <div className=\"bg-white-opacity-5 w-full p-2\" key={index}>", "score": 0.8532792925834656 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": " }, [transcriptionQueue]);\n return (\n <div className=\"closed-captions-wrapper z-50\">\n <div className=\"closed-captions-container\">\n {caption?.message ? (\n <>\n <div className=\"closed-captions-username\">{caption.sender}</div>\n <span>:&nbsp;</span>\n </>\n ) : null}", "score": 0.8301036357879639 }, { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " <h2 className=\"gradient-text\">{transcription?.speaker}</h2>\n <p className=\"font-lg text-white\">\n {transcription.utterance}\n </p>\n <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {transcription.timestamp}\n </div>\n </div>\n );\n })}", "score": 0.8228944540023804 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " >\n <Captions\n transcriptionQueue={transcriptionQueue}\n setTranscriptionQueue={setTranscriptionQueue}\n languageCode={selectedLanguage}\n />\n <VideoConference chatMessageFormatter={formatChatMessageLinks} />\n <DebugMode logLevel={LogLevel.info} />\n </LiveKitRoom>\n )}", "score": 0.8201512098312378 }, { "filename": "src/components/splashScreen/index.tsx", "retrieved_chunk": " className=\"h-12 w-auto\"\n priority\n />\n <div className=\"flex flex-col items-center justify-center\">\n <h1 className=\"gradient-text text-4xl font-bold\">Jab We Meet</h1>\n <div className=\"text-center text-gray-300\">\n Loading your experience...\n <Loader />\n </div>\n </div>", "score": 0.8177183866500854 } ]
typescript
Tabs summary={data.output[0].contents[1]?.utterance}
import Image from "next/image"; import Link from "next/link"; import CharacterAnimation from "../animation/character"; import { BiMenuAltRight as MenuIcon } from "react-icons/bi"; import { AiOutlineClose as XIcon } from "react-icons/ai"; import { useState } from "react"; import { signIn, signOut } from "next-auth/react"; import { Session } from "next-auth"; import { FcGoogle } from "react-icons/fc"; import PopAnimation from "../animation/pop"; import Loader from "../loader"; const Navbar = ({ status, session, }: { status: "loading" | "authenticated" | "unauthenticated"; session: Session | null; }) => { const links = [ { label: "Home", path: "#", }, { label: "About", path: "#about", }, { label: "Contact", path: "#contact", }, ]; const [isMenuOpen, setIsMenuOpen] = useState(false); const toggleMenu = () => { setIsMenuOpen(!isMenuOpen); }; return ( <nav className="fixed top-0 z-10 w-full border-b border-gray-400/20 bg-white bg-opacity-5 backdrop-blur-lg backdrop-filter"> <div className="mx-auto max-w-5xl px-4"> <div className="flex h-16 items-center justify-between"> <Link href="/" className="flex items-center space-x-2">
<PopAnimation> <Image src="/logo.png" alt="Logo" width={40}
height={40} priority /> </PopAnimation> <CharacterAnimation text="Jab We Meet" textStyle="text-xl font-bold text-white" /> </Link> <div className="hidden space-x-6 text-white lg:flex lg:items-center"> {links.map((link) => ( <Link className="transition-colors duration-300 hover:text-gray-400" key={link.path} href={link.path} > <CharacterAnimation text={link.label} textStyle="text-lg font-medium" /> </Link> ))} <PopAnimation> <button className="lk-button" onClick={() => { if (status === "authenticated") { signOut(); } else { signIn("google"); } }} > {status === "authenticated" ? ( "Sign Out" ) : ( <div className="flex items-center space-x-2"> <FcGoogle /> <div>Sign In</div> </div> )} </button> </PopAnimation> <PopAnimation> <select className="lk-button"> <option value="en">English</option> </select> </PopAnimation> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> <div className="flex items-center space-x-4 lg:hidden"> {isMenuOpen ? ( <XIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> ) : ( <MenuIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> )} </div> </div> {isMenuOpen && ( <div className="flex flex-col space-y-2 p-5 text-white lg:hidden"> {links.map((link) => ( <Link key={link.path} href={link.path} className="block py-2 px-4 text-sm hover:bg-white" > {link.label} </Link> ))} <div className="flex items-center space-x-4"> <button className="lk-button" onClick={() => { if (status === "authenticated") { signIn("google"); } else { signOut(); } }} > {status === "authenticated" ? "Sign Out" : "Sign In"} </button> <select className="lk-button"> <option value="en">English</option> </select> </div> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> )} </div> </nav> ); }; export default Navbar;
src/components/navbar/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " <footer id=\"contact\" className=\"bg-gray-900\">\n <div className=\"mx-auto max-w-5xl px-4 py-16 sm:px-6 lg:px-8\">\n <PopAnimation className=\"flex justify-center text-primary\">\n <Image\n src=\"/logo.png\"\n alt=\"Logo\"\n width={100}\n height={100}\n className=\"h-12 w-auto\"\n />", "score": 0.8984088897705078 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " </PopAnimation>\n <p className=\"mx-auto mt-6 max-w-md text-center leading-relaxed text-white\">\n <TextAnimation text=\"Jab We Meet\" className=\"flex justify-center\" />\n <TextAnimation\n text=\"Multilingual Video Conferencing App\"\n className=\"flex justify-center\"\n textStyle=\"text-xs text-gray-300\"\n />\n </p>\n <nav className=\"mt-12\">", "score": 0.8743767738342285 }, { "filename": "src/components/modal/index.tsx", "retrieved_chunk": " <div className=\"fixed inset-0 overflow-y-auto\">\n <div className=\"flex min-h-full items-center justify-center p-4 text-center\">\n <Transition.Child\n as={Fragment}\n enter=\"ease-out duration-300\"\n enterFrom=\"opacity-0 scale-95\"\n enterTo=\"opacity-100 scale-100\"\n leave=\"ease-in duration-200\"\n leaveFrom=\"opacity-100 scale-100\"\n leaveTo=\"opacity-0 scale-95\"", "score": 0.8715066313743591 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Link from \"next/link\";\nimport PopAnimation from \"../animation/pop\";\nimport TextAnimation from \"../animation/text\";\nconst Footer = () => {\n const links = [\n {\n label: \"Home\",\n path: \"#\",\n },", "score": 0.8537404537200928 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " };\n if (status === \"loading\") return <SplashScreen />;\n return (\n <>\n <Navbar status={status} session={session} />\n <div className=\"isolate overflow-x-hidden\">\n <div className=\"flex h-screen w-screen flex-col items-center justify-center space-y-4 p-5 text-center md:flex-row\">\n <div className=\"absolute inset-x-0 top-[-10rem] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[-20rem]\">\n <svg\n className=\"relative left-[calc(50%-11rem)] -z-10 h-[21.1875rem] max-w-none -translate-x-1/2 rotate-[30deg] sm:left-[calc(50%-30rem)] sm:h-[42.375rem]\"", "score": 0.8433316349983215 } ]
typescript
<PopAnimation> <Image src="/logo.png" alt="Logo" width={40}
import { LiveKitRoom, PreJoin, LocalUserChoices, VideoConference, formatChatMessageLinks, } from "@livekit/components-react"; import { LogLevel, RoomOptions, VideoPresets } from "livekit-client"; import type { NextPage } from "next"; import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { DebugMode } from "../../lib/Debug"; import { api } from "~/utils/api"; import { signIn, useSession } from "next-auth/react"; import Pusher from "pusher-js"; import useTranscribe from "~/hooks/useTranscribe"; import Captions from "~/components/captions"; import SplashScreen from "~/components/splashScreen"; import { AiFillSetting } from "react-icons/ai"; const Home: NextPage = () => { const router = useRouter(); const { name: roomName } = router.query; const { data: session, status } = useSession(); const [preJoinChoices, setPreJoinChoices] = useState< LocalUserChoices | undefined >(undefined); const [selectedCode, setSelectedCode] = useState("en"); if (status === "loading") return <SplashScreen />; if (!session) signIn("google"); const languageCodes = [ { language: "English", code: "en-US", }, { language: "Hindi", code: "hi-IN", }, { language: "Japanese", code: "ja-JP", }, { language: "French", code: "fr-FR", }, { language: "Deutsch", code: "de-DE", }, ]; return ( <main data-lk-theme="default"> {roomName && !Array.isArray(roomName) && preJoinChoices ? ( <> <ActiveRoom roomName={roomName} userChoices={preJoinChoices} onLeave={() => setPreJoinChoices(undefined)} userId={session?.user.id as string} selectedLanguage={selectedCode} ></ActiveRoom> <div className="lk-prejoin" style={{ width: "100%", }} > <label className="flex items-center justify-center gap-2"> <span className="flex items-center space-x-2 text-center text-xs lg:text-sm"> <AiFillSetting /> <a>Switch Language</a> </span> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} defaultValue={selectedCode} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </label> </div> </> ) : ( <div className="flex h-screen flex-col items-center justify-center"> <div className="lk-prejoin flex flex-col gap-3"> <div className="text-2xl font-bold">Hey, {session?.user.name}!</div> <div className="text-sm font-normal"> You are joining{" "} <span className="gradient-text font-semibold">{roomName}</span> </div> <label> <span>Choose your Language</span> </label> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </div> <PreJoin onError={(err) => console.log("Error while setting up prejoin", err) } defaults={{ username: session?.user.name as string, videoEnabled: true, audioEnabled: true, }} onSubmit={(values) => { console.log("Joining with: ", values); setPreJoinChoices(values); }} ></PreJoin> </div> )} </main> ); }; export default Home; type ActiveRoomProps = { userChoices: LocalUserChoices; roomName: string; region?: string; onLeave?: () => void; userId: string; selectedLanguage: string; }; const ActiveRoom = ({ roomName, userChoices, onLeave, userId, selectedLanguage, }: ActiveRoomProps) => {
const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName });
const router = useRouter(); const { region, hq } = router.query; // const liveKitUrl = useServerUrl(region as string | undefined); const roomOptions = useMemo((): RoomOptions => { return { videoCaptureDefaults: { deviceId: userChoices.videoDeviceId ?? undefined, resolution: hq === "true" ? VideoPresets.h2160 : VideoPresets.h720, }, publishDefaults: { videoSimulcastLayers: hq === "true" ? [VideoPresets.h1080, VideoPresets.h720] : [VideoPresets.h540, VideoPresets.h216], }, audioCaptureDefaults: { deviceId: userChoices.audioDeviceId ?? undefined, }, adaptiveStream: { pixelDensity: "screen" }, dynacast: true, }; }, [userChoices, hq]); const [transcriptionQueue, setTranscriptionQueue] = useState< { sender: string; message: string; senderId: string; isFinal: boolean; }[] >([]); useTranscribe({ roomName, audioEnabled: userChoices.audioEnabled, languageCode: selectedLanguage, }); useEffect(() => { const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, { cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string, }); const channel = pusher.subscribe(roomName); channel.bind( "transcribe-event", function (data: { sender: string; message: string; senderId: string; isFinal: boolean; }) { if (data.isFinal && userId !== data.senderId) { setTranscriptionQueue((prev) => { return [...prev, data]; }); } } ); return () => { pusher.unsubscribe(roomName); }; }, []); return ( <> {data && ( <LiveKitRoom token={data.accessToken} serverUrl={process.env.NEXT_PUBLIC_LIVEKIT_API_HOST} options={roomOptions} video={userChoices.videoEnabled} audio={userChoices.audioEnabled} onDisconnected={onLeave} > <Captions transcriptionQueue={transcriptionQueue} setTranscriptionQueue={setTranscriptionQueue} languageCode={selectedLanguage} /> <VideoConference chatMessageFormatter={formatChatMessageLinks} /> <DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )} </> ); };
src/pages/rooms/[name].tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/modal/index.tsx", "retrieved_chunk": "};\nconst Modal: FunctionComponent<ModalProps> = ({\n setIsOpen,\n roomName,\n visible,\n}) => {\n const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({\n roomName,\n });\n console.log(data);", "score": 0.8732154369354248 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": " const { data: rooms, isLoading, error } = api.rooms.getRoomsByUser.useQuery();\n if (status === \"loading\") return <SplashScreen />;\n if (!session && status === \"unauthenticated\") return signIn(\"google\");\n const ownedRooms =\n rooms?.filter((room) => room.OwnerId === session?.user.id) || [];\n const joinedRooms =\n rooms?.filter((room) => room.OwnerId !== session?.user.id) || [];\n return (\n <>\n <Navbar status={status} session={session} />", "score": 0.8543609976768494 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " });\n const [roomLoading, setRoomLoading] = React.useState(false);\n const createRoomHandler = async () => {\n if (status === \"unauthenticated\") signIn(\"google\");\n else {\n setRoomLoading(true);\n const data = await createRoom.mutateAsync();\n setRoomLoading(false);\n router.push(`/rooms/${data.roomName}`);\n }", "score": 0.8514928817749023 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " slug: string | null;\n createdAt: Date;\n };\n}) {\n let [isOpen, setIsOpen] = useState(false)\n return (\n <div className=\"m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10\">\n <div key={room.name}>\n <TextAnimation textStyle=\"text-xl font-bold text-white\" text=\"Room\" />\n <div className=\"gradient-text\">{room.slug || room.name}</div>", "score": 0.8458076119422913 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": "import { useEffect } from \"react\";\nimport SpeechRecognition, {\n useSpeechRecognition,\n} from \"react-speech-recognition\";\nimport { api } from \"~/utils/api\";\ntype UseTranscribeProps = {\n roomName: string;\n audioEnabled: boolean;\n languageCode?: string;\n};", "score": 0.84440016746521 } ]
typescript
const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName });
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant); const result: TokenResult = { identity, accessToken: token, }; try { // check if user is already in room console.log("here");
const participant = await ctx.prisma.participant.findUnique({
where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order const transcripts = await ctx.prisma.transcript.findMany({ where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, }); const chatLog = transcripts.map((transcript) => ({ speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " .input(\n z.object({\n message: string(),\n roomName: string(),\n isFinal: z.boolean(),\n })\n )\n .mutation(async ({ input, ctx }) => {\n const { message } = input;\n const { user } = ctx.session;", "score": 0.850922703742981 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 0.8497028946876526 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const response = await pusher.trigger(\n input.roomName,\n \"transcribe-event\",\n {\n message,\n sender: user.name,\n isFinal: input.isFinal,\n senderId: user.id,\n }\n );", "score": 0.8234846591949463 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " });\n const [roomLoading, setRoomLoading] = React.useState(false);\n const createRoomHandler = async () => {\n if (status === \"unauthenticated\") signIn(\"google\");\n else {\n setRoomLoading(true);\n const data = await createRoom.mutateAsync();\n setRoomLoading(false);\n router.push(`/rooms/${data.roomName}`);\n }", "score": 0.8166158199310303 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " const channel = pusher.subscribe(roomName);\n channel.bind(\n \"transcribe-event\",\n function (data: {\n sender: string;\n message: string;\n senderId: string;\n isFinal: boolean;\n }) {\n if (data.isFinal && userId !== data.senderId) {", "score": 0.8103159666061401 } ]
typescript
const participant = await ctx.prisma.participant.findUnique({
import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { env } from "~/env.mjs"; import { prisma } from "~/server/db"; /** * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` * object and keep type safety. * * @see https://next-auth.js.org/getting-started/typescript#module-augmentation */ declare module "next-auth" { interface Session extends DefaultSession { user: { id: string; // ...other properties // role: UserRole; } & DefaultSession["user"]; } // interface User { // // ...other properties // // role: UserRole; // } } /** * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. * * @see https://next-auth.js.org/configuration/options */ export const authOptions: NextAuthOptions = { callbacks: { session({ session, user }) { if (session.user) { session.user.id = user.id; // session.user.role = user.role; <-- put other properties on the session here } return session; }, }, adapter: PrismaAdapter(prisma), providers: [ GoogleProvider({ clientId: env.
GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
/** * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. * * @see https://next-auth.js.org/configuration/nextjs */ export const getServerAuthSession = (ctx: { req: GetServerSidePropsContext["req"]; res: GetServerSidePropsContext["res"]; }) => { return getServerSession(ctx.req, ctx.res, authOptions); };
src/server/auth.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/db.ts", "retrieved_chunk": "import { PrismaClient } from \"@prisma/client\";\nimport { env } from \"~/env.mjs\";\nconst globalForPrisma = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma =\n globalForPrisma.prisma ||\n new PrismaClient({\n log:\n env.NODE_ENV === \"development\" ? [\"query\", \"error\", \"warn\"] : [\"error\"],\n });\nif (env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;", "score": 0.888027548789978 }, { "filename": "src/utils/api.ts", "retrieved_chunk": " ],\n };\n },\n /**\n * Whether tRPC should await queries when server rendering pages.\n *\n * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false\n */\n ssr: false,\n});", "score": 0.8204021453857422 }, { "filename": "src/utils/pusher.ts", "retrieved_chunk": "import Pusher from \"pusher\";\nexport const pusher = new Pusher({\n appId: process.env.PUSHER_APP_ID as string,\n key: process.env.PUSHER_KEY as string,\n secret: process.env.PUSHER_SECRET as string,\n cluster: process.env.PUSHER_CLUSTER as string,\n useTLS: true,\n});", "score": 0.8116925954818726 }, { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": "import { createNextApiHandler } from \"@trpc/server/adapters/next\";\nimport { env } from \"~/env.mjs\";\nimport { createTRPCContext } from \"~/server/api/trpc\";\nimport { appRouter } from \"~/server/api/root\";\n// export API handler\nexport default createNextApiHandler({\n router: appRouter,\n createContext: createTRPCContext,\n onError:\n env.NODE_ENV === \"development\"", "score": 0.8098897933959961 }, { "filename": "src/pages/api/auth/[...nextauth].ts", "retrieved_chunk": "import NextAuth from \"next-auth\";\nimport { authOptions } from \"~/server/auth\";\nexport default NextAuth(authOptions);", "score": 0.7942414283752441 } ]
typescript
GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant); const result: TokenResult = { identity, accessToken: token, }; try { // check if user is already in room console.log("here"); const participant = await ctx.prisma.participant.findUnique({ where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order const transcripts = await ctx.prisma.transcript.findMany({ where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, }); const chatLog
= transcripts.map((transcript) => ({
speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 0.7994092106819153 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " dynacast: true,\n };\n }, [userChoices, hq]);\n const [transcriptionQueue, setTranscriptionQueue] = useState<\n {\n sender: string;\n message: string;\n senderId: string;\n isFinal: boolean;\n }[]", "score": 0.7989893555641174 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": "}) => {\n const [caption, setCaption] = useState<{ sender: string; message: string }>();\n useEffect(() => {\n async function translateText() {\n console.info(\"transcriptionQueue\", transcriptionQueue);\n if (transcriptionQueue.length > 0) {\n const res = await translate(transcriptionQueue[0]?.message as string, {\n // @ts-ignore\n to: languageCode.split(\"-\")[0],\n });", "score": 0.7952240705490112 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": "const useTranscribe = ({\n roomName,\n audioEnabled,\n languageCode,\n}: UseTranscribeProps) => {\n const {\n transcript,\n resetTranscript,\n finalTranscript,\n browserSupportsSpeechRecognition,", "score": 0.790675163269043 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " >\n <Captions\n transcriptionQueue={transcriptionQueue}\n setTranscriptionQueue={setTranscriptionQueue}\n languageCode={selectedLanguage}\n />\n <VideoConference chatMessageFormatter={formatChatMessageLinks} />\n <DebugMode logLevel={LogLevel.info} />\n </LiveKitRoom>\n )}", "score": 0.7887482047080994 } ]
typescript
= transcripts.map((transcript) => ({
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request
: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> {
if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/dtos/login-request.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}", "score": 0.840649425983429 }, { "filename": "src/dtos/login-response.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nexport class LoginResponseDto {\n @ApiProperty()\n public readonly accessToken: string;\n @ApiProperty()\n public readonly refreshToken: string;\n}", "score": 0.824265718460083 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8242378234863281 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.8222423791885376 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8218088150024414 } ]
typescript
: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> {
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant); const result: TokenResult = { identity, accessToken: token, }; try { // check if user is already in room console.log("here"); const participant = await ctx.prisma.participant.findUnique({ where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order
const transcripts = await ctx.prisma.transcript.findMany({
where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, }); const chatLog = transcripts.map((transcript) => ({ speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " .input(\n z.object({\n message: string(),\n roomName: string(),\n isFinal: z.boolean(),\n })\n )\n .mutation(async ({ input, ctx }) => {\n const { message } = input;\n const { user } = ctx.session;", "score": 0.8455355167388916 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 0.8426306247711182 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": "const useTranscribe = ({\n roomName,\n audioEnabled,\n languageCode,\n}: UseTranscribeProps) => {\n const {\n transcript,\n resetTranscript,\n finalTranscript,\n browserSupportsSpeechRecognition,", "score": 0.7956657409667969 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName });\n const router = useRouter();\n const { region, hq } = router.query;\n // const liveKitUrl = useServerUrl(region as string | undefined);\n const roomOptions = useMemo((): RoomOptions => {\n return {\n videoCaptureDefaults: {\n deviceId: userChoices.videoDeviceId ?? undefined,\n resolution: hq === \"true\" ? VideoPresets.h2160 : VideoPresets.h720,\n },", "score": 0.7925072312355042 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": "import { string, z } from \"zod\";\nimport { pusher } from \"~/utils/pusher\";\nimport {\n createTRPCRouter,\n publicProcedure,\n protectedProcedure,\n} from \"~/server/api/trpc\";\nimport { translate } from \"@vitalets/google-translate-api\";\nexport const pusherRouter = createTRPCRouter({\n send: protectedProcedure", "score": 0.7771155834197998 } ]
typescript
const transcripts = await ctx.prisma.transcript.findMany({
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login(
@Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> {
if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/dtos/login-request.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}", "score": 0.8442267179489136 }, { "filename": "src/dtos/login-response.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nexport class LoginResponseDto {\n @ApiProperty()\n public readonly accessToken: string;\n @ApiProperty()\n public readonly refreshToken: string;\n}", "score": 0.8280661106109619 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8274782299995422 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8254828453063965 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.8240986466407776 } ]
typescript
@Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> {
/** * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which * contains the Next.js App-wrapper, as well as your type-safe React Query hooks. * * We also create a few inference helpers for input and output types. */ import { httpBatchLink, loggerLink } from "@trpc/client"; import { createTRPCNext } from "@trpc/next"; import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"; import superjson from "superjson"; import { type AppRouter } from "~/server/api/root"; const getBaseUrl = () => { if (typeof window !== "undefined") return ""; // browser should use relative url if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost }; /** A set of type-safe react-query hooks for your tRPC API. */ export const api = createTRPCNext<AppRouter>({ config() { return { /** * Transformer used for data de-serialization from the server. * * @see https://trpc.io/docs/data-transformers */ transformer: superjson, /** * Links used to determine request flow from client to server. * * @see https://trpc.io/docs/links */ links: [ loggerLink({ enabled: (opts) => process.env.NODE_ENV === "development" || (opts.direction === "down" && opts.result instanceof Error), }), httpBatchLink({ url: `${getBaseUrl()}/api/trpc`, }), ], }; }, /** * Whether tRPC should await queries when server rendering pages. * * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false */ ssr: false, }); /** * Inference helper for inputs. * * @example type HelloInput = RouterInputs['example']['hello'] */ export type RouterInputs
= inferRouterInputs<AppRouter>;
/** * Inference helper for outputs. * * @example type HelloOutput = RouterOutputs['example']['hello'] */ export type RouterOutputs = inferRouterOutputs<AppRouter>;
src/utils/api.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/api/root.ts", "retrieved_chunk": " pusher: pusherRouter,\n});\n// export type definition of API\nexport type AppRouter = typeof appRouter;", "score": 0.793311595916748 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " transformer: superjson,\n errorFormatter({ shape }) {\n return shape;\n },\n});\n/**\n * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)\n *\n * These are the pieces you use to build your tRPC API. You should import these a lot in the\n * \"/src/server/api/routers\" directory.", "score": 0.7455253601074219 }, { "filename": "src/pages/_app.tsx", "retrieved_chunk": "import { type AppType } from \"next/app\";\nimport { type Session } from \"next-auth\";\nimport { SessionProvider } from \"next-auth/react\";\nimport { api } from \"~/utils/api\";\nimport \"~/styles/globals.css\";\nimport \"@livekit/components-styles\";\nimport \"@livekit/components-styles/prefabs\";\nimport Head from \"next/head\";\nconst MyApp: AppType<{ session: Session | null }> = ({\n Component,", "score": 0.74509596824646 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " session: Session | null;\n};\n/**\n * This helper generates the \"internals\" for a tRPC context. If you need to use it, you can export\n * it from here.\n *\n * Examples of things you may need it for:\n * - testing, so we don't have to mock Next.js' req/res\n * - tRPC's `createSSGHelpers`, where we don't have req/res\n *", "score": 0.7432259321212769 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName });\n const router = useRouter();\n const { region, hq } = router.query;\n // const liveKitUrl = useServerUrl(region as string | undefined);\n const roomOptions = useMemo((): RoomOptions => {\n return {\n videoCaptureDefaults: {\n deviceId: userChoices.videoDeviceId ?? undefined,\n resolution: hq === \"true\" ? VideoPresets.h2160 : VideoPresets.h720,\n },", "score": 0.7425624132156372 } ]
typescript
= inferRouterInputs<AppRouter>;
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[
TokenType.PasswordlessLoginToken];
if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8766372799873352 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8511502742767334 }, { "filename": "src/generators/passwordless-login-token.generator.ts", "retrieved_chunk": " constructor(\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n async generate(user: IUser, requestId: string): Promise<IToken> {\n const id = randomUUID();\n const ttl = this.config.auth.passwordless.tokenTtl;\n const expiresAt = new Date();\n expiresAt.setSeconds(expiresAt.getSeconds() + ttl);\n return new TokenModel(", "score": 0.8323268890380859 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 0.8253034353256226 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.8237640261650085 } ]
typescript
TokenType.PasswordlessLoginToken];
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response);
this.eventBus.publish(new LoggedInEvent(user.getId()));
return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8658599853515625 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.8563159108161926 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8536324501037598 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8450958728790283 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 0.8407086133956909 } ]
typescript
this.eventBus.publish(new LoggedInEvent(user.getId()));
import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { env } from "~/env.mjs"; import { prisma } from "~/server/db"; /** * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` * object and keep type safety. * * @see https://next-auth.js.org/getting-started/typescript#module-augmentation */ declare module "next-auth" { interface Session extends DefaultSession { user: { id: string; // ...other properties // role: UserRole; } & DefaultSession["user"]; } // interface User { // // ...other properties // // role: UserRole; // } } /** * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. * * @see https://next-auth.js.org/configuration/options */ export const authOptions: NextAuthOptions = { callbacks: { session({ session, user }) { if (session.user) { session.user.id = user.id; // session.user.role = user.role; <-- put other properties on the session here } return session; }, }, adapter: PrismaAdapter(prisma), providers: [ GoogleProvider({ clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
/** * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. * * @see https://next-auth.js.org/configuration/nextjs */ export const getServerAuthSession = (ctx: { req: GetServerSidePropsContext["req"]; res: GetServerSidePropsContext["res"]; }) => { return getServerSession(ctx.req, ctx.res, authOptions); };
src/server/auth.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/db.ts", "retrieved_chunk": "import { PrismaClient } from \"@prisma/client\";\nimport { env } from \"~/env.mjs\";\nconst globalForPrisma = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma =\n globalForPrisma.prisma ||\n new PrismaClient({\n log:\n env.NODE_ENV === \"development\" ? [\"query\", \"error\", \"warn\"] : [\"error\"],\n });\nif (env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;", "score": 0.8856109380722046 }, { "filename": "src/utils/api.ts", "retrieved_chunk": " ],\n };\n },\n /**\n * Whether tRPC should await queries when server rendering pages.\n *\n * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false\n */\n ssr: false,\n});", "score": 0.8231953382492065 }, { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": "import { createNextApiHandler } from \"@trpc/server/adapters/next\";\nimport { env } from \"~/env.mjs\";\nimport { createTRPCContext } from \"~/server/api/trpc\";\nimport { appRouter } from \"~/server/api/root\";\n// export API handler\nexport default createNextApiHandler({\n router: appRouter,\n createContext: createTRPCContext,\n onError:\n env.NODE_ENV === \"development\"", "score": 0.8050100803375244 }, { "filename": "src/utils/pusher.ts", "retrieved_chunk": "import Pusher from \"pusher\";\nexport const pusher = new Pusher({\n appId: process.env.PUSHER_APP_ID as string,\n key: process.env.PUSHER_KEY as string,\n secret: process.env.PUSHER_SECRET as string,\n cluster: process.env.PUSHER_CLUSTER as string,\n useTLS: true,\n});", "score": 0.8030766248703003 }, { "filename": "src/pages/api/auth/[...nextauth].ts", "retrieved_chunk": "import NextAuth from \"next-auth\";\nimport { authOptions } from \"~/server/auth\";\nexport default NextAuth(authOptions);", "score": 0.7935926914215088 } ]
typescript
clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.
publish(new LoggedOutEvent(activeUser.userId));
} }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8865209221839905 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8374419212341309 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 0.829768180847168 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.8275437355041504 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 0.8266547918319702 } ]
typescript
publish(new LoggedOutEvent(activeUser.userId));
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { APP_GUARD } from '@nestjs/core'; import { CqrsModule } from '@nestjs/cqrs'; import { JwtModule } from '@nestjs/jwt'; import iamConfig from './configs/iam.config'; import { AuthController } from './controllers/auth.controller'; import { AccessTokenGenerator } from './generators/access-token.generator'; import { PasswordlessLoginTokenGenerator } from './generators/passwordless-login-token.generator'; import { RefreshTokenGenerator } from './generators/refresh-token.generator'; import { AccessTokenGuard } from './guards/access-token.guard'; import { AuthGuard } from './guards/auth.guard'; import { NoneGuard } from './guards/none.guard'; import { RolesGuard } from './guards/roles.guard'; import { BcryptHasher } from './hashers/bcrypt.hasher'; import { ConfigurableModuleClass } from './iam.module-definition'; import { LoginProcessor } from './processors/login.processor'; import { LogoutProcessor } from './processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from './processors/passwordless-login-request.processor'; @Module({ imports: [ ConfigModule.forFeature(iamConfig), CqrsModule, JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (config: ConfigService) => ({ secret: config.get('iam.jwt.secret'), signOptions: { audience: config.get('iam.jwt.audience'), issuer: config.get('iam.jwt.issuer'), }, }), inject: [ConfigService], }), ], providers: [ AccessTokenGenerator, AccessTokenGuard, AuthGuard, BcryptHasher, LoginProcessor, LogoutProcessor, NoneGuard, PasswordlessLoginRequestProcessor, PasswordlessLoginTokenGenerator, RefreshTokenGenerator, RolesGuard, { provide: APP_GUARD, useClass: AuthGuard, }, { provide: APP_GUARD, useClass: RolesGuard, }, ], exports: [BcryptHasher, LoginProcessor], controllers
: [AuthController], }) export class IamModule extends ConfigurableModuleClass {}
src/iam.module.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/controllers/auth.controller.ts", "retrieved_chunk": "import { AuthType } from '../enums/auth-type.enum';\nimport { TokenType } from '../enums/token-type.enum';\nimport { LoggedInEvent } from '../events/logged-in.event';\nimport { LoggedOutEvent } from '../events/logged-out.event';\nimport { BcryptHasher } from '../hashers/bcrypt.hasher';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IActiveUser } from '../interfaces/active-user.interface';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\nimport { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface';\nimport { LoginProcessor } from '../processors/login.processor';", "score": 0.8536447882652283 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { Response } from 'express';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { AccessTokenGenerator } from '../generators/access-token.generator';\nimport { RefreshTokenGenerator } from '../generators/refresh-token.generator';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { ILogin } from '../interfaces/login.interface';\nimport { IModuleOptions } from '../interfaces/module-options.interface';", "score": 0.845199465751648 }, { "filename": "src/index.ts", "retrieved_chunk": "export * from './decorators/active-user.decorator';\nexport * from './decorators/auth.decorator';\nexport * from './decorators/roles.decorator';\nexport * from './enums/auth-type.enum';\nexport * from './enums/token-type.enum';\nexport * from './events/logged-in.event';\nexport * from './events/logged-out.event';\nexport * from './hashers/bcrypt.hasher';\nexport * from './iam.module';\nexport * from './interfaces/active-user.interface';", "score": 0.8383760452270508 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { randomUUID } from 'crypto';\nimport { Response } from 'express';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { PasswordlessLoginTokenGenerator } from '../generators/passwordless-login-token.generator';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\nimport { IUser } from '../interfaces/user.interface';", "score": 0.8382187485694885 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { JwtService } from '@nestjs/jwt';\nimport { Request, Response } from 'express';\nimport { IRefreshTokenJwtPayload } from 'src/interfaces/refresh-token-jwt-payload.interface';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\n@Injectable()", "score": 0.8369054198265076 } ]
typescript
: [AuthController], }) export class IamModule extends ConfigurableModuleClass {}
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest(
@Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> {
if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8639873266220093 }, { "filename": "src/dtos/passwordless-login-request-request.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class PasswordlessLoginRequestRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n}", "score": 0.8468613624572754 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8429276347160339 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8183132410049438 }, { "filename": "src/dtos/login-request.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}", "score": 0.8085986375808716 } ]
typescript
@Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> {
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser:
IActiveUser, ) {
await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8611732125282288 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 0.8273193836212158 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 0.8199081420898438 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8043990731239319 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8030891418457031 } ]
typescript
IActiveUser, ) {
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body()
request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> {
if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8653194904327393 }, { "filename": "src/dtos/passwordless-login-request-request.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class PasswordlessLoginRequestRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n}", "score": 0.8437172770500183 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8409385681152344 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8170406818389893 }, { "filename": "src/dtos/login-request.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}", "score": 0.8057596683502197 } ]
typescript
request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> {
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @
ActiveUser() activeUser: IActiveUser, ) {
await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8637173771858215 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 0.8292386531829834 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 0.8174068927764893 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8052380681037903 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8007616996765137 } ]
typescript
ActiveUser() activeUser: IActiveUser, ) {
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response,
@ActiveUser() activeUser: IActiveUser, ) {
await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8644369840621948 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 0.8313901424407959 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 0.821465015411377 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8096383810043335 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8080319166183472 } ]
typescript
@ActiveUser() activeUser: IActiveUser, ) {
import { toError } from '../core/helper.js'; import { CacheStrategy } from './strategy.js'; import { CacheStrategyOptions, FetchListenerEnv } from './types.js'; export interface NetworkOnlyOptions extends Omit<CacheStrategyOptions, 'cacheName' | 'matchOptions'> { networkTimeoutSeconds?: number; } export class NetworkOnly extends CacheStrategy { private fetchListenerEnv: FetchListenerEnv; private readonly _networkTimeoutSeconds: number; constructor(options: NetworkOnlyOptions = {}, env?: FetchListenerEnv) { // this is gonna come back and bite me. // I need to sort this out quick though //@ts-ignore super(options); this.fetchListenerEnv = env || {}; this._networkTimeoutSeconds = options.networkTimeoutSeconds || 10; } override async _handle(request: Request) { if (request.method !== 'GET') { return fetch(request); } // `fetcher` is a custom fetch function that can de defined and passed to the constructor or just regular fetch const fetcher = this.fetchListenerEnv.state!.fetcher || fetch; const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject( new Error( `Network request timed out after ${ this._networkTimeoutSeconds * 1000 } seconds` ) ); }, this._networkTimeoutSeconds * 1000); }); try { for (let plugin of this.plugins) { if (plugin.requestWillFetch) { plugin.requestWillFetch({ request }); } } const fetchPromise: Response = await fetcher(request); const response = (await Promise.race([ fetchPromise, timeoutPromise ])) as Response; if (response) { for (const plugin of this.plugins) { if (plugin.fetchDidSucceed) { await plugin.fetchDidSucceed({ request, response }); } } return response; } // Re-thrown error to be caught by `catch` block throw new Error('Network request failed'); } catch (error) { for (const plugin of this.plugins) { if (plugin.fetchDidFail) { await plugin.fetchDidFail({ request, error:
toError(error) });
} } const headers = { 'X-Remix-Catch': 'yes', 'X-Remix-Worker': 'yes' }; return new Response(JSON.stringify({ message: 'Network Error' }), { status: 500, ...(this.isLoader ? { headers } : {}) }); } } }
src/strategy/networkOnly.ts
remix-pwa-sw-eb66466
[ { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " let response = await fetch(req).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail) {\n plugin.fetchDidFail({\n request: req.clone(),\n error: err\n });\n }\n }\n });", "score": 0.8928633332252502 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " request: updatedRequest\n });\n }\n }\n const fetchPromise = fetcher(updatedRequest).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail)\n plugin.fetchDidFail({\n request: updatedRequest,\n error: err as unknown as Error", "score": 0.8694229125976562 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " )\n );\n }, this._networkTimeoutSeconds * 1000);\n })\n : null;\n const fetcher = this.fetchListenerEnv.state?.fetcher || fetch;\n let updatedRequest = request.clone();\n for (const plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n updatedRequest = await plugin.requestWillFetch({", "score": 0.8570545315742493 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " }\n return null;\n }\n private async getFromNetwork(request: Request): Promise<Response | null> {\n let req: Request = request.clone();\n for (const plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n req = await plugin.requestWillFetch({ request: req });\n }\n }", "score": 0.8466749787330627 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " if (response) {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidSucceed) {\n response = await plugin.fetchDidSucceed({ request: req, response });\n }\n }\n return response;\n }\n return null;\n }", "score": 0.8447443246841431 } ]
typescript
toError(error) });
import { toError } from '../core/helper.js'; import { CacheStrategy } from './strategy.js'; import { CacheStrategyOptions, FetchListenerEnv } from './types.js'; export interface NetworkOnlyOptions extends Omit<CacheStrategyOptions, 'cacheName' | 'matchOptions'> { networkTimeoutSeconds?: number; } export class NetworkOnly extends CacheStrategy { private fetchListenerEnv: FetchListenerEnv; private readonly _networkTimeoutSeconds: number; constructor(options: NetworkOnlyOptions = {}, env?: FetchListenerEnv) { // this is gonna come back and bite me. // I need to sort this out quick though //@ts-ignore super(options); this.fetchListenerEnv = env || {}; this._networkTimeoutSeconds = options.networkTimeoutSeconds || 10; } override async _handle(request: Request) { if (request.method !== 'GET') { return fetch(request); } // `fetcher` is a custom fetch function that can de defined and passed to the constructor or just regular fetch const fetcher = this.fetchListenerEnv.state!.fetcher || fetch; const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject( new Error( `Network request timed out after ${ this._networkTimeoutSeconds * 1000 } seconds` ) ); }, this._networkTimeoutSeconds * 1000); }); try {
for (let plugin of this.plugins) {
if (plugin.requestWillFetch) { plugin.requestWillFetch({ request }); } } const fetchPromise: Response = await fetcher(request); const response = (await Promise.race([ fetchPromise, timeoutPromise ])) as Response; if (response) { for (const plugin of this.plugins) { if (plugin.fetchDidSucceed) { await plugin.fetchDidSucceed({ request, response }); } } return response; } // Re-thrown error to be caught by `catch` block throw new Error('Network request failed'); } catch (error) { for (const plugin of this.plugins) { if (plugin.fetchDidFail) { await plugin.fetchDidFail({ request, error: toError(error) }); } } const headers = { 'X-Remix-Catch': 'yes', 'X-Remix-Worker': 'yes' }; return new Response(JSON.stringify({ message: 'Network Error' }), { status: 500, ...(this.isLoader ? { headers } : {}) }); } } }
src/strategy/networkOnly.ts
remix-pwa-sw-eb66466
[ { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " )\n );\n }, this._networkTimeoutSeconds * 1000);\n })\n : null;\n const fetcher = this.fetchListenerEnv.state?.fetcher || fetch;\n let updatedRequest = request.clone();\n for (const plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n updatedRequest = await plugin.requestWillFetch({", "score": 0.8452804088592529 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " }\n private async fetchAndCache(request: Request): Promise<Response> {\n const cache = await caches.open(this.cacheName);\n const timeoutPromise =\n this._networkTimeoutSeconds !== Infinity\n ? new Promise<Response>((_, reject) => {\n setTimeout(() => {\n reject(\n new Error(\n `Network timed out after ${this._networkTimeoutSeconds} seconds`", "score": 0.840117335319519 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " let response = await fetch(req).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail) {\n plugin.fetchDidFail({\n request: req.clone(),\n error: err\n });\n }\n }\n });", "score": 0.8163022994995117 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " }\n return null;\n }\n private async getFromNetwork(request: Request): Promise<Response | null> {\n let req: Request = request.clone();\n for (const plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n req = await plugin.requestWillFetch({ request: req });\n }\n }", "score": 0.8059054017066956 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " for (const plugin of this.plugins) {\n if (plugin.cacheDidUpdate) {\n plugin.cacheDidUpdate({\n cacheName: this.cacheName,\n request,\n oldResponse,\n newResponse\n });\n }\n }", "score": 0.8043308258056641 } ]
typescript
for (let plugin of this.plugins) {
import { toError } from '../core/helper.js'; import { CacheStrategy } from './strategy.js'; import { CacheStrategyOptions, FetchListenerEnv } from './types.js'; export interface NetworkFirstOptions extends CacheStrategyOptions { networkTimeoutSeconds?: number; } export class NetworkFirst extends CacheStrategy { private fetchListenerEnv: FetchListenerEnv; private readonly _networkTimeoutSeconds: number; constructor(options: NetworkFirstOptions, env: FetchListenerEnv = {}) { super(options); this.fetchListenerEnv = env; // Default timeout of `Infinity` this._networkTimeoutSeconds = options.networkTimeoutSeconds || Infinity; } override async _handle(request: Request) { const cache = await caches.open(this.cacheName); try { const response = await this.fetchAndCache(request); return response; } catch (error) { let err = toError(error); const cachedResponse = await cache.match(request, this.matchOptions); if (cachedResponse) { const body = cachedResponse.clone().body; const headers = new Headers(cachedResponse.clone().headers); // Safari throws an error if we try to mutate the headers directly const newResponse = new Response(body, { headers: { ...headers, 'X-Remix-Worker': 'yes' }, status: cachedResponse.status, statusText: cachedResponse.statusText }); return newResponse; } // throw error; return new Response(JSON.stringify({ message: 'Network Error' }), { status: 500, headers: { 'X-Remix-Catch': 'yes', 'X-Remix-Worker': 'yes' } }); } } private async fetchAndCache(request: Request): Promise<Response> { const cache = await caches.open(this.cacheName); const timeoutPromise = this._networkTimeoutSeconds !== Infinity ? new Promise<Response>((_, reject) => { setTimeout(() => { reject( new Error( `Network timed out after ${this._networkTimeoutSeconds} seconds` ) ); }, this._networkTimeoutSeconds * 1000); }) : null; const fetcher = this.fetchListenerEnv.state?.fetcher || fetch; let updatedRequest = request.clone(); for (const plugin of this.plugins) { if (plugin.requestWillFetch) { updatedRequest = await plugin.requestWillFetch({ request: updatedRequest }); } }
const fetchPromise = fetcher(updatedRequest).catch((err) => {
for (const plugin of this.plugins) { if (plugin.fetchDidFail) plugin.fetchDidFail({ request: updatedRequest, error: err as unknown as Error }); } }); let response = timeoutPromise ? await Promise.race([fetchPromise, timeoutPromise]) : await fetchPromise; // If the fetch was successful, then proceed along else throw an error if (response) { // `fetchDidSucceed` performs some changes to response so store it elsewhere // to avoid overtyping original variable let updatedResponse: Response = response.clone(); for (const plugin of this.plugins) { if (plugin.fetchDidSucceed) { updatedResponse = await plugin.fetchDidSucceed({ request: updatedRequest, response: updatedResponse }); } } // `null` can be returned here to avoid caching resources. Hence store in // a new variable that can be checked for if null. let aboutToBeCachedResponse: Response | null = updatedResponse; for (const plugin of this.plugins) { if (plugin.cacheWillUpdate) { aboutToBeCachedResponse = await plugin.cacheWillUpdate({ request: updatedRequest, response: aboutToBeCachedResponse! }); if (!aboutToBeCachedResponse) { break; } } } // If response wasn't null, update cache and return the response if (aboutToBeCachedResponse) { await cache.put(request, response.clone()); for (const plugin of this.plugins) { if (plugin.cacheDidUpdate) { await plugin.cacheDidUpdate({ request: updatedRequest, cacheName: this.cacheName, newResponse: updatedResponse }); } } return aboutToBeCachedResponse; } return updatedResponse; } throw new Error('No response received from fetch: Timeout'); } }
src/strategy/networkFirst.ts
remix-pwa-sw-eb66466
[ { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " let response = await fetch(req).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail) {\n plugin.fetchDidFail({\n request: req.clone(),\n error: err\n });\n }\n }\n });", "score": 0.891402006149292 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " }\n return null;\n }\n private async getFromNetwork(request: Request): Promise<Response | null> {\n let req: Request = request.clone();\n for (const plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n req = await plugin.requestWillFetch({ request: req });\n }\n }", "score": 0.8740254044532776 }, { "filename": "src/strategy/networkOnly.ts", "retrieved_chunk": " });\n }\n }\n const fetchPromise: Response = await fetcher(request);\n const response = (await Promise.race([\n fetchPromise,\n timeoutPromise\n ])) as Response;\n if (response) {\n for (const plugin of this.plugins) {", "score": 0.8699719905853271 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " if (response) {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidSucceed) {\n response = await plugin.fetchDidSucceed({ request: req, response });\n }\n }\n return response;\n }\n return null;\n }", "score": 0.8691610097885132 }, { "filename": "src/strategy/networkOnly.ts", "retrieved_chunk": " throw new Error('Network request failed');\n } catch (error) {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail) {\n await plugin.fetchDidFail({\n request,\n error: toError(error)\n });\n }\n }", "score": 0.8568477630615234 } ]
typescript
const fetchPromise = fetcher(updatedRequest).catch((err) => {
import { logger } from '../core/logger.js'; import { MessageHandler } from './message.js'; import type { MessageHandlerParams } from './message.js'; export interface RemixNavigationHandlerOptions extends MessageHandlerParams { dataCacheName: string; documentCacheName: string; } export class RemixNavigationHandler extends MessageHandler { dataCacheName: string; documentCacheName: string; constructor({ plugins, dataCacheName, documentCacheName, state }: RemixNavigationHandlerOptions) { super({ plugins, state }); this.dataCacheName = dataCacheName; this.documentCacheName = documentCacheName; this._handleMessage = this._handleMessage.bind(this); } override async _handleMessage( event: ExtendableMessageEvent ): Promise<void> { const { data } = event; let DATA, PAGES; DATA = this.dataCacheName; PAGES = this.documentCacheName; this.runPlugins("messageDidReceive", { event, }) let cachePromises: Map<string, Promise<void>> = new Map(); if (data.type === 'REMIX_NAVIGATION') { let { isMount, location, matches, manifest } = data; let documentUrl = location.pathname + location.search + location.hash; let [dataCache, documentCache, existingDocument] = await Promise.all([ caches.open(DATA), caches.open(PAGES), caches.match(documentUrl) ]); if (!existingDocument || !isMount) { cachePromises.set( documentUrl, documentCache.add(documentUrl).catch((error) => {
logger.error(`Failed to cache document for ${documentUrl}:`, error);
}) ); } if (isMount) { for (let match of matches) { if (manifest.routes[match.id].hasLoader) { let params = new URLSearchParams(location.search); params.set('_data', match.id); let search = params.toString(); search = search ? `?${search}` : ''; let url = location.pathname + search + location.hash; if (!cachePromises.has(url)) { logger.debug('Caching data for:', url); cachePromises.set( url, dataCache.add(url).catch((error) => { logger.error(`Failed to cache data for ${url}:`, error); }) ); } } } } } await Promise.all(cachePromises.values()); } }
src/message/remixNavigationHandler.ts
remix-pwa-sw-eb66466
[ { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " if (cachePromises.has(assetUrl)) {\n continue;\n }\n cachePromises.set(assetUrl, cacheAsset(assetUrl));\n }\n }\n logger.info(\"Caching document:\", pathname);\n cachePromises.set(\n pathname,\n documentCache.add(pathname).catch((error) => {", "score": 0.901718258857727 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " if (error instanceof TypeError) {\n logger.error(`TypeError when caching document ${pathname}:`, error.message);\n } else if (error instanceof DOMException) {\n logger.error(`DOMException when caching document ${pathname}:`, error.message);\n } else {\n logger.error(`Failed to cache document ${pathname}:`, error);\n }\n })\n );\n }", "score": 0.8430728912353516 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " }\n async function cacheAsset(assetUrl: string) {\n if (await assetCache.match(assetUrl)) {\n return;\n }\n logger.debug(\"Caching asset:\", assetUrl);\n return assetCache.add(assetUrl).catch((error) => {\n if (error instanceof TypeError) {\n logger.error(`TypeError when caching asset ${assetUrl}:`, error.message);\n } else if (error instanceof DOMException) {", "score": 0.8396371603012085 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " ASSET_CACHE = this.assetCacheName;\n this.runPlugins(\"messageDidReceive\", {\n event,\n });\n const cachePromises: Map<string, Promise<void>> = new Map();\n const [dataCache, documentCache, assetCache] = await Promise.all([\n caches.open(DATA_CACHE),\n caches.open(DOCUMENT_CACHE),\n caches.open(ASSET_CACHE),\n ]);", "score": 0.8374664783477783 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " if (error instanceof TypeError) {\n logger.error(`TypeError when caching data ${pathname}:`, error.message);\n } else if (error instanceof DOMException) {\n logger.error(`DOMException when caching data ${pathname}:`, error.message);\n } else {\n logger.error(`Failed to cache data ${pathname}:`, error);\n }\n })\n );\n }", "score": 0.8314199447631836 } ]
typescript
logger.error(`Failed to cache document for ${documentUrl}:`, error);
import type { MessagePlugin } from '../plugins/interfaces/messagePlugin.js'; import type { MessageEnv } from './types.js'; export interface MessageHandlerParams { plugins?: MessagePlugin[]; state?: MessageEnv; } export abstract class MessageHandler { /** * The plugins array is used to run plugins before and after the message handler. * They are passed in when the handler is initialised. */ protected plugins: MessagePlugin[]; /** * The state object is used to pass data between plugins. */ protected state: MessageEnv; constructor({ plugins, state }: MessageHandlerParams = {}) { this.plugins = plugins || []; this.state = state || {}; } /** * The method that handles the message event. * * Takes in the MessageEvent as a mandatory argument as well as an optional * object that can be used to pass further information/data. */ async handle(event: ExtendableMessageEvent, state: Record<string, any> = {}) { await this._handleMessage(event, state); } protected abstract _handleMessage( event: ExtendableMessageEvent, state: Record<string, any> ): Promise<void> | void; /** * Runs the plugins that are passed in when the handler is initialised. */ protected
async runPlugins(hook: keyof MessagePlugin, env: MessageEnv) {
for (const plugin of this.plugins) { if (plugin[hook]) { plugin[hook]!(env); } } } }
src/message/message.ts
remix-pwa-sw-eb66466
[ { "filename": "src/message/remixNavigationHandler.ts", "retrieved_chunk": " }\n override async _handleMessage(\n event: ExtendableMessageEvent\n ): Promise<void> {\n const { data } = event;\n let DATA, PAGES;\n DATA = this.dataCacheName;\n PAGES = this.documentCacheName;\n this.runPlugins(\"messageDidReceive\", {\n event,", "score": 0.8536900281906128 }, { "filename": "src/plugins/interfaces/messagePlugin.ts", "retrieved_chunk": "import { MessageEnv } from '../../message/types.js';\n/**\n * A plugin that can be used to modify the message environment\n */\nexport interface MessagePlugin {\n /**\n * A function that is called when a message is received\n */\n messageDidReceive?: (env: MessageEnv) => void;\n /**", "score": 0.818026602268219 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " this.dataCacheName = dataCacheName;\n this.documentCacheName = documentCacheName;\n this.assetCacheName = assetCacheName;\n this._handleMessage = this._handleMessage.bind(this);\n this._ignoredFiles = state?.ignoredRoutes || null;\n }\n override async _handleMessage(event: ExtendableMessageEvent): Promise<void> {\n let DATA_CACHE, DOCUMENT_CACHE, ASSET_CACHE;\n DATA_CACHE = this.dataCacheName;\n DOCUMENT_CACHE = this.documentCacheName;", "score": 0.8158631920814514 }, { "filename": "src/message/types.ts", "retrieved_chunk": "/**\n * @fileoverview Global typings for `message` sub-module\n */\nexport interface MessageEnv {\n event?: ExtendableMessageEvent;\n state?: Record<string, any>;\n}", "score": 0.8045370578765869 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " ASSET_CACHE = this.assetCacheName;\n this.runPlugins(\"messageDidReceive\", {\n event,\n });\n const cachePromises: Map<string, Promise<void>> = new Map();\n const [dataCache, documentCache, assetCache] = await Promise.all([\n caches.open(DATA_CACHE),\n caches.open(DOCUMENT_CACHE),\n caches.open(ASSET_CACHE),\n ]);", "score": 0.7880545258522034 } ]
typescript
async runPlugins(hook: keyof MessagePlugin, env: MessageEnv) {
import type { MessagePlugin } from '../plugins/interfaces/messagePlugin.js'; import type { MessageEnv } from './types.js'; export interface MessageHandlerParams { plugins?: MessagePlugin[]; state?: MessageEnv; } export abstract class MessageHandler { /** * The plugins array is used to run plugins before and after the message handler. * They are passed in when the handler is initialised. */ protected plugins: MessagePlugin[]; /** * The state object is used to pass data between plugins. */ protected state: MessageEnv; constructor({ plugins, state }: MessageHandlerParams = {}) { this.plugins = plugins || []; this.state = state || {}; } /** * The method that handles the message event. * * Takes in the MessageEvent as a mandatory argument as well as an optional * object that can be used to pass further information/data. */ async handle(event: ExtendableMessageEvent, state: Record<string, any> = {}) { await this._handleMessage(event, state); } protected abstract _handleMessage( event: ExtendableMessageEvent, state: Record<string, any> ): Promise<void> | void; /** * Runs the plugins that are passed in when the handler is initialised. */ protected async runPlugins(
hook: keyof MessagePlugin, env: MessageEnv) {
for (const plugin of this.plugins) { if (plugin[hook]) { plugin[hook]!(env); } } } }
src/message/message.ts
remix-pwa-sw-eb66466
[ { "filename": "src/message/remixNavigationHandler.ts", "retrieved_chunk": " }\n override async _handleMessage(\n event: ExtendableMessageEvent\n ): Promise<void> {\n const { data } = event;\n let DATA, PAGES;\n DATA = this.dataCacheName;\n PAGES = this.documentCacheName;\n this.runPlugins(\"messageDidReceive\", {\n event,", "score": 0.8598580956459045 }, { "filename": "src/plugins/interfaces/messagePlugin.ts", "retrieved_chunk": "import { MessageEnv } from '../../message/types.js';\n/**\n * A plugin that can be used to modify the message environment\n */\nexport interface MessagePlugin {\n /**\n * A function that is called when a message is received\n */\n messageDidReceive?: (env: MessageEnv) => void;\n /**", "score": 0.8266109824180603 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " this.dataCacheName = dataCacheName;\n this.documentCacheName = documentCacheName;\n this.assetCacheName = assetCacheName;\n this._handleMessage = this._handleMessage.bind(this);\n this._ignoredFiles = state?.ignoredRoutes || null;\n }\n override async _handleMessage(event: ExtendableMessageEvent): Promise<void> {\n let DATA_CACHE, DOCUMENT_CACHE, ASSET_CACHE;\n DATA_CACHE = this.dataCacheName;\n DOCUMENT_CACHE = this.documentCacheName;", "score": 0.825871467590332 }, { "filename": "src/message/types.ts", "retrieved_chunk": "/**\n * @fileoverview Global typings for `message` sub-module\n */\nexport interface MessageEnv {\n event?: ExtendableMessageEvent;\n state?: Record<string, any>;\n}", "score": 0.8168983459472656 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " ASSET_CACHE = this.assetCacheName;\n this.runPlugins(\"messageDidReceive\", {\n event,\n });\n const cachePromises: Map<string, Promise<void>> = new Map();\n const [dataCache, documentCache, assetCache] = await Promise.all([\n caches.open(DATA_CACHE),\n caches.open(DOCUMENT_CACHE),\n caches.open(ASSET_CACHE),\n ]);", "score": 0.7983568906784058 } ]
typescript
hook: keyof MessagePlugin, env: MessageEnv) {
import { logger } from '../core/logger.js'; import { MessageHandler } from './message.js'; import type { MessageHandlerParams } from './message.js'; export interface RemixNavigationHandlerOptions extends MessageHandlerParams { dataCacheName: string; documentCacheName: string; } export class RemixNavigationHandler extends MessageHandler { dataCacheName: string; documentCacheName: string; constructor({ plugins, dataCacheName, documentCacheName, state }: RemixNavigationHandlerOptions) { super({ plugins, state }); this.dataCacheName = dataCacheName; this.documentCacheName = documentCacheName; this._handleMessage = this._handleMessage.bind(this); } override async _handleMessage( event: ExtendableMessageEvent ): Promise<void> { const { data } = event; let DATA, PAGES; DATA = this.dataCacheName; PAGES = this.documentCacheName; this.runPlugins("messageDidReceive", { event, }) let cachePromises: Map<string, Promise<void>> = new Map(); if (data.type === 'REMIX_NAVIGATION') { let { isMount, location, matches, manifest } = data; let documentUrl = location.pathname + location.search + location.hash; let [dataCache, documentCache, existingDocument] = await Promise.all([ caches.open(DATA), caches.open(PAGES), caches.match(documentUrl) ]); if (!existingDocument || !isMount) { cachePromises.set( documentUrl, documentCache.add(documentUrl).catch((error) => { logger.error(`Failed to cache document for ${documentUrl}:`, error); }) ); } if (isMount) { for (let match of matches) { if (manifest.routes[match.id].hasLoader) { let params = new URLSearchParams(location.search); params.set('_data', match.id); let search = params.toString(); search = search ? `?${search}` : ''; let url = location.pathname + search + location.hash; if (!cachePromises.has(url)) { logger.
debug('Caching data for:', url);
cachePromises.set( url, dataCache.add(url).catch((error) => { logger.error(`Failed to cache data for ${url}:`, error); }) ); } } } } } await Promise.all(cachePromises.values()); } }
src/message/remixNavigationHandler.ts
remix-pwa-sw-eb66466
[ { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " function cacheLoaderData(route: EntryRoute) {\n const pathname = getPathname(route);\n const params = new URLSearchParams({ _data: route.id });\n const search = `?${params.toString()}`;\n const url = pathname + search;\n if (!cachePromises.has(url)) {\n logger.debug(\"caching loader data\", url);\n cachePromises.set(\n url,\n dataCache.add(url).catch((error) => {", "score": 0.8769164085388184 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " logger.log(\"Precaching route:\", route.id);\n cacheRoute(route);\n }\n await Promise.all(cachePromises.values());\n function cacheRoute(route: EntryRoute) {\n const pathname = getPathname(route);\n if (route.hasLoader) {\n cacheLoaderData(route);\n }\n if (route.module) {", "score": 0.8515814542770386 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " cachePromises.set(route.module, cacheAsset(route.module));\n }\n if (route.imports) {\n for (const assetUrl of route.imports) {\n logger.groupCollapsed(\"Caching asset: \", assetUrl);\n logger.log(\"Is index:\", route.index || false);\n logger.log(\"Parent ID:\", route.parentId);\n logger.log(\"Imports:\", route.imports);\n logger.log(\"Module:\", route.module);\n logger.groupEnd();", "score": 0.8445081114768982 }, { "filename": "src/react/useSWEffect.ts", "retrieved_chunk": " isMount: mounted,\n location,\n matches: matches.filter(filteredMatches).map(sanitizeHandleObject),\n manifest: window.__remixManifest,\n });\n } else {\n let listener = async () => {\n await navigator.serviceWorker.ready;\n navigator.serviceWorker.controller?.postMessage({\n type: \"REMIX_NAVIGATION\",", "score": 0.8353585004806519 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " if (cachePromises.has(assetUrl)) {\n continue;\n }\n cachePromises.set(assetUrl, cacheAsset(assetUrl));\n }\n }\n logger.info(\"Caching document:\", pathname);\n cachePromises.set(\n pathname,\n documentCache.add(pathname).catch((error) => {", "score": 0.828918993473053 } ]
typescript
debug('Caching data for:', url);
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { APP_GUARD } from '@nestjs/core'; import { CqrsModule } from '@nestjs/cqrs'; import { JwtModule } from '@nestjs/jwt'; import iamConfig from './configs/iam.config'; import { AuthController } from './controllers/auth.controller'; import { AccessTokenGenerator } from './generators/access-token.generator'; import { PasswordlessLoginTokenGenerator } from './generators/passwordless-login-token.generator'; import { RefreshTokenGenerator } from './generators/refresh-token.generator'; import { AccessTokenGuard } from './guards/access-token.guard'; import { AuthGuard } from './guards/auth.guard'; import { NoneGuard } from './guards/none.guard'; import { RolesGuard } from './guards/roles.guard'; import { BcryptHasher } from './hashers/bcrypt.hasher'; import { ConfigurableModuleClass } from './iam.module-definition'; import { LoginProcessor } from './processors/login.processor'; import { LogoutProcessor } from './processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from './processors/passwordless-login-request.processor'; @Module({ imports: [ ConfigModule.forFeature(iamConfig), CqrsModule, JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (config: ConfigService) => ({ secret: config.get('iam.jwt.secret'), signOptions: { audience: config.get('iam.jwt.audience'), issuer: config.get('iam.jwt.issuer'), }, }), inject: [ConfigService], }), ], providers: [ AccessTokenGenerator, AccessTokenGuard, AuthGuard, BcryptHasher, LoginProcessor, LogoutProcessor, NoneGuard, PasswordlessLoginRequestProcessor, PasswordlessLoginTokenGenerator, RefreshTokenGenerator, RolesGuard, { provide: APP_GUARD, useClass: AuthGuard, }, { provide: APP_GUARD, useClass: RolesGuard, }, ], exports: [BcryptHasher, LoginProcessor], controllers: [AuthController], })
export class IamModule extends ConfigurableModuleClass {}
src/iam.module.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/controllers/auth.controller.ts", "retrieved_chunk": "import { AuthType } from '../enums/auth-type.enum';\nimport { TokenType } from '../enums/token-type.enum';\nimport { LoggedInEvent } from '../events/logged-in.event';\nimport { LoggedOutEvent } from '../events/logged-out.event';\nimport { BcryptHasher } from '../hashers/bcrypt.hasher';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IActiveUser } from '../interfaces/active-user.interface';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\nimport { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface';\nimport { LoginProcessor } from '../processors/login.processor';", "score": 0.8559384942054749 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { Response } from 'express';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { AccessTokenGenerator } from '../generators/access-token.generator';\nimport { RefreshTokenGenerator } from '../generators/refresh-token.generator';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { ILogin } from '../interfaces/login.interface';\nimport { IModuleOptions } from '../interfaces/module-options.interface';", "score": 0.8450756072998047 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { randomUUID } from 'crypto';\nimport { Response } from 'express';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { PasswordlessLoginTokenGenerator } from '../generators/passwordless-login-token.generator';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\nimport { IUser } from '../interfaces/user.interface';", "score": 0.8396013975143433 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { JwtService } from '@nestjs/jwt';\nimport { Request, Response } from 'express';\nimport { IRefreshTokenJwtPayload } from 'src/interfaces/refresh-token-jwt-payload.interface';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\n@Injectable()", "score": 0.8364177942276001 }, { "filename": "src/index.ts", "retrieved_chunk": "export * from './decorators/active-user.decorator';\nexport * from './decorators/auth.decorator';\nexport * from './decorators/roles.decorator';\nexport * from './enums/auth-type.enum';\nexport * from './enums/token-type.enum';\nexport * from './events/logged-in.event';\nexport * from './events/logged-out.event';\nexport * from './hashers/bcrypt.hasher';\nexport * from './iam.module';\nexport * from './interfaces/active-user.interface';", "score": 0.8349906802177429 } ]
typescript
export class IamModule extends ConfigurableModuleClass {}
import { logger } from "../../core/logger"; import { CacheQueryMatchOptions } from "../../strategy/types"; import { StrategyPlugin } from "../interfaces/strategyPlugin"; export class ExpirationPlugin implements StrategyPlugin { private readonly maxEntries: number; private readonly maxAgeSeconds: number; constructor({ maxEntries, maxAgeSeconds, }: { maxEntries?: number; maxAgeSeconds?: number } = {}) { this.maxAgeSeconds = maxAgeSeconds || 30 * 24 * 3_600; this.maxEntries = maxEntries || Infinity; } async cachedResponseWillBeUsed(options: { cacheName: string; request: Request; matchOptions: CacheQueryMatchOptions; cachedResponse: Response; event?: ExtendableEvent | undefined; }): Promise<Response | null> { const now = Date.now(); const expirationDate = options.cachedResponse.headers.get("X-Expires"); const newResponse = options.cachedResponse.clone() const headers = new Headers(newResponse.headers) const modifedResponse = new Response(newResponse.body, { status: newResponse.status, statusText: newResponse.statusText, headers }) if (expirationDate) { const elapsedTime = new Date(expirationDate).getTime() - now; if (elapsedTime < 0) { const cache = await caches.open(options.cacheName); await cache.delete(options.request, options.matchOptions); console.log("cacheResponseWillBeUsed", options.request.url); return options.cachedResponse; } modifedResponse.headers.set( "X-Access-Time", new Date(now).toUTCString() ); return modifedResponse } else { modifedResponse.headers.set( "X-Access-Time", new Date(now).toUTCString() ); return modifedResponse; } } async cacheWillUpdate(options: { response: Response; request: Request; event?: ExtendableEvent | undefined; }): Promise<Response | null> { const now = Date.now(); console.log("cacheWillUpdate", options.request.url); let newResponse = options.response.clone(); const headers = new Headers(newResponse.headers) const modifedResponse = new Response(newResponse.body, { status: newResponse.status, statusText: newResponse.statusText, headers }) modifedResponse.headers.set( "X-Expires", new Date(now + this.maxAgeSeconds * 1_000).toUTCString() ); return modifedResponse; } async cacheDidUpdate(options: { cacheName: string; request: Request; oldResponse?: Response | undefined; newResponse: Response; event?: ExtendableEvent | undefined; }) { const cache = await caches.open(options.cacheName); const keys = await cache.keys(); console.error(keys.length, this.maxEntries); if (keys.length > this.maxEntries) {
logger.debug("Cache is full, removing oldest entry");
this.removeLRUEntry(options.cacheName); } } async removeLRUEntry(cacheName: string) { const cache = await caches.open(cacheName); const keys = await cache.keys(); let oldestEntry: Response | null = null; for (const key of keys) { const entry = await cache.match(key); if (!entry) { continue; } if (!oldestEntry) { oldestEntry = entry; continue; } const oldestEntryDate = oldestEntry.headers.get("X-Access-Time"); const entryDate = entry.headers.get("X-Access-Time"); if (!oldestEntryDate || !entryDate) { continue; } if (new Date(oldestEntryDate).getTime() > new Date(entryDate).getTime()) { oldestEntry = entry; } } if (oldestEntry) { await cache.delete(oldestEntry.url); } } }
src/plugins/cache/expirationPlugin.ts
remix-pwa-sw-eb66466
[ { "filename": "src/plugins/interfaces/strategyPlugin.ts", "retrieved_chunk": " cacheDidUpdate?: (options: {\n cacheName: string;\n request: Request;\n oldResponse?: Response;\n newResponse: Response;\n event?: ExtendableEvent;\n }) => Promise<void>;\n // Called before a cached response is used to respond to a fetch event.\n /**\n * This is called just before a response from a cache is used, which allows you to examine that ", "score": 0.8627143502235413 }, { "filename": "src/plugins/interfaces/strategyPlugin.ts", "retrieved_chunk": " cacheWillUpdate?: (options: {\n response: Response;\n request: Request;\n event?: ExtendableEvent;\n }) => Promise<Response | null>;\n // Called after a response is stored in the cache.\n /**\n * Called when a new entry is added to a cache or if an existing entry is updated. \n * Plugins that use this method may be useful when you want to perform an action after a cache update.\n */", "score": 0.8514156937599182 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " private async updateCache(\n request: Request,\n response: Response\n ): Promise<void> {\n const cache = await caches.open(this.cacheName);\n const oldResponse = await cache.match(request);\n let newResponse: Response | null = response.clone();\n for (const plugin of this.plugins) {\n if (plugin.cacheWillUpdate) {\n newResponse = await plugin.cacheWillUpdate({", "score": 0.8493547439575195 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " let cachedResponse = await cache.match(request, {\n ignoreVary: this.matchOptions?.ignoreVary || false,\n ignoreSearch: this.matchOptions?.ignoreSearch || false\n });\n if (cachedResponse) {\n let res: Response | null = cachedResponse.clone();\n for (const plugin of this.plugins) {\n if (plugin.cachedResponseWillBeUsed) {\n res = await plugin.cachedResponseWillBeUsed({\n cacheName: this.cacheName,", "score": 0.8391409516334534 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " super(options);\n this.fetchListenerEnv = env;\n // Default timeout of `Infinity`\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || Infinity;\n }\n override async _handle(request: Request) {\n const cache = await caches.open(this.cacheName);\n try {\n const response = await this.fetchAndCache(request);\n return response;", "score": 0.8309788107872009 } ]
typescript
logger.debug("Cache is full, removing oldest entry");
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { APP_GUARD } from '@nestjs/core'; import { CqrsModule } from '@nestjs/cqrs'; import { JwtModule } from '@nestjs/jwt'; import iamConfig from './configs/iam.config'; import { AuthController } from './controllers/auth.controller'; import { AccessTokenGenerator } from './generators/access-token.generator'; import { PasswordlessLoginTokenGenerator } from './generators/passwordless-login-token.generator'; import { RefreshTokenGenerator } from './generators/refresh-token.generator'; import { AccessTokenGuard } from './guards/access-token.guard'; import { AuthGuard } from './guards/auth.guard'; import { NoneGuard } from './guards/none.guard'; import { RolesGuard } from './guards/roles.guard'; import { BcryptHasher } from './hashers/bcrypt.hasher'; import { ConfigurableModuleClass } from './iam.module-definition'; import { LoginProcessor } from './processors/login.processor'; import { LogoutProcessor } from './processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from './processors/passwordless-login-request.processor'; @Module({ imports: [ ConfigModule.forFeature(iamConfig), CqrsModule, JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (config: ConfigService) => ({ secret: config.get('iam.jwt.secret'), signOptions: { audience: config.get('iam.jwt.audience'), issuer: config.get('iam.jwt.issuer'), }, }), inject: [ConfigService], }), ], providers: [ AccessTokenGenerator, AccessTokenGuard, AuthGuard, BcryptHasher, LoginProcessor, LogoutProcessor, NoneGuard, PasswordlessLoginRequestProcessor, PasswordlessLoginTokenGenerator, RefreshTokenGenerator, RolesGuard, { provide: APP_GUARD, useClass: AuthGuard, }, { provide: APP_GUARD, useClass: RolesGuard, }, ], exports: [BcryptHasher, LoginProcessor], controllers: [AuthController], }) export class IamModule extends
ConfigurableModuleClass {}
src/iam.module.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/controllers/auth.controller.ts", "retrieved_chunk": "import { AuthType } from '../enums/auth-type.enum';\nimport { TokenType } from '../enums/token-type.enum';\nimport { LoggedInEvent } from '../events/logged-in.event';\nimport { LoggedOutEvent } from '../events/logged-out.event';\nimport { BcryptHasher } from '../hashers/bcrypt.hasher';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IActiveUser } from '../interfaces/active-user.interface';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\nimport { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface';\nimport { LoginProcessor } from '../processors/login.processor';", "score": 0.8523816466331482 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { Response } from 'express';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { AccessTokenGenerator } from '../generators/access-token.generator';\nimport { RefreshTokenGenerator } from '../generators/refresh-token.generator';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { ILogin } from '../interfaces/login.interface';\nimport { IModuleOptions } from '../interfaces/module-options.interface';", "score": 0.8447961807250977 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { randomUUID } from 'crypto';\nimport { Response } from 'express';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { PasswordlessLoginTokenGenerator } from '../generators/passwordless-login-token.generator';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\nimport { IUser } from '../interfaces/user.interface';", "score": 0.8379120230674744 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { JwtService } from '@nestjs/jwt';\nimport { Request, Response } from 'express';\nimport { IRefreshTokenJwtPayload } from 'src/interfaces/refresh-token-jwt-payload.interface';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\n@Injectable()", "score": 0.8367493748664856 }, { "filename": "src/index.ts", "retrieved_chunk": "export * from './decorators/active-user.decorator';\nexport * from './decorators/auth.decorator';\nexport * from './decorators/roles.decorator';\nexport * from './enums/auth-type.enum';\nexport * from './enums/token-type.enum';\nexport * from './events/logged-in.event';\nexport * from './events/logged-out.event';\nexport * from './hashers/bcrypt.hasher';\nexport * from './iam.module';\nexport * from './interfaces/active-user.interface';", "score": 0.8365275859832764 } ]
typescript
ConfigurableModuleClass {}
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, );
if (!(await this.hasher.compare(request.password, user.getPassword()))) {
throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8432102203369141 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.838127076625824 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8253040909767151 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8185123205184937 }, { "filename": "src/dtos/login-request.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}", "score": 0.8148656487464905 } ]
typescript
if (!(await this.hasher.compare(request.password, user.getPassword()))) {
import { toError } from '../core/helper.js'; import { CacheStrategy } from './strategy.js'; import { CacheStrategyOptions, FetchListenerEnv } from './types.js'; export interface NetworkOnlyOptions extends Omit<CacheStrategyOptions, 'cacheName' | 'matchOptions'> { networkTimeoutSeconds?: number; } export class NetworkOnly extends CacheStrategy { private fetchListenerEnv: FetchListenerEnv; private readonly _networkTimeoutSeconds: number; constructor(options: NetworkOnlyOptions = {}, env?: FetchListenerEnv) { // this is gonna come back and bite me. // I need to sort this out quick though //@ts-ignore super(options); this.fetchListenerEnv = env || {}; this._networkTimeoutSeconds = options.networkTimeoutSeconds || 10; } override async _handle(request: Request) { if (request.method !== 'GET') { return fetch(request); } // `fetcher` is a custom fetch function that can de defined and passed to the constructor or just regular fetch const fetcher = this.fetchListenerEnv.state!.fetcher || fetch; const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject( new Error( `Network request timed out after ${ this._networkTimeoutSeconds * 1000 } seconds` ) ); }, this._networkTimeoutSeconds * 1000); }); try { for (let plugin of this.plugins) { if (plugin.requestWillFetch) { plugin.requestWillFetch({ request }); } } const fetchPromise: Response = await fetcher(request); const response = (await Promise.race([ fetchPromise, timeoutPromise ])) as Response; if (response) { for (const plugin of this.plugins) { if (plugin.fetchDidSucceed) { await plugin.fetchDidSucceed({ request, response }); } } return response; } // Re-thrown error to be caught by `catch` block throw new Error('Network request failed'); } catch (error) { for (const plugin of this.plugins) { if (plugin.fetchDidFail) { await plugin.fetchDidFail({ request,
error: toError(error) });
} } const headers = { 'X-Remix-Catch': 'yes', 'X-Remix-Worker': 'yes' }; return new Response(JSON.stringify({ message: 'Network Error' }), { status: 500, ...(this.isLoader ? { headers } : {}) }); } } }
src/strategy/networkOnly.ts
remix-pwa-sw-eb66466
[ { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " let response = await fetch(req).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail) {\n plugin.fetchDidFail({\n request: req.clone(),\n error: err\n });\n }\n }\n });", "score": 0.8974723815917969 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " request: updatedRequest\n });\n }\n }\n const fetchPromise = fetcher(updatedRequest).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail)\n plugin.fetchDidFail({\n request: updatedRequest,\n error: err as unknown as Error", "score": 0.8740047812461853 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " )\n );\n }, this._networkTimeoutSeconds * 1000);\n })\n : null;\n const fetcher = this.fetchListenerEnv.state?.fetcher || fetch;\n let updatedRequest = request.clone();\n for (const plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n updatedRequest = await plugin.requestWillFetch({", "score": 0.8599773049354553 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " }\n return null;\n }\n private async getFromNetwork(request: Request): Promise<Response | null> {\n let req: Request = request.clone();\n for (const plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n req = await plugin.requestWillFetch({ request: req });\n }\n }", "score": 0.8542095422744751 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " if (response) {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidSucceed) {\n response = await plugin.fetchDidSucceed({ request: req, response });\n }\n }\n return response;\n }\n return null;\n }", "score": 0.8527846932411194 } ]
typescript
error: toError(error) });
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) {
await this.logoutProcessor.process(request, response);
if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8875850439071655 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 0.8296434283256531 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8231598734855652 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 0.8148099184036255 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.8124002814292908 } ]
typescript
await this.logoutProcessor.process(request, response);
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try {
const user = await this.moduleOptions.authService.checkUser( request.username, );
if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.837352991104126 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8347154855728149 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8256749510765076 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.824505090713501 }, { "filename": "src/dtos/login-request.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}", "score": 0.8201285600662231 } ]
typescript
const user = await this.moduleOptions.authService.checkUser( request.username, );
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); }
const login = await this.loginProcessor.process(user, response);
this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.850884735584259 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8417399525642395 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.8413494825363159 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8353729844093323 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 0.8352304697036743 } ]
typescript
const login = await this.loginProcessor.process(user, response);
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.
id, TokenType.RefreshToken, );
const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 0.9277174472808838 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 0.8632037043571472 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8607803583145142 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport { JwtService } from '@nestjs/jwt';\nimport { Request, Response } from 'express';\nimport { IRefreshTokenJwtPayload } from 'src/interfaces/refresh-token-jwt-payload.interface';\nimport iamConfig from '../configs/iam.config';\nimport { TokenType } from '../enums/token-type.enum';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\n@Injectable()", "score": 0.8499718904495239 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 0.8488085269927979 } ]
typescript
id, TokenType.RefreshToken, );
import { LiteralTypeNode, Project, SourceFile, ts } from 'ts-morph'; import { toCamelCase } from './toCamelCase'; import chalk from 'chalk'; export function getEnumsProperties( project: Project, sourceFile: SourceFile, schema: string ) { const databaseInterface = sourceFile.getInterfaceOrThrow('Database'); const publicProperty = databaseInterface.getPropertyOrThrow(schema); const publicType = publicProperty.getType(); const enumsProperty = publicType .getApparentProperties() .find((property) => property.getName() === 'Enums'); if (!enumsProperty) { console.log( `${chalk.yellow.bold( 'warn' )} No Enums property found within the Database interface for schema ${schema}.` ); return []; } const enumsType = project .getProgram() .getTypeChecker() .getTypeAtLocation(enumsProperty.getValueDeclarationOrThrow()); const enumsProperties = enumsType.getProperties(); if (enumsProperties.length < 1) { console.log( `${chalk.yellow.bold( 'warn' )} No enums found within the Enums property for schema ${schema}.` ); return []; } return enumsProperties; } function getEnumValueLabel(value: LiteralTypeNode) { let enumValue = value.getText().replace(/"/g, ''); if (enumValue.includes(' ')) { enumValue.replace(/ /g, '_'); } if (enumValue.includes('-')) { enumValue.replace(/-/g, '_'); } if (enumValue.includes('.')) { enumValue =
toCamelCase(enumValue, '.');
} return enumValue; } function getEnumValueText(value: LiteralTypeNode) { return value.getText(); } export function getEnumValuesText( enumProperty: ReturnType<typeof getEnumsProperties>[number] ) { const enumValues = enumProperty .getValueDeclarationOrThrow() .getChildrenOfKind(ts.SyntaxKind.UnionType) .flatMap((enumValue) => enumValue.getChildrenOfKind(ts.SyntaxKind.LiteralType) ); return enumValues.map( (value) => ` ${getEnumValueLabel(value)} = ${getEnumValueText(value)},` ); }
src/utils/getEnumsProperties.ts
FroggyPanda-better-supabase-types-4e1b1eb
[ { "filename": "src/generate.ts", "retrieved_chunk": " types.push('// Enums');\n }\n for (const enumProperty of enumsProperties) {\n const enumName = enumProperty.getName();\n const enumNameType = toPascalCase(enumName, makeSingular);\n types.push(\n `export enum ${enumNameType} {`,\n ...(getEnumValuesText(enumProperty) ?? []),\n '}',\n '\\n'", "score": 0.8041635155677795 }, { "filename": "src/utils/toPascalCase.ts", "retrieved_chunk": "import { singular } from 'pluralize';\nconst wordToPascalCase = (makeSingular: boolean) => (word: string) => {\n const singularWord = makeSingular ? singular(word) : word;\n return singularWord.charAt(0).toUpperCase() + singularWord.substring(1);\n}\nexport function toPascalCase(str: string, makeSingular: boolean = false) {\n return str\n .split('_')\n .map(wordToPascalCase(makeSingular))\n .join('');", "score": 0.7711681127548218 }, { "filename": "src/utils/toCamelCase.ts", "retrieved_chunk": "export function toCamelCase(str: string, delimiter: string = '-') {\n const pattern = new RegExp(('\\\\' + delimiter + '([a-z])'), 'g')\n return str.replace(pattern, (match, capture) => capture.toUpperCase())\n}", "score": 0.7668819427490234 }, { "filename": "src/generate.ts", "retrieved_chunk": "import fs from 'fs';\nimport {\n getEnumValuesText,\n getEnumsProperties,\n getFunctionReturnTypes,\n getSchemasProperties,\n getTablesProperties,\n prettierFormat,\n toPascalCase,\n} from './utils';", "score": 0.7602208852767944 }, { "filename": "src/generate.ts", "retrieved_chunk": " sourceFile,\n schemaName\n );\n const enumsProperties = getEnumsProperties(project, sourceFile, schemaName);\n const functionProperties = getFunctionReturnTypes(\n project,\n sourceFile,\n schemaName\n );\n if (enumsProperties.length > 0) {", "score": 0.7555631399154663 } ]
typescript
toCamelCase(enumValue, '.');
import { LiteralTypeNode, Project, SourceFile, ts } from 'ts-morph'; import { toCamelCase } from './toCamelCase'; import chalk from 'chalk'; export function getEnumsProperties( project: Project, sourceFile: SourceFile, schema: string ) { const databaseInterface = sourceFile.getInterfaceOrThrow('Database'); const publicProperty = databaseInterface.getPropertyOrThrow(schema); const publicType = publicProperty.getType(); const enumsProperty = publicType .getApparentProperties() .find((property) => property.getName() === 'Enums'); if (!enumsProperty) { console.log( `${chalk.yellow.bold( 'warn' )} No Enums property found within the Database interface for schema ${schema}.` ); return []; } const enumsType = project .getProgram() .getTypeChecker() .getTypeAtLocation(enumsProperty.getValueDeclarationOrThrow()); const enumsProperties = enumsType.getProperties(); if (enumsProperties.length < 1) { console.log( `${chalk.yellow.bold( 'warn' )} No enums found within the Enums property for schema ${schema}.` ); return []; } return enumsProperties; } function getEnumValueLabel(value: LiteralTypeNode) { let enumValue = value.getText().replace(/"/g, ''); if (enumValue.includes(' ')) { enumValue.replace(/ /g, '_'); } if (enumValue.includes('-')) { enumValue.replace(/-/g, '_'); } if (enumValue.includes('.')) { enumValue
= toCamelCase(enumValue, '.');
} return enumValue; } function getEnumValueText(value: LiteralTypeNode) { return value.getText(); } export function getEnumValuesText( enumProperty: ReturnType<typeof getEnumsProperties>[number] ) { const enumValues = enumProperty .getValueDeclarationOrThrow() .getChildrenOfKind(ts.SyntaxKind.UnionType) .flatMap((enumValue) => enumValue.getChildrenOfKind(ts.SyntaxKind.LiteralType) ); return enumValues.map( (value) => ` ${getEnumValueLabel(value)} = ${getEnumValueText(value)},` ); }
src/utils/getEnumsProperties.ts
FroggyPanda-better-supabase-types-4e1b1eb
[ { "filename": "src/generate.ts", "retrieved_chunk": " types.push('// Enums');\n }\n for (const enumProperty of enumsProperties) {\n const enumName = enumProperty.getName();\n const enumNameType = toPascalCase(enumName, makeSingular);\n types.push(\n `export enum ${enumNameType} {`,\n ...(getEnumValuesText(enumProperty) ?? []),\n '}',\n '\\n'", "score": 0.8085496425628662 }, { "filename": "src/utils/toPascalCase.ts", "retrieved_chunk": "import { singular } from 'pluralize';\nconst wordToPascalCase = (makeSingular: boolean) => (word: string) => {\n const singularWord = makeSingular ? singular(word) : word;\n return singularWord.charAt(0).toUpperCase() + singularWord.substring(1);\n}\nexport function toPascalCase(str: string, makeSingular: boolean = false) {\n return str\n .split('_')\n .map(wordToPascalCase(makeSingular))\n .join('');", "score": 0.7762434482574463 }, { "filename": "src/utils/toCamelCase.ts", "retrieved_chunk": "export function toCamelCase(str: string, delimiter: string = '-') {\n const pattern = new RegExp(('\\\\' + delimiter + '([a-z])'), 'g')\n return str.replace(pattern, (match, capture) => capture.toUpperCase())\n}", "score": 0.7704344391822815 }, { "filename": "src/generate.ts", "retrieved_chunk": "import fs from 'fs';\nimport {\n getEnumValuesText,\n getEnumsProperties,\n getFunctionReturnTypes,\n getSchemasProperties,\n getTablesProperties,\n prettierFormat,\n toPascalCase,\n} from './utils';", "score": 0.7635895609855652 }, { "filename": "src/generate.ts", "retrieved_chunk": " sourceFile,\n schemaName\n );\n const enumsProperties = getEnumsProperties(project, sourceFile, schemaName);\n const functionProperties = getFunctionReturnTypes(\n project,\n sourceFile,\n schemaName\n );\n if (enumsProperties.length > 0) {", "score": 0.7608795166015625 } ]
typescript
= toCamelCase(enumValue, '.');
import defaultStore from './Store'; import produce from 'immer'; import merge from '../utils/merge'; import { logByFunc } from '../log'; import { IStore } from './types'; // TODO add enhancer export function createDefineStore( _store: IStore = defaultStore, enhancer?: (createDefineStore: any) => <S>( name: any, initState: S ) => { getState: () => S; setState: (state: Partial<S> | ((pre: S) => void), currName?: any) => void; regist: (funcs?: {}) => void; store: IStore; setAsyncState: (state: (pre: S) => void) => Promise<S>; name: any; subscribe: any; } ) { console.log('test enhancer.............'); console.log(enhancer); if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error(`Expected the enhancer to be a function`); } return enhancer(createDefineStore); } const store: IStore = _store || defaultStore; return function defineStore<S>(name, initState: S) { function getState(): S { const state = store.getState(); if (typeof state === 'object' && state) { return state[name] as S; } return void 0 as unknown as S; } function setState(state: Partial<S> | ((pre: S) => void)) { const lastState = getState(); //TODO let nextState; if (typeof state === 'function') { nextState = produce(lastState, state as (pre: S) => void); } else { nextState = merge(lastState, state); } if (process.env.NODE_ENV === 'development') { logByFunc(setState, name, lastState, nextState); }
store.setState({
[name]: nextState, }); //TODO } async function setAsyncState(state: (pre: S) => void) { const startStack = new Error().stack; const lastState = getState(); let nextState; nextState = await produce(lastState, state as (pre: S) => void); if (process.env.NODE_ENV === 'development') { logByFunc(startStack, name, lastState, nextState, true); } store.setState({ [name]: nextState, }); } function regist(funcs = {}) { store[name] = merge(store[name], funcs); } function init() { const currentState = getState(); if (!currentState) { setState(initState); } } init(); return { getState, setState, regist, store, setAsyncState, subscribe: store.subscribe, }; }; } export default createDefineStore();
src/store/defineStore.ts
hongyin163-silver-store-8ffcb94
[ { "filename": "src/store/StoreBase.ts", "retrieved_chunk": " const lastState = this.getState();\n let nextState;\n if (typeof state === \"function\") {\n nextState = produce(lastState, state as (pre: S) => void);\n } else {\n nextState = merge(lastState, state);\n }\n if (process.env.NODE_ENV === \"development\") {\n logByFunc(this.setState, this.name, lastState, nextState);\n }", "score": 0.9722706079483032 }, { "filename": "src/store/StoreBase.ts", "retrieved_chunk": " setState = (state: S | ((pre: S) => void)) => {\n const lastState = this.getState();\n let nextState;\n if (typeof state === \"function\") {\n nextState = produce(lastState, state as (pre: S) => void);\n } else {\n nextState = merge(lastState, state);\n }\n if (process.env.NODE_ENV === \"development\") {\n logByFunc(this.setState, this.name, lastState, nextState);", "score": 0.9557921886444092 }, { "filename": "src/store/StoreBase.ts", "retrieved_chunk": " const currentState = this.getState();\n if (!currentState) {\n if (typeof initState === \"function\") {\n this.setState(initState());\n } else {\n this.setState(initState);\n }\n }\n };\n setState = (state: S | ((pre: S) => void)) => {", "score": 0.8667356967926025 }, { "filename": "src/store/StoreBase.ts", "retrieved_chunk": " this.store.setState({\n [this.name]: nextState,\n } as any);\n };\n}", "score": 0.8596518039703369 }, { "filename": "src/store/StoreBase.ts", "retrieved_chunk": " }\n this.store.setState({\n [this.name]: nextState,\n } as any);\n };\n };\n}\nexport default createStoreBase();\nexport class StoreBase<S> {\n name: string = \"\";", "score": 0.8457362651824951 } ]
typescript
store.setState({
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; }
this.eventBus.publish(new LoggedOutEvent(activeUser.userId));
} }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 0.8868089318275452 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8313112258911133 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 0.8275125026702881 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 0.8252312541007996 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 0.824351966381073 } ]
typescript
this.eventBus.publish(new LoggedOutEvent(activeUser.userId));
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); }
const requestId = request.cookies[TokenType.PasswordlessLoginToken];
if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 0.8660382032394409 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 0.8385111093521118 }, { "filename": "src/dtos/passwordless-login-request-request.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class PasswordlessLoginRequestRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n}", "score": 0.816015362739563 }, { "filename": "src/generators/passwordless-login-token.generator.ts", "retrieved_chunk": " constructor(\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n async generate(user: IUser, requestId: string): Promise<IToken> {\n const id = randomUUID();\n const ttl = this.config.auth.passwordless.tokenTtl;\n const expiresAt = new Date();\n expiresAt.setSeconds(expiresAt.getSeconds() + ttl);\n return new TokenModel(", "score": 0.8146933913230896 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 0.8080816268920898 } ]
typescript
const requestId = request.cookies[TokenType.PasswordlessLoginToken];
import type {OperatorKey} from '../core/operators'; import type {Signal, SignalSet} from '../signals'; import type Rule from './rule'; import {assertArray, assertString} from '../core/assert'; import {operator} from '../core/operators'; import GroupRule from './group'; import InverseRule from './inverse'; import SignalRule from './signal'; function assertObjectWithSingleKey( data: unknown, ): asserts data is {[key: string]: unknown} { if (data == null || typeof data !== 'object') { throw new Error('Expected an object, got: ' + data); } if (Object.keys(data).length !== 1) { throw new Error('Expected an object with a single key, got: ' + data); } } function assertOperatorKey(data: unknown): asserts data is OperatorKey { if (!Object.keys(operator).includes(assertString(data))) { throw new Error('Expected an operator key, got: ' + data); } } export default async function parse<TContext>( data: unknown, signals: SignalSet<TContext>, ): Promise<Rule<TContext>> { assertObjectWithSingleKey(data); const key = Object.keys(data)[0]; const value = data[key]; switch (key) { case '$and': case '$or': return new GroupRule<TContext>( operator[key], await Promise.all( assertArray(value).map(element => parse(element, signals)), ), ); case '$not': return new InverseRule(await parse(value, signals)); } const signal = signals[key]; assertObjectWithSingleKey(value); const operatorKey = Object.keys(value)[0]; assertOperatorKey(operatorKey); const operatorValue = value[operatorKey];
const arraySignal = signal as Signal<TContext, Array<unknown>>;
const numberSignal = signal as Signal<TContext, number>; const stringSignal = signal as Signal<TContext, string>; switch (operatorKey) { case '$and': case '$or': return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>( operator[operatorKey], signal as Signal<TContext, Array<TContext>>, [await parse(operatorValue, signals)], ); case '$not': throw new Error('Invalid operator key: ' + operatorKey); case '$all': case '$any': return new SignalRule( operator[operatorKey], arraySignal, await arraySignal.__assert(operatorValue), ); case '$inc': case '$pfx': case '$sfx': return new SignalRule( operator[operatorKey], stringSignal, await stringSignal.__assert(operatorValue), ); case '$rx': const match = (await stringSignal.__assert(operatorValue)).match( new RegExp('^/(.*?)/([dgimsuy]*)$'), ); if (match == null) { throw new Error('Expected a regular expression, got: ' + operatorValue); } return new SignalRule( operator[operatorKey], signal, new RegExp(match[1], match[2]), ); case '$gt': case '$gte': case '$lt': case '$lte': return new SignalRule( operator[operatorKey], numberSignal, await numberSignal.__assert(operatorValue), ); case '$eq': return new SignalRule(operator[operatorKey], signal, operatorValue); case '$in': return new SignalRule( operator[operatorKey], signal, assertArray(operatorValue), ); } }
src/rules/parse.ts
decs-ruls-c037c91
[ { "filename": "src/rules/inverse.ts", "retrieved_chunk": "import type {SignalSet} from '../signals';\nimport type {EncodedRule} from './rule';\nimport {operator} from '../core/operators';\nimport Rule from './rule';\nexport type EncodedInverseRule<TContext> = {\n $not: EncodedRule<TContext>;\n};\nexport default class InverseRule<TContext> extends Rule<TContext> {\n constructor(protected rule: Rule<TContext>) {\n super(async context => operator.$not(await rule.evaluate(context)));", "score": 0.8783795833587646 }, { "filename": "src/rules/inverse.ts", "retrieved_chunk": " }\n encode(signals: SignalSet<TContext>): EncodedInverseRule<TContext> {\n return {$not: this.rule.encode(signals)};\n }\n}", "score": 0.8687150478363037 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": "import type Rule from '../rules/rule';\nimport type {Infer, Schema} from '@decs/typeschema';\nimport {createAssert} from '@decs/typeschema';\nimport {operator} from '../core/operators';\nimport InverseRule from '../rules/inverse';\nimport SignalRule from '../rules/signal';\nexport type Signal<TContext, TValue> = {\n __assert: (data: unknown) => Promise<TValue>;\n evaluate: (context: TContext) => Promise<TValue>;\n not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>;", "score": 0.8609909415245056 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " in: values => new SignalRule(operator.$in, signal, values),\n };\n}\nfunction addArrayOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>;\n return {\n ...signal,\n contains: value => new SignalRule(operator.$all, arraySignal, [value]),", "score": 0.8489291667938232 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " return {\n ...signal,\n greaterThan: value => new SignalRule(operator.$gt, numberSignal, value),\n greaterThanOrEquals: value =>\n new SignalRule(operator.$gte, numberSignal, value),\n lessThan: value => new SignalRule(operator.$lt, numberSignal, value),\n lessThanOrEquals: value =>\n new SignalRule(operator.$lte, numberSignal, value),\n };\n}", "score": 0.8460390567779541 } ]
typescript
const arraySignal = signal as Signal<TContext, Array<unknown>>;
import {describe, expect, test} from '@jest/globals'; import {z} from 'zod'; import {rule} from '../rules'; import {signal} from '../signals'; describe('json-rules-engine', () => { test('basic example', async () => { type Context = { gameDuration: number; personalFouls: number; }; const signals = { gameDuration: signal .type(z.number()) .value<Context>(({gameDuration}) => gameDuration), personalFouls: signal .type(z.number()) .value<Context>(({personalFouls}) => personalFouls), }; const fouledOut = rule.some([ rule.every([ signals.gameDuration.equals(40), signals.personalFouls.greaterThanOrEquals(5), ]), rule.every([ signals.gameDuration.equals(48), signals.personalFouls.greaterThanOrEquals(6), ]), ]); expect( await fouledOut.evaluate({gameDuration: 40, personalFouls: 6}), ).toBeTruthy(); expect( await fouledOut.evaluate({gameDuration: 48, personalFouls: 5}), ).toBeFalsy(); }); test('advanced example', async () => { type Context = { company: string; status: string; ptoDaysTaken: Array<string>; }; const signals = { company: signal.type(z.string()).value<Context>(({company}) => company), ptoDaysTaken: signal .type(z.array(z.string())) .value<Context>(({ptoDaysTaken}) => ptoDaysTaken),
status: signal.type(z.string()).value<Context>(({status}) => status), };
const microsoftEmployeeOutOnChristmas = rule.every([ signals.company.equals('microsoft'), signals.status.in(['active', 'paid-leave']), signals.ptoDaysTaken.contains('2016-12-25'), ]); const accountInformation = { company: 'microsoft', ptoDaysTaken: ['2016-12-24', '2016-12-25'], status: 'active', }; expect( await microsoftEmployeeOutOnChristmas.evaluate(accountInformation), ).toBeTruthy(); accountInformation.company = 'apple'; expect( await microsoftEmployeeOutOnChristmas.evaluate(accountInformation), ).toBeFalsy(); }); });
src/__tests__/comparison.test.ts
decs-ruls-c037c91
[ { "filename": "src/__tests__/main.test.ts", "retrieved_chunk": " sampleArray: signal\n .type(z.array(z.number()))\n .value<Context>(({id}) => [id]),\n sampleBoolean: signal.type(z.boolean()).value<Context>(({id}) => id > 0),\n sampleNumber: signal.type(z.number()).value<Context>(({id}) => 2 * id),\n sampleString: signal.type(z.string()).value<Context>(({id}) => `id=${id}`),\n };\n test('evaluate', async () => {\n expect(await signals.sampleArray.evaluate({id: 123})).toEqual([123]);\n expect(await signals.sampleBoolean.evaluate({id: 123})).toEqual(true);", "score": 0.8507097959518433 }, { "filename": "src/__tests__/main.test.ts", "retrieved_chunk": "import {describe, expect, test} from '@jest/globals';\nimport {z} from 'zod';\nimport {rule} from '../rules';\nimport Rule from '../rules/rule';\nimport {signal} from '../signals';\ntype Context = {\n id: number;\n};\ndescribe('ruls', () => {\n const signals = {", "score": 0.8436628580093384 }, { "filename": "src/rules/group.ts", "retrieved_chunk": " rule.encode(signals),\n ),\n };\n }\n}", "score": 0.8204503059387207 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " return {\n ...signal,\n greaterThan: value => new SignalRule(operator.$gt, numberSignal, value),\n greaterThanOrEquals: value =>\n new SignalRule(operator.$gte, numberSignal, value),\n lessThan: value => new SignalRule(operator.$lt, numberSignal, value),\n lessThanOrEquals: value =>\n new SignalRule(operator.$lte, numberSignal, value),\n };\n}", "score": 0.8196054100990295 }, { "filename": "src/__tests__/async.test.ts", "retrieved_chunk": " return {name: `record_${id}`};\n}\ndescribe('ruls', () => {\n const signals = {\n name: signal\n .type(z.string())\n .value<Context>(async ({id}) => (await fetchRecord(id)).name),\n };\n test('evaluate', async () => {\n expect(await signals.name.evaluate({id: 123})).toEqual('record_123');", "score": 0.8137773871421814 } ]
typescript
status: signal.type(z.string()).value<Context>(({status}) => status), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new
InverseRule(value.bind(target)(...args)) : value;
}, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 0.8679906725883484 }, { "filename": "src/rules/inverse.ts", "retrieved_chunk": "import type {SignalSet} from '../signals';\nimport type {EncodedRule} from './rule';\nimport {operator} from '../core/operators';\nimport Rule from './rule';\nexport type EncodedInverseRule<TContext> = {\n $not: EncodedRule<TContext>;\n};\nexport default class InverseRule<TContext> extends Rule<TContext> {\n constructor(protected rule: Rule<TContext>) {\n super(async context => operator.$not(await rule.evaluate(context)));", "score": 0.8568441867828369 }, { "filename": "src/rules/inverse.ts", "retrieved_chunk": " }\n encode(signals: SignalSet<TContext>): EncodedInverseRule<TContext> {\n return {$not: this.rule.encode(signals)};\n }\n}", "score": 0.8501413464546204 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 0.811771035194397 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new SignalRule(\n operator[operatorKey],\n stringSignal,\n await stringSignal.__assert(operatorValue),\n );\n case '$rx':\n const match = (await stringSignal.__assert(operatorValue)).match(\n new RegExp('^/(.*?)/([dgimsuy]*)$'),\n );\n if (match == null) {", "score": 0.806067943572998 } ]
typescript
InverseRule(value.bind(target)(...args)) : value;
import type {OperatorKey} from '../core/operators'; import type {Signal, SignalSet} from '../signals'; import type Rule from './rule'; import {assertArray, assertString} from '../core/assert'; import {operator} from '../core/operators'; import GroupRule from './group'; import InverseRule from './inverse'; import SignalRule from './signal'; function assertObjectWithSingleKey( data: unknown, ): asserts data is {[key: string]: unknown} { if (data == null || typeof data !== 'object') { throw new Error('Expected an object, got: ' + data); } if (Object.keys(data).length !== 1) { throw new Error('Expected an object with a single key, got: ' + data); } } function assertOperatorKey(data: unknown): asserts data is OperatorKey { if (!Object.keys(operator).includes(assertString(data))) { throw new Error('Expected an operator key, got: ' + data); } } export default async function parse<TContext>( data: unknown, signals: SignalSet<TContext>, ): Promise<Rule<TContext>> { assertObjectWithSingleKey(data); const key = Object.keys(data)[0]; const value = data[key]; switch (key) { case '$and': case '$or': return new GroupRule<TContext>( operator[key], await Promise.all( assertArray(value).map(element => parse(element, signals)), ), ); case '$not':
return new InverseRule(await parse(value, signals));
} const signal = signals[key]; assertObjectWithSingleKey(value); const operatorKey = Object.keys(value)[0]; assertOperatorKey(operatorKey); const operatorValue = value[operatorKey]; const arraySignal = signal as Signal<TContext, Array<unknown>>; const numberSignal = signal as Signal<TContext, number>; const stringSignal = signal as Signal<TContext, string>; switch (operatorKey) { case '$and': case '$or': return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>( operator[operatorKey], signal as Signal<TContext, Array<TContext>>, [await parse(operatorValue, signals)], ); case '$not': throw new Error('Invalid operator key: ' + operatorKey); case '$all': case '$any': return new SignalRule( operator[operatorKey], arraySignal, await arraySignal.__assert(operatorValue), ); case '$inc': case '$pfx': case '$sfx': return new SignalRule( operator[operatorKey], stringSignal, await stringSignal.__assert(operatorValue), ); case '$rx': const match = (await stringSignal.__assert(operatorValue)).match( new RegExp('^/(.*?)/([dgimsuy]*)$'), ); if (match == null) { throw new Error('Expected a regular expression, got: ' + operatorValue); } return new SignalRule( operator[operatorKey], signal, new RegExp(match[1], match[2]), ); case '$gt': case '$gte': case '$lt': case '$lte': return new SignalRule( operator[operatorKey], numberSignal, await numberSignal.__assert(operatorValue), ); case '$eq': return new SignalRule(operator[operatorKey], signal, operatorValue); case '$in': return new SignalRule( operator[operatorKey], signal, assertArray(operatorValue), ); } }
src/rules/parse.ts
decs-ruls-c037c91
[ { "filename": "src/rules/index.ts", "retrieved_chunk": " none<TContext>(rules: Array<Rule<TContext>>): Rule<TContext> {\n return new InverseRule(new GroupRule(operator.$or, rules));\n },\n parse,\n some<TContext>(rules: Array<Rule<TContext>>): Rule<TContext> {\n return new GroupRule(operator.$or, rules);\n },\n};", "score": 0.8732747435569763 }, { "filename": "src/rules/index.ts", "retrieved_chunk": "import type Rule from './rule';\nimport {operator} from '../core/operators';\nimport GroupRule from './group';\nimport InverseRule from './inverse';\nimport parse from './parse';\nexport type {default as Rule} from './rule';\nexport const rule = {\n every<TContext>(rules: Array<Rule<TContext>>): Rule<TContext> {\n return new GroupRule(operator.$and, rules);\n },", "score": 0.8517405390739441 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": "import type Rule from '../rules/rule';\nimport type {Infer, Schema} from '@decs/typeschema';\nimport {createAssert} from '@decs/typeschema';\nimport {operator} from '../core/operators';\nimport InverseRule from '../rules/inverse';\nimport SignalRule from '../rules/signal';\nexport type Signal<TContext, TValue> = {\n __assert: (data: unknown) => Promise<TValue>;\n evaluate: (context: TContext) => Promise<TValue>;\n not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>;", "score": 0.8490707874298096 }, { "filename": "src/rules/inverse.ts", "retrieved_chunk": "import type {SignalSet} from '../signals';\nimport type {EncodedRule} from './rule';\nimport {operator} from '../core/operators';\nimport Rule from './rule';\nexport type EncodedInverseRule<TContext> = {\n $not: EncodedRule<TContext>;\n};\nexport default class InverseRule<TContext> extends Rule<TContext> {\n constructor(protected rule: Rule<TContext>) {\n super(async context => operator.$not(await rule.evaluate(context)));", "score": 0.8438698053359985 }, { "filename": "src/rules/group.ts", "retrieved_chunk": " context: Array<TContext>,\n rules: Array<Rule<TContext>>,\n ) => Promise<boolean>,\n protected rules: Array<Rule<TContext>>,\n ) {\n super(context => operator([context], rules));\n }\n encode(signals: SignalSet<TContext>): EncodedGroupRule<TContext> {\n return {\n [getOperatorKey(this.operator)]: this.rules.map(rule =>", "score": 0.8419145941734314 } ]
typescript
return new InverseRule(await parse(value, signals));
import type {OperatorKey} from '../core/operators'; import type {Signal, SignalSet} from '../signals'; import type Rule from './rule'; import {assertArray, assertString} from '../core/assert'; import {operator} from '../core/operators'; import GroupRule from './group'; import InverseRule from './inverse'; import SignalRule from './signal'; function assertObjectWithSingleKey( data: unknown, ): asserts data is {[key: string]: unknown} { if (data == null || typeof data !== 'object') { throw new Error('Expected an object, got: ' + data); } if (Object.keys(data).length !== 1) { throw new Error('Expected an object with a single key, got: ' + data); } } function assertOperatorKey(data: unknown): asserts data is OperatorKey { if (!Object.keys(operator).includes(assertString(data))) { throw new Error('Expected an operator key, got: ' + data); } } export default async function parse<TContext>( data: unknown, signals: SignalSet<TContext>, ): Promise<Rule<TContext>> { assertObjectWithSingleKey(data); const key = Object.keys(data)[0]; const value = data[key]; switch (key) { case '$and': case '$or': return new GroupRule<TContext>( operator[key], await Promise.all( assertArray(value).map(element => parse(element, signals)), ), ); case '$not': return new InverseRule(await parse(value, signals)); } const signal = signals[key]; assertObjectWithSingleKey(value); const operatorKey = Object.keys(value)[0]; assertOperatorKey(operatorKey); const operatorValue = value[operatorKey]; const arraySignal = signal as Signal<TContext, Array<unknown>>; const numberSignal = signal as Signal<TContext, number>; const stringSignal = signal as Signal<TContext, string>; switch (operatorKey) { case '$and': case '$or': return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>( operator[operatorKey], signal as Signal<TContext, Array<TContext>>, [await parse(operatorValue, signals)], ); case '$not': throw new Error('Invalid operator key: ' + operatorKey); case '$all': case '$any': return new SignalRule( operator[operatorKey], arraySignal, await arraySignal.__assert(operatorValue), ); case '$inc': case '$pfx': case '$sfx': return new SignalRule( operator[operatorKey], stringSignal, await stringSignal.__assert(operatorValue), ); case '$rx': const match = (await stringSignal.__assert(operatorValue)).match( new RegExp('^/(.*?)/([dgimsuy]*)$'), ); if (match == null) { throw new Error('Expected a regular expression, got: ' + operatorValue); } return new SignalRule( operator[operatorKey], signal, new RegExp(match[1], match[2]), ); case '$gt': case '$gte': case '$lt': case '$lte': return new SignalRule( operator[operatorKey], numberSignal, await numberSignal.__assert(operatorValue), ); case '$eq':
return new SignalRule(operator[operatorKey], signal, operatorValue);
case '$in': return new SignalRule( operator[operatorKey], signal, assertArray(operatorValue), ); } }
src/rules/parse.ts
decs-ruls-c037c91
[ { "filename": "src/signals/factory.ts", "retrieved_chunk": " return {\n ...signal,\n greaterThan: value => new SignalRule(operator.$gt, numberSignal, value),\n greaterThanOrEquals: value =>\n new SignalRule(operator.$gte, numberSignal, value),\n lessThan: value => new SignalRule(operator.$lt, numberSignal, value),\n lessThanOrEquals: value =>\n new SignalRule(operator.$lte, numberSignal, value),\n };\n}", "score": 0.9077638387680054 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " return {\n ...signal,\n isFalse: () => new SignalRule(operator.$eq, booleanSignal, false),\n isTrue: () => new SignalRule(operator.$eq, booleanSignal, true),\n };\n}\nfunction addNumberOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n const numberSignal = signal as unknown as Signal<TContext, number>;", "score": 0.8585055470466614 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " __assert: assert,\n evaluate: async (context: TContext) => assert(await fn(context)),\n } as Signal<TContext, TValue>;\n}\nfunction addOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n return {\n ...signal,\n equals: value => new SignalRule(operator.$eq, signal, value),", "score": 0.8444558382034302 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " containsEvery: values => new SignalRule(operator.$all, arraySignal, values),\n containsSome: values => new SignalRule(operator.$any, arraySignal, values),\n every: rule => new SignalRule(operator.$and, arraySignal, [rule]),\n some: rule => new SignalRule(operator.$or, arraySignal, [rule]),\n };\n}\nfunction addBooleanOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n const booleanSignal = signal as unknown as Signal<TContext, boolean>;", "score": 0.8365105986595154 }, { "filename": "src/__tests__/main.test.ts", "retrieved_chunk": " expect(await signals.sampleNumber.evaluate({id: 123})).toEqual(246);\n expect(await signals.sampleString.evaluate({id: 123})).toEqual('id=123');\n });\n test('rules', async () => {\n const check = rule.every([\n signals.sampleString.matches(/3$/g),\n signals.sampleArray.not.contains(246),\n ]);\n expect(check).toBeInstanceOf(Rule);\n const encodedCheck = check.encode(signals);", "score": 0.8335520029067993 } ]
typescript
return new SignalRule(operator[operatorKey], signal, operatorValue);
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new
SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), };
} function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 0.8727484941482544 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 0.8627063035964966 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$lte':\n return new SignalRule(\n operator[operatorKey],\n numberSignal,\n await numberSignal.__assert(operatorValue),\n );\n case '$eq':\n return new SignalRule(operator[operatorKey], signal, operatorValue);\n case '$in':\n return new SignalRule(", "score": 0.8564092516899109 }, { "filename": "src/rules/group.ts", "retrieved_chunk": " context: Array<TContext>,\n rules: Array<Rule<TContext>>,\n ) => Promise<boolean>,\n protected rules: Array<Rule<TContext>>,\n ) {\n super(context => operator([context], rules));\n }\n encode(signals: SignalSet<TContext>): EncodedGroupRule<TContext> {\n return {\n [getOperatorKey(this.operator)]: this.rules.map(rule =>", "score": 0.8539472222328186 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$all':\n case '$any':\n return new SignalRule(\n operator[operatorKey],\n arraySignal,\n await arraySignal.__assert(operatorValue),\n );\n case '$inc':\n case '$pfx':\n case '$sfx':", "score": 0.8429408073425293 } ]
typescript
SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule
(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), };
} function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 0.873284637928009 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 0.8638119101524353 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$lte':\n return new SignalRule(\n operator[operatorKey],\n numberSignal,\n await numberSignal.__assert(operatorValue),\n );\n case '$eq':\n return new SignalRule(operator[operatorKey], signal, operatorValue);\n case '$in':\n return new SignalRule(", "score": 0.8577526211738586 }, { "filename": "src/rules/group.ts", "retrieved_chunk": " context: Array<TContext>,\n rules: Array<Rule<TContext>>,\n ) => Promise<boolean>,\n protected rules: Array<Rule<TContext>>,\n ) {\n super(context => operator([context], rules));\n }\n encode(signals: SignalSet<TContext>): EncodedGroupRule<TContext> {\n return {\n [getOperatorKey(this.operator)]: this.rules.map(rule =>", "score": 0.8563172817230225 }, { "filename": "src/rules/signal.ts", "retrieved_chunk": " super(async context => operator(await first.evaluate(context), second));\n }\n encode(signals: SignalSet<TContext>): EncodedSignalRule {\n return {\n [getSignalKey(this.first, signals)]: {\n [getOperatorKey(this.operator)]:\n this.second instanceof Rule\n ? this.second.encode(signals)\n : this.second instanceof RegExp\n ? this.second.toString()", "score": 0.8443213701248169 } ]
typescript
(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]),
some: rule => new SignalRule(operator.$or, arraySignal, [rule]), };
} function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 0.8848313093185425 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 0.8822419047355652 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$all':\n case '$any':\n return new SignalRule(\n operator[operatorKey],\n arraySignal,\n await arraySignal.__assert(operatorValue),\n );\n case '$inc':\n case '$pfx':\n case '$sfx':", "score": 0.8595755696296692 }, { "filename": "src/rules/group.ts", "retrieved_chunk": " context: Array<TContext>,\n rules: Array<Rule<TContext>>,\n ) => Promise<boolean>,\n protected rules: Array<Rule<TContext>>,\n ) {\n super(context => operator([context], rules));\n }\n encode(signals: SignalSet<TContext>): EncodedGroupRule<TContext> {\n return {\n [getOperatorKey(this.operator)]: this.rules.map(rule =>", "score": 0.851125180721283 }, { "filename": "src/rules/signal.ts", "retrieved_chunk": "import type {Signal, SignalSet} from '../signals';\nimport {getOperatorKey} from '../core/operators';\nimport {getSignalKey} from '../signals/set';\nimport Rule from './rule';\nexport type EncodedSignalRule = {\n [signal: string]: {[operator: string]: unknown};\n};\nexport default class SignalRule<\n TContext,\n TFirst,", "score": 0.849960446357727 } ]
typescript
some: rule => new SignalRule(operator.$or, arraySignal, [rule]), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule
(operator.$pfx, stringSignal, value), };
} function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 0.8804630041122437 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new SignalRule(\n operator[operatorKey],\n stringSignal,\n await stringSignal.__assert(operatorValue),\n );\n case '$rx':\n const match = (await stringSignal.__assert(operatorValue)).match(\n new RegExp('^/(.*?)/([dgimsuy]*)$'),\n );\n if (match == null) {", "score": 0.8753975033760071 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 0.8714531064033508 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " throw new Error('Expected a regular expression, got: ' + operatorValue);\n }\n return new SignalRule(\n operator[operatorKey],\n signal,\n new RegExp(match[1], match[2]),\n );\n case '$gt':\n case '$gte':\n case '$lt':", "score": 0.8589953184127808 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$all':\n case '$any':\n return new SignalRule(\n operator[operatorKey],\n arraySignal,\n await arraySignal.__assert(operatorValue),\n );\n case '$inc':\n case '$pfx':\n case '$sfx':", "score": 0.8547900319099426 } ]
typescript
(operator.$pfx, stringSignal, value), };
import* as fs from 'fs'; import error from '../modules/log.js'; import { Runner, Test, Out } from '../modules/types.js'; function parseOut(test: any): Out { let expected: Out = { stdout: undefined, stderr: undefined, exitCode: undefined } if (test.stdout) expected.stdout = test.stdout; if (test.stderr) expected.stderr = test.stderr; if (test.exitCode !== undefined) expected.exitCode = test.exitCode; return expected; } export default async function parse(runner: Runner, doc: any): Promise<Runner> { const tests: Test[] = []; try { let testId = 0; for (const test of doc.Tests) { testId++; const testObj: Test = { id: testId, name: test.name, description: test.description, command: test.command, testType: test.testType, referCommand: undefined, expected: undefined, result: undefined }; if (test.testType === 'refer') testObj.referCommand = test.referCommand; else if (test.testType === "expect") testObj.expected = parseOut(test.expected); else throw new Error(`Invalid testType or comparsionType in test ${testObj.id}`); tests.push(testObj); } } catch(e) { error(`Error parsing: ${e}`); }
runner.tests = tests;
return runner; }
src/fileParsing/parse.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/runTests.ts", "retrieved_chunk": " }\n if (runner.settings.outputFormat == 'text')\n console.log(\"Starting Tests...\\n\");\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) {\n test.result = {\n status: 'pending',\n msg: 'In the queue',\n result: {\n stdout: undefined,", "score": 0.8327679634094238 }, { "filename": "src/runTests.ts", "retrieved_chunk": " if (runner.settings.verbose) {\n print_test_description(test);\n } else if (runner.settings.outputFormat == 'text') \n process.stdout.write(`Test ${test.id}: ${test.name}... \\t`);\n if (test.testType === 'refer')\n await runRefer(runner, test);\n else if (test.testType === 'expect')\n await runExpect(runner, test);\n if (runner.settings.verbose)\n console.log('\\n');", "score": 0.827898383140564 }, { "filename": "src/runTests.ts", "retrieved_chunk": " stdout: undefined,\n stderr: undefined,\n exitCode: undefined\n },\n timeTaken: undefined\n };\n }\n }\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) {", "score": 0.8265736103057861 }, { "filename": "src/runTests.ts", "retrieved_chunk": " console.log(`Test ${test.id}: ${test.name}`);\n console.log(`Test Command: $${test.command}`);\n console.log(`Test type: [${test.testType}]`);\n if (test.testType === 'refer')\n console.log(`Refer Command: $${test.referCommand}`);\n else {\n print_expected(test.expected);\n }\n}\nasync function runTest(runner: Runner, test: Test): Promise<void> {", "score": 0.8262075781822205 }, { "filename": "src/runner/expect.ts", "retrieved_chunk": " },\n timeTaken: endTime - startTime\n };\n if (test.result.timeTaken > runner.settings.timeout && runner.settings.timeout !== 0) {\n return jobError(runner, test, `Test timed out after ${test.result.timeTaken}ms`);\n }\n if (!compareStatus(run.status, test)) {\n return jobError(runner, test, `Expected exit code ${test.expected.exitCode} but got ${run.status}`);\n }\n if (!compareStdout(run.stdout.toString(), test)) {", "score": 0.8249484300613403 } ]
typescript
runner.tests = tests;
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator
.$lte, numberSignal, value), };
} function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$lte':\n return new SignalRule(\n operator[operatorKey],\n numberSignal,\n await numberSignal.__assert(operatorValue),\n );\n case '$eq':\n return new SignalRule(operator[operatorKey], signal, operatorValue);\n case '$in':\n return new SignalRule(", "score": 0.8874383568763733 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " throw new Error('Expected a regular expression, got: ' + operatorValue);\n }\n return new SignalRule(\n operator[operatorKey],\n signal,\n new RegExp(match[1], match[2]),\n );\n case '$gt':\n case '$gte':\n case '$lt':", "score": 0.8806225061416626 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 0.8726921081542969 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 0.8656994700431824 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new SignalRule(\n operator[operatorKey],\n stringSignal,\n await stringSignal.__assert(operatorValue),\n );\n case '$rx':\n const match = (await stringSignal.__assert(operatorValue)).match(\n new RegExp('^/(.*?)/([dgimsuy]*)$'),\n );\n if (match == null) {", "score": 0.8643025755882263 } ]
typescript
.$lte, numberSignal, value), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule
(value.bind(target)(...args)) : value;
}, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 0.873093843460083 }, { "filename": "src/rules/inverse.ts", "retrieved_chunk": "import type {SignalSet} from '../signals';\nimport type {EncodedRule} from './rule';\nimport {operator} from '../core/operators';\nimport Rule from './rule';\nexport type EncodedInverseRule<TContext> = {\n $not: EncodedRule<TContext>;\n};\nexport default class InverseRule<TContext> extends Rule<TContext> {\n constructor(protected rule: Rule<TContext>) {\n super(async context => operator.$not(await rule.evaluate(context)));", "score": 0.8641252517700195 }, { "filename": "src/rules/inverse.ts", "retrieved_chunk": " }\n encode(signals: SignalSet<TContext>): EncodedInverseRule<TContext> {\n return {$not: this.rule.encode(signals)};\n }\n}", "score": 0.8555927276611328 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 0.8140085339546204 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new SignalRule(\n operator[operatorKey],\n stringSignal,\n await stringSignal.__assert(operatorValue),\n );\n case '$rx':\n const match = (await stringSignal.__assert(operatorValue)).match(\n new RegExp('^/(.*?)/([dgimsuy]*)$'),\n );\n if (match == null) {", "score": 0.8083333373069763 } ]
typescript
(value.bind(target)(...args)) : value;
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new
SignalRule(operator.$in, signal, values), };
} function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 0.8726041913032532 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 0.862533688545227 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$lte':\n return new SignalRule(\n operator[operatorKey],\n numberSignal,\n await numberSignal.__assert(operatorValue),\n );\n case '$eq':\n return new SignalRule(operator[operatorKey], signal, operatorValue);\n case '$in':\n return new SignalRule(", "score": 0.8587836027145386 }, { "filename": "src/rules/group.ts", "retrieved_chunk": " context: Array<TContext>,\n rules: Array<Rule<TContext>>,\n ) => Promise<boolean>,\n protected rules: Array<Rule<TContext>>,\n ) {\n super(context => operator([context], rules));\n }\n encode(signals: SignalSet<TContext>): EncodedGroupRule<TContext> {\n return {\n [getOperatorKey(this.operator)]: this.rules.map(rule =>", "score": 0.8535871505737305 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$all':\n case '$any':\n return new SignalRule(\n operator[operatorKey],\n arraySignal,\n await arraySignal.__assert(operatorValue),\n );\n case '$inc':\n case '$pfx':\n case '$sfx':", "score": 0.8430296778678894 } ]
typescript
SignalRule(operator.$in, signal, values), };
import { Runner, Test, Out } from './modules/types.js'; import runRefer from './runner/refer.js'; import runExpect from './runner/expect.js'; import yaml from 'js-yaml'; import createOutput from './output.js'; function print_expected(out: Out): void { if (out.stdout !== undefined) if (out.stdout.string !== undefined) console.log(`Expected stdout: "${out.stdout.string}"`); else if (out.stdout.regex !== undefined) console.log(`stdout must match: /${out.stdout.regex}/`); if (out.stderr !== undefined) if (out.stderr.string !== undefined) console.log(`Expected stderr: "${out.stderr.string}"`); else if (out.stderr.regex !== undefined) console.log(`stderr must match: /${out.stderr.regex}/`); if (out.exitCode !== undefined) console.log(`Expected exit code: ${out.exitCode}`); } function print_test_description(test: Test): void { console.log(`Test ${test.id}: ${test.name}`); console.log(`Test Command: $${test.command}`); console.log(`Test type: [${test.testType}]`); if (test.testType === 'refer') console.log(`Refer Command: $${test.referCommand}`); else { print_expected(test.expected); } } async function runTest(runner: Runner, test: Test): Promise<void> { if (runner.settings.verbose) { print_test_description(test); } else if (runner.settings.outputFormat == 'text') process.stdout.write(`Test ${test.id}: ${test.name}... \t`); if (test.testType === 'refer') await runRefer(runner, test); else if (test.testType === 'expect') await runExpect(runner, test); if (runner.settings.verbose) console.log('\n'); } export default async function runTests(runner: Runner): Promise<void> { if (runner.settings.verbose) {
console.log(`Starting Tests for ${runner.testFilePath}...`);
console.log(`Settings: \n${yaml.dump(runner.settings)}`); console.log("Test Queue:"); for (const test of runner.tests) { if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) console.log(`Test ${test.id}: ${test.name}`); } } if (runner.settings.outputFormat == 'text') console.log("Starting Tests...\n"); for (const test of runner.tests) { if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) { test.result = { status: 'pending', msg: 'In the queue', result: { stdout: undefined, stderr: undefined, exitCode: undefined }, timeTaken: undefined }; } else { test.result = { status: 'skipped', msg: 'Skipped by user', result: { stdout: undefined, stderr: undefined, exitCode: undefined }, timeTaken: undefined }; } } for (const test of runner.tests) { if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) { test.result = { status: 'pending', msg: 'In the queue', result: { stdout: undefined, stderr: undefined, exitCode: undefined }, timeTaken: undefined }; await runTest(runner, test); } } createOutput(runner); }
src/runTests.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/runner/expect.ts", "retrieved_chunk": "}\nasync function runExpect(runner: Runner, test: Test): Promise<void> {\n let startTime = Date.now();\n let run: SpawnSyncReturns<Buffer> = spawnSync(test.command, {\n timeout: runner.settings.timeout,\n shell: true\n });\n let endTime = Date.now();\n if (runner.settings.verbose) {\n console.log(`Run stdout: \"${run.stdout}\"`);", "score": 0.8774486184120178 }, { "filename": "src/runner/refer.ts", "retrieved_chunk": "import {Runner, Test, Out} from '../modules/types.js';\nimport { spawnSync, SpawnSyncReturns } from 'child_process';\nimport jobError from './jobError.js';\nasync function runRefer(runner: Runner, test: Test): Promise<void> {\n let startTime = Date.now();\n let run: SpawnSyncReturns<Buffer> = spawnSync(test.command, {\n timeout: runner.settings.timeout,\n shell: true\n });\n let endTime = Date.now();", "score": 0.8688200116157532 }, { "filename": "src/fileParsing/parse.ts", "retrieved_chunk": " expected.stdout = test.stdout;\n if (test.stderr)\n expected.stderr = test.stderr;\n if (test.exitCode !== undefined)\n expected.exitCode = test.exitCode;\n return expected;\n}\nexport default async function parse(runner: Runner, doc: any): Promise<Runner> {\n const tests: Test[] = [];\n try {", "score": 0.8666711449623108 }, { "filename": "src/output.ts", "retrieved_chunk": "export function returnYaml(runner: Runner): string {\n return yaml.dump(constructReturn(runner));\n}\nfunction print_end(runner: Runner): void {\n if (runner.settings.verbose)\n console.log(\"Finished Tests!\");\n if (runner.settings.outputFormat == 'text')\n console.log(`\\nTests Results\n->\\tSuccess: ${runner.numberSuccess}\\tFail: ${runner.numberFail} \\tSkipped: ${runner.tests.length - runner.numberFail - runner.numberSuccess}\\t<-`);\n}", "score": 0.8568542003631592 }, { "filename": "src/argsHandler.ts", "retrieved_chunk": " break;\n }\n }\n if (runner.testFilePath === '') {\n help();\n process.exit(1);\n }\n if (runner.testFilePath.endsWith('.yaml') || runner.testFilePath.endsWith('.yml'))\n runner = await parseYaml(runner);\n else if (runner.testFilePath.endsWith('.json'))", "score": 0.8549019694328308 } ]
typescript
console.log(`Starting Tests for ${runner.testFilePath}...`);
import help from './modules/help.js'; import error from './modules/log.js'; import { Runner } from './modules/types.js'; import parseYaml from './fileParsing/yaml.js'; import parseJson from './fileParsing/json.js'; async function parseArguments(args: string[]): Promise<Runner> { let runner: Runner = { testFilePath: '', tests: [], settings: { output: 'stdout', outputFormat: 'text', timeout: 0, verbose: false, status: false, runList: [], stopWhenFail: false, }, numberSuccess: 0, numberFail: 0, }; for (let i = 0; i < args.length; i++) { switch (args[i]) { case '-o': case '--output': if (args[i + 1] === undefined) error("Invalid output (must be 'file [json or yaml]')"); runner.settings.output = args[i + 1]; runner.settings.outputFormat = 'yaml'; if (args[i + 1].endsWith('.json')) runner.settings.outputFormat = 'json'; i++; break; case '-t': case '--timeout': if (args[i + 1] === undefined || isNaN(parseInt(args[i + 1])) || parseInt(args[i + 1]) < 0) error('Invalid timeout'); runner.settings.timeout = parseInt(args[i + 1]); i++; break; case '-v': case '--verbose': runner.settings.verbose = true; break; case '-s': case '--status': runner.settings.status = true; break; case '-swf': case '--stop-when-fail': runner.settings.stopWhenFail = true; break; case '-r': case '--runList': if (args[i + 1] === undefined || args[i + 1].split(',').some((x) => isNaN(parseInt(x)))) error('Invalid run list'); runner.settings.runList = args[i + 1].split(',').map((x) => parseInt(x)); i++; break; case '-h': case '--help': help(); process.exit(0); default: if (args[i].startsWith('-') || args[i].startsWith('--')) error(`Invalid argument: ${args[i]}`); runner.testFilePath = args[i]; break; } } if (runner.testFilePath === '') { help(); process.exit(1); } if (runner.testFilePath.endsWith('.yaml') || runner.testFilePath.endsWith('.yml')) runner = await parseYaml(runner); else if (runner.testFilePath.endsWith('.json'))
runner = await parseJson(runner);
return runner; } export default parseArguments; export { parseArguments };
src/argsHandler.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/fileParsing/json.ts", "retrieved_chunk": "import* as fs from 'fs';\nimport error from '../modules/log.js';\nimport { Runner, Test, Out } from '../modules/types.js';\nimport parse from './parse.js';\nexport default async function parseYaml(runner: Runner): Promise<Runner> {\n let data = fs.readFileSync(runner.testFilePath, 'utf8');\n if (!data) error(`Error reading file from disk: ${runner.testFilePath}`);\n try {\n return await parse(runner, JSON.parse(data));\n } catch(e) {", "score": 0.8979851603507996 }, { "filename": "src/fileParsing/yaml.ts", "retrieved_chunk": "import* as fs from 'fs';\nimport* as yaml from 'js-yaml';\nimport error from '../modules/log.js';\nimport { Runner, Test, Out } from '../modules/types.js';\nimport parse from './parse.js';\nexport default async function parseYaml(runner: Runner): Promise<Runner> {\n let data = fs.readFileSync(runner.testFilePath, 'utf8');\n if (!data) error(`Error reading file from disk: ${runner.testFilePath}`);\n try {\n return await parse(runner, yaml.load(data));", "score": 0.8910610675811768 }, { "filename": "src/fileParsing/parse.ts", "retrieved_chunk": " }\n } catch(e) {\n error(`Error parsing: ${e}`);\n }\n runner.tests = tests;\n return runner;\n}", "score": 0.8710061311721802 }, { "filename": "src/runTests.ts", "retrieved_chunk": " if (runner.settings.verbose) {\n print_test_description(test);\n } else if (runner.settings.outputFormat == 'text') \n process.stdout.write(`Test ${test.id}: ${test.name}... \\t`);\n if (test.testType === 'refer')\n await runRefer(runner, test);\n else if (test.testType === 'expect')\n await runExpect(runner, test);\n if (runner.settings.verbose)\n console.log('\\n');", "score": 0.8665636777877808 }, { "filename": "src/fileParsing/parse.ts", "retrieved_chunk": " expected.stdout = test.stdout;\n if (test.stderr)\n expected.stderr = test.stderr;\n if (test.exitCode !== undefined)\n expected.exitCode = test.exitCode;\n return expected;\n}\nexport default async function parse(runner: Runner, doc: any): Promise<Runner> {\n const tests: Test[] = [];\n try {", "score": 0.862135112285614 } ]
typescript
runner = await parseJson(runner);
import help from './modules/help.js'; import error from './modules/log.js'; import { Runner } from './modules/types.js'; import parseYaml from './fileParsing/yaml.js'; import parseJson from './fileParsing/json.js'; async function parseArguments(args: string[]): Promise<Runner> { let runner: Runner = { testFilePath: '', tests: [], settings: { output: 'stdout', outputFormat: 'text', timeout: 0, verbose: false, status: false, runList: [], stopWhenFail: false, }, numberSuccess: 0, numberFail: 0, }; for (let i = 0; i < args.length; i++) { switch (args[i]) { case '-o': case '--output': if (args[i + 1] === undefined) error("Invalid output (must be 'file [json or yaml]')"); runner.settings.output = args[i + 1]; runner.settings.outputFormat = 'yaml'; if (args[i + 1].endsWith('.json')) runner.settings.outputFormat = 'json'; i++; break; case '-t': case '--timeout': if (args[i + 1] === undefined || isNaN(parseInt(args[i + 1])) || parseInt(args[i + 1]) < 0) error('Invalid timeout'); runner.settings.timeout = parseInt(args[i + 1]); i++; break; case '-v': case '--verbose': runner.settings.verbose = true; break; case '-s': case '--status': runner.settings.status = true; break; case '-swf': case '--stop-when-fail': runner.settings.stopWhenFail = true; break; case '-r': case '--runList': if (args[i + 1] === undefined || args[i + 1].split(',').some((x) => isNaN(parseInt(x)))) error('Invalid run list'); runner.settings.runList = args[i + 1].split(',').map((x) => parseInt(x)); i++; break; case '-h': case '--help': help(); process.exit(0); default: if (args[i].startsWith('-') || args[i].startsWith('--')) error(`Invalid argument: ${args[i]}`); runner.testFilePath = args[i]; break; } } if (runner.testFilePath === '') { help(); process.exit(1); } if (runner.testFilePath.endsWith('.yaml') || runner.testFilePath.endsWith('.yml')) runner
= await parseYaml(runner);
else if (runner.testFilePath.endsWith('.json')) runner = await parseJson(runner); return runner; } export default parseArguments; export { parseArguments };
src/argsHandler.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/fileParsing/json.ts", "retrieved_chunk": "import* as fs from 'fs';\nimport error from '../modules/log.js';\nimport { Runner, Test, Out } from '../modules/types.js';\nimport parse from './parse.js';\nexport default async function parseYaml(runner: Runner): Promise<Runner> {\n let data = fs.readFileSync(runner.testFilePath, 'utf8');\n if (!data) error(`Error reading file from disk: ${runner.testFilePath}`);\n try {\n return await parse(runner, JSON.parse(data));\n } catch(e) {", "score": 0.8871683478355408 }, { "filename": "src/fileParsing/yaml.ts", "retrieved_chunk": "import* as fs from 'fs';\nimport* as yaml from 'js-yaml';\nimport error from '../modules/log.js';\nimport { Runner, Test, Out } from '../modules/types.js';\nimport parse from './parse.js';\nexport default async function parseYaml(runner: Runner): Promise<Runner> {\n let data = fs.readFileSync(runner.testFilePath, 'utf8');\n if (!data) error(`Error reading file from disk: ${runner.testFilePath}`);\n try {\n return await parse(runner, yaml.load(data));", "score": 0.8839205503463745 }, { "filename": "src/runner/jobError.ts", "retrieved_chunk": " createOutput(runner);\n if (runner.settings.status)\n process.exit(1);\n else\n process.exit(0);\n }\n}", "score": 0.8648998737335205 }, { "filename": "src/fileParsing/parse.ts", "retrieved_chunk": " }\n } catch(e) {\n error(`Error parsing: ${e}`);\n }\n runner.tests = tests;\n return runner;\n}", "score": 0.8616059422492981 }, { "filename": "src/runTests.ts", "retrieved_chunk": " if (runner.settings.verbose) {\n print_test_description(test);\n } else if (runner.settings.outputFormat == 'text') \n process.stdout.write(`Test ${test.id}: ${test.name}... \\t`);\n if (test.testType === 'refer')\n await runRefer(runner, test);\n else if (test.testType === 'expect')\n await runExpect(runner, test);\n if (runner.settings.verbose)\n console.log('\\n');", "score": 0.8570073246955872 } ]
typescript
= await parseYaml(runner);
import help from './modules/help.js'; import error from './modules/log.js'; import { Runner } from './modules/types.js'; import parseYaml from './fileParsing/yaml.js'; import parseJson from './fileParsing/json.js'; async function parseArguments(args: string[]): Promise<Runner> { let runner: Runner = { testFilePath: '', tests: [], settings: { output: 'stdout', outputFormat: 'text', timeout: 0, verbose: false, status: false, runList: [], stopWhenFail: false, }, numberSuccess: 0, numberFail: 0, }; for (let i = 0; i < args.length; i++) { switch (args[i]) { case '-o': case '--output': if (args[i + 1] === undefined) error("Invalid output (must be 'file [json or yaml]')"); runner.settings.output = args[i + 1]; runner.settings.outputFormat = 'yaml'; if (args[i + 1].endsWith('.json')) runner.settings.outputFormat = 'json'; i++; break; case '-t': case '--timeout': if (args[i + 1] === undefined || isNaN(parseInt(args[i + 1])) || parseInt(args[i + 1]) < 0) error('Invalid timeout'); runner.settings.timeout = parseInt(args[i + 1]); i++; break; case '-v': case '--verbose': runner.settings.verbose = true; break; case '-s': case '--status': runner.settings.status = true; break; case '-swf': case '--stop-when-fail': runner.settings.stopWhenFail = true; break; case '-r': case '--runList': if (args[i + 1] === undefined || args[i + 1].split(',').some((x) => isNaN(parseInt(x)))) error('Invalid run list'); runner.settings.runList = args[i + 1].split(',').map((x) => parseInt(x)); i++; break; case '-h': case '--help': help(); process.exit(0); default: if (args[i].startsWith('-') || args[i].startsWith('--')) error(`Invalid argument: ${args[i]}`);
runner.testFilePath = args[i];
break; } } if (runner.testFilePath === '') { help(); process.exit(1); } if (runner.testFilePath.endsWith('.yaml') || runner.testFilePath.endsWith('.yml')) runner = await parseYaml(runner); else if (runner.testFilePath.endsWith('.json')) runner = await parseJson(runner); return runner; } export default parseArguments; export { parseArguments };
src/argsHandler.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/modules/help.ts", "retrieved_chunk": "function help(): void {\n process.stdout.write(`Usage ${process.argv[1].split(\"/\").slice(-1)} [options] [file]`);\n process.stdout.write(`\\n\\n`);\n process.stdout.write(`Options:\\n`);\n process.stdout.write(`\\t-o, --output [file (json or yaml)]\\t`);\n process.stdout.write(`Output format (default: text)\\n`);\n process.stdout.write(`\\t-swf, --stop-when-fail\\t`);\n process.stdout.write(`Stop when a test fails (default: false)\\n`);\n process.stdout.write(`\\t-t, --timeout [number]\\t`);\n process.stdout.write(`Timeout in milliseconds (default: -1)\\n`);", "score": 0.8426163196563721 }, { "filename": "src/modules/help.ts", "retrieved_chunk": " process.stdout.write(`\\t-v, --verbose\\t`);\n process.stdout.write(`Verbose output (default: false)\\n`);\n process.stdout.write(`\\t-s, --status\\t`);\n process.stdout.write(`Show status (default: false)\\n`);\n process.stdout.write(`\\t-r, --runList [number,number,...]\\t`);\n process.stdout.write(`Run only specified tests (default: [])\\n`);\n process.stdout.write(`\\t-h, --help\\t`);\n process.stdout.write(`Show this help message\\n`);\n process.stdout.write(`\\n`);\n}", "score": 0.8404353857040405 }, { "filename": "src/fileParsing/parse.ts", "retrieved_chunk": " }\n } catch(e) {\n error(`Error parsing: ${e}`);\n }\n runner.tests = tests;\n return runner;\n}", "score": 0.8311001062393188 }, { "filename": "src/binaryTester.ts", "retrieved_chunk": "import argsHandler from './argsHandler.js';\nimport runTests from './runTests.js';\nexport async function cli(): Promise<void> {\n runTests((await argsHandler(process.argv.slice(2))));\n}", "score": 0.8304855823516846 }, { "filename": "src/runTests.ts", "retrieved_chunk": " stdout: undefined,\n stderr: undefined,\n exitCode: undefined\n },\n timeTaken: undefined\n };\n }\n }\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) {", "score": 0.8254153728485107 } ]
typescript
runner.testFilePath = args[i];
import chalk from "chalk" import fs from "fs" import path from "path" import { Ora } from "ora" import promiseExec from "./promise-exec.js" import { EOL } from "os" import runProcess from "./run-process.js" import getFact from "./get-fact.js" import onProcessTerminated from "./on-process-terminated.js" import boxen from "boxen" type PrepareOptions = { directory: string dbConnectionString: string admin?: { email: string } seed?: boolean spinner?: Ora abortController?: AbortController } const showFact = (lastFact: string, spinner: Ora): string => { const fact = getFact(lastFact) spinner.text = `${boxen(fact, { title: chalk.cyan("Installing Dependencies..."), titleAlignment: "center", textAlignment: "center", padding: 1, margin: 1, float: "center", })}` return fact } export default async ({ directory, dbConnectionString, admin, seed, spinner, abortController, }: PrepareOptions) => { // initialize execution options const execOptions = { cwd: directory, signal: abortController?.signal, } // initialize the invite token to return let inviteToken: string | undefined = undefined // add connection string to project fs.appendFileSync( path.join(directory, `.env`), `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}` ) let interval: NodeJS.Timer | undefined = undefined let fact = "" if (spinner) { spinner.spinner = { frames: [""], } fact = showFact(fact, spinner) interval = setInterval(() => { fact = showFact(fact, spinner) }, 6000) onProcessTerminated(() => clearInterval(interval)) } await runProcess({ process: async () => { try { await
promiseExec(`yarn`, execOptions) } catch (e) {
// yarn isn't available // use npm await promiseExec(`npm install`, execOptions) } }, ignoreERESOLVE: true, }) if (interval) { clearInterval(interval) } if (spinner) { spinner.spinner = "dots" spinner.succeed(chalk.green("Installed Dependencies")) spinner.start(chalk.white("Running Migrations...")) } // run migrations await runProcess({ process: async () => { await promiseExec( "npx -y @medusajs/medusa-cli@latest migrations run", execOptions ) }, }) spinner?.succeed(chalk.green("Ran Migrations")).start() if (admin) { // create admin user if (spinner) { spinner.text = chalk.white("Creating an admin user...") } await runProcess({ process: async () => { const proc = await promiseExec( `npx -y @medusajs/medusa-cli@1.3.15-snapshot-20230529090917 user -e ${admin.email} --invite`, execOptions ) // get invite token from stdout const match = proc.stdout.match(/Invite token: (?<token>.+)/) inviteToken = match?.groups?.token }, }) spinner?.succeed(chalk.green("Created admin user")).start() } if (seed) { if (spinner) { spinner.text = chalk.white("Seeding database...") } // check if a seed file exists in the project if (!fs.existsSync(path.join(directory, "data", "seed.jsons"))) { spinner ?.warn( chalk.yellow( "Seed file was not found in the project. Skipping seeding..." ) ) .start() return } if (spinner) { spinner.text = chalk.white("Seeding database with demo data...") } await runProcess({ process: async () => { await promiseExec( `npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join( "data", "seed.json" )}`, execOptions ) }, }) spinner?.succeed(chalk.green("Seeded database with demo data")).start() } return inviteToken }
src/utils/prepare-project.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/run-process.ts", "retrieved_chunk": " do {\n try {\n await process()\n } catch (error) {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error?.code === \"EAGAIN\"\n ) {", "score": 0.8305988311767578 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " ? true\n : \"Please enter a valid email\"\n },\n },\n ])\n const spinner = ora(chalk.white(\"Setting up project\")).start()\n onProcessTerminated(() => spinner.stop())\n // clone repository\n try {\n await cloneRepo({", "score": 0.8003678917884827 }, { "filename": "src/utils/on-process-terminated.ts", "retrieved_chunk": "export default (fn: Function) => {\n process.on(\"SIGTERM\", () => fn())\n process.on(\"SIGINT\", () => fn())\n}", "score": 0.8000764846801758 }, { "filename": "src/utils/start-medusa.ts", "retrieved_chunk": " childProcess.stdout?.pipe(process.stdout)\n}", "score": 0.7980116605758667 }, { "filename": "src/utils/run-process.ts", "retrieved_chunk": "type ProcessOptions = {\n process: Function\n ignoreERESOLVE?: boolean\n}\n// when running commands with npx or npm sometimes they\n// terminate with EAGAIN error unexpectedly\n// this utility function allows retrying the process if\n// EAGAIN occurs, or otherwise throw the error that occurs\nexport default async ({ process, ignoreERESOLVE }: ProcessOptions) => {\n let processError = false", "score": 0.7948758602142334 } ]
typescript
promiseExec(`yarn`, execOptions) } catch (e) {
import inquirer from "inquirer" import slugifyType from "slugify" import chalk from "chalk" import pg from "pg" import createDb from "../utils/create-db.js" import postgresClient from "../utils/postgres-client.js" import cloneRepo from "../utils/clone-repo.js" import prepareProject from "../utils/prepare-project.js" import startMedusa from "../utils/start-medusa.js" import open from "open" import waitOn from "wait-on" import formatConnectionString from "../utils/format-connection-string.js" import ora from "ora" import fs from "fs" import { nanoid } from "nanoid" import isEmailImported from "validator/lib/isEmail.js" import logMessage from "../utils/log-message.js" import onProcessTerminated from "../utils/on-process-terminated.js" import createAbortController, { isAbortError, } from "../utils/create-abort-controller.js" const slugify = slugifyType.default const isEmail = isEmailImported.default type CreateOptions = { repoUrl?: string seed?: boolean } export default async ({ repoUrl = "", seed }: CreateOptions) => { const abortController = createAbortController() const { projectName } = await inquirer.prompt([ { type: "input", name: "projectName", message: "What's the name of your project?", default: "my-medusa-store", filter: (input) => { return slugify(input) }, validate: (input) => { if (!input.length) { return "Please enter a project name" } return fs.existsSync(input) && fs.lstatSync(input).isDirectory() ? "A directory already exists with the same name. Please enter a different project name." : true }, }, ]) let client: pg.Client | undefined let dbConnectionString = "" let postgresUsername = "postgres" let postgresPassword = "" // try to log in with default db username and password try {
client = await postgresClient({
user: postgresUsername, password: postgresPassword, }) } catch (e) { // ask for the user's credentials const answers = await inquirer.prompt([ { type: "input", name: "postgresUsername", message: "Enter your Postgres username", default: "postgres", validate: (input) => { return typeof input === "string" && input.length > 0 }, }, { type: "password", name: "postgresPassword", message: "Enter your Postgres password", }, ]) postgresUsername = answers.postgresUsername postgresPassword = answers.postgresPassword try { client = await postgresClient({ user: postgresUsername, password: postgresPassword, }) } catch (e) { logMessage({ message: "Couldn't connect to PostgreSQL. Make sure you have PostgreSQL installed and the credentials you provided are correct.\n\n" + "You can learn how to install PostgreSQL here: https://docs.medusajs.com/development/backend/prepare-environment#postgresql", type: "error", }) } } const { adminEmail } = await inquirer.prompt([ { type: "input", name: "adminEmail", message: "Enter an email for your admin dashboard user", default: !seed ? "admin@medusa-test.com" : undefined, validate: (input) => { return typeof input === "string" && input.length > 0 && isEmail(input) ? true : "Please enter a valid email" }, }, ]) const spinner = ora(chalk.white("Setting up project")).start() onProcessTerminated(() => spinner.stop()) // clone repository try { await cloneRepo({ directoryName: projectName, repoUrl, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while setting up your project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Created project directory")).start() if (client) { spinner.text = chalk.white("Creating database...") const dbName = `medusa-${nanoid(4)}` // create postgres database try { await createDb({ client, db: dbName, }) } catch (e) { logMessage({ message: `An error occurred while trying to create your database: ${e}`, type: "error", }) } // format connection string dbConnectionString = formatConnectionString({ user: postgresUsername, password: postgresPassword, host: client.host, db: dbName, }) spinner.succeed(chalk.green(`Database ${dbName} created`)).start() } spinner.text = chalk.white("Preparing project...") // prepare project let inviteToken: string | undefined = undefined try { inviteToken = await prepareProject({ directory: projectName, dbConnectionString, admin: { email: adminEmail, }, seed, spinner, abortController, }) } catch (e: any) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while preparing project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Project Prepared")) // close db connection await client?.end() // start backend logMessage({ message: "Starting Medusa...", }) try { startMedusa({ directory: projectName, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while starting Medusa`, type: "error", }) } waitOn({ resources: ["http://localhost:9000/health"], }).then(() => open( inviteToken ? `http://localhost:9000/app/invite?token=${inviteToken}` : "http://localhost:9000/app" ) ) }
src/commands/create.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/postgres-client.ts", "retrieved_chunk": "import pg from \"pg\"\nconst { Client } = pg\ntype PostgresConnection = {\n user?: string\n password?: string\n}\nexport default async (connect: PostgresConnection) => {\n const client = new Client(connect)\n await client.connect()\n return client", "score": 0.8741458058357239 }, { "filename": "src/utils/create-db.ts", "retrieved_chunk": "import pg from \"pg\"\ntype CreateDbOptions = {\n client: pg.Client\n db: string\n}\nexport default async ({ client, db }: CreateDbOptions) => {\n await client.query(`CREATE DATABASE \"${db}\"`)\n}", "score": 0.855824887752533 }, { "filename": "src/utils/format-connection-string.ts", "retrieved_chunk": "type ConnectionStringOptions = {\n user?: string\n password?: string\n host?: string\n db: string\n}\nexport default ({ user, password, host, db }: ConnectionStringOptions) => {\n let connection = `postgres://`\n if (user) {\n connection += user", "score": 0.8427742123603821 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}`\n )\n let interval: NodeJS.Timer | undefined = undefined\n let fact = \"\"\n if (spinner) {\n spinner.spinner = {\n frames: [\"\"],\n }\n fact = showFact(fact, spinner)\n interval = setInterval(() => {", "score": 0.7882771492004395 }, { "filename": "src/utils/format-connection-string.ts", "retrieved_chunk": " }\n if (password) {\n connection += `:${password}`\n }\n if (user || password) {\n connection += \"@\"\n }\n connection += `${host}/${db}`\n return connection\n}", "score": 0.7781035900115967 } ]
typescript
client = await postgresClient({
import axios from "axios"; import { getOptions, Options } from "../../types/Bing"; import * as cheerio from 'cheerio'; import HttpsProxyAgent from 'https-proxy-agent'; import _url from "../../utils/handleUrl"; import useProxies from "../../utils/useProxies"; import https from 'https'; export class Bing { private options: Options = getOptions(); private updateQueries: (name: string, value: any) => void; constructor(options: Options = getOptions()) { let _options = { ...getOptions(), ...options }; function updateQueries(name: string, value: any) { _options.queries = { ..._options.queries, [name]: value } } if (_options?.mkt) { if (!_options?.queries?.mkt) updateQueries('mkt', _options?.mkt); if (!_options?.queries?.setlang) updateQueries('setlang', _options?.mkt); } if (_options?.safe) { if (!_options?.queries?.safe) updateQueries('safeSearch', _options?.safe); } if (_options?.perPage) { if (!_options?.queries?.count) updateQueries('count', _options?.perPage); if (!_options?.queries?.offset) updateQueries('offset', (_options?.perPage * (_options?.page - 1))); } if (!_options?.queries?.pt) updateQueries('pt', 'page.serp'); if (!_options?.queries?.mkt) updateQueries('mkt', 'en-us'); if (!_options?.queries?.cp) updateQueries('cp', 6); if (!_options?.queries?.msbqf) updateQueries('msbqf', false); if (!_options?.queries?.cvid) updateQueries('cvid', 'void_development'); this.updateQueries = updateQueries; this.options = _options; } useProxies = useProxies; public async search(query: string): Promise<{}> {
if (!this.options?.queries?.bq) this.updateQueries('bq', query);
if (!this.options?.queries?.q) this.updateQueries('q', query); if (!this.options?.queries?.qry) this.updateQueries('qry', query); const __proxy = this.options.proxy; if (__proxy) { this.options.proxies.push(__proxy); this.options.proxy = undefined; } return await this.useProxies(() => this._search(query)); } private async _search(query: string): Promise<{}> { return new Promise(async (resolve, reject) => { const agent = this.options.proxy ? HttpsProxyAgent({ host: this.options.proxy?.host, port: this.options.proxy?.port, auth: this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password }) : new https.Agent({ rejectUnauthorized: false }); return await axios(Object.assign({ url: _url(`https://www.bing.com/search`, this.options.queries), method: 'GET', headers: this.options.headers }, (agent ? { proxy: this.options.proxy ? { host: this.options.proxy?.host, port: this.options.proxy?.port, auth: { username: this.options.proxy?.auth?.username, password: this.options.proxy?.auth?.password } } : undefined, httpsAgent: agent } : {}))).then(response => { const html = response.data; const $ = cheerio.load(html); const results: any[] = []; $('#b_results .b_algo').each((i, el) => { const title = $(el).find('h2 a').first().text(); const description = $(el).find('.b_algoSlug').each((i, el) => { $(el).find('span').remove(); }).text(); const link = $(el).find('a').first().attr('href'); const deepLinks: any[] = []; $(el).find('.b_deep li').each((i, el) => { deepLinks.push({ title: $(el).find('a').text(), link: $(el).find('a').attr('href'), description: $(el).find('p').text() }); }); results.push({ title, description, link, deepLinks }); }); const data = { results, proxy: this.options.proxy, queries: this.options.queries }; return resolve(data); }).catch(error => { return reject(error); }); }); } public async suggestions(query: string): Promise<{}> { if (!this.options?.queries?.bq) this.updateQueries('bq', query); if (!this.options?.queries?.q) this.updateQueries('q', query); if (!this.options?.queries?.qry) this.updateQueries('qry', query); const __proxy = this.options.proxy; if (__proxy) { this.options.proxies.push(__proxy); this.options.proxy = undefined; } return await this.useProxies(() => this._suggestions(query)); } private async _suggestions(query: string): Promise<{}> { return new Promise(async (resolve, reject) => { const agent = this.options.proxy ? HttpsProxyAgent({ host: this.options.proxy?.host, port: this.options.proxy?.port, auth: this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password }) : new https.Agent({ rejectUnauthorized: false }); return await axios(Object.assign({ url: _url(`https://www.bing.com/AS/Suggestions`, this.options.queries), method: 'GET', headers: this.options.headers }, (agent ? { proxy: this.options.proxy ? { host: this.options.proxy?.host, port: this.options.proxy?.port, auth: { username: this.options.proxy?.auth?.username, password: this.options.proxy?.auth?.password } } : undefined, httpsAgent: agent } : {}))).then(response => { const html = response.data; const $ = cheerio.load(html); const suggestions: any[] = []; $('#sa_ul li').each((i, el) => { suggestions.push({ text: $(el).find('.pp_title').text() || $(el).find('.sa_tm_text').text() || null, image: $(el).find('img').attr('src') ? 'https://th.bing.com' + $(el).find('img').attr('src') : null }); }); const data = { suggestions: suggestions.filter(s => s.text), proxy: this.options.proxy, queries: this.options.queries }; return resolve(data); }).catch(error => { return reject(error); }); }); } public async images(query: string): Promise<{}> { return new Error('Not implemented yet'); } }
src/engines/lib/Bing.ts
VoidDevsorg-node-scrapper-470e34a
[ { "filename": "src/engines/lib/YouTube.ts", "retrieved_chunk": " }\n this.updateQueries = updateQueries;\n this.options = _options;\n }\n useProxies = useProxies;\n public async search(query: string): Promise<{}> {\n this.updateQueries('search_query', encodeURIComponent(query));\n const __proxy = this.options.proxy;\n if (__proxy) {\n this.options.proxies.push(__proxy);", "score": 0.9535523653030396 }, { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " if (!_options?.queries?.num) updateQueries('num', _options?.perPage);\n if (!_options?.queries?.start) updateQueries('start', (_options?.page - 1) * _options?.perPage);\n }\n this.updateQueries = updateQueries;\n this.options = _options;\n }\n useProxies = useProxies;\n public async search(query: string): Promise<{}> {\n if (!this.options?.queries?.q) this.updateQueries('q', query);\n const __proxy = this.options.proxy;", "score": 0.9478996992111206 }, { "filename": "src/engines/lib/Wikipedia.ts", "retrieved_chunk": " }\n this.updateQueries = updateQueries;\n this.options = _options;\n }\n useProxies = useProxies;\n public async get(query: string): Promise<{}> {\n const __proxy = this.options.proxy;\n if (__proxy) {\n this.options.proxies.push(__proxy);\n this.options.proxy = undefined;", "score": 0.9173150062561035 }, { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " this.updateQueries('client', 'gws-wiz');\n this.updateQueries('dpr', 1);\n const __proxy = this.options.proxy;\n if (__proxy) {\n this.options.proxies.push(__proxy);\n this.options.proxy = undefined;\n }\n return await this.useProxies(() => this._suggestions(query));\n }\n private async _suggestions(query: string): Promise<{}> {", "score": 0.8923419713973999 }, { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " }\n if (_options?.mkt) {\n if (!_options?.queries?.lr) updateQueries('lr', 'lang_' + (_options?.mkt?.split('-')?.[0] || 'en'));\n if (!_options?.queries?.hl) updateQueries('hl', _options?.mkt?.split('-')?.[0] || 'en');\n if (!_options?.queries?.gl) updateQueries('gl', _options?.mkt?.split('-')?.[1] || 'US');\n }\n if (_options?.safe) {\n if (!_options?.queries?.safe) updateQueries('safe', _options?.safe);\n }\n if (_options?.perPage) {", "score": 0.8856258392333984 } ]
typescript
if (!this.options?.queries?.bq) this.updateQueries('bq', query);
import chalk from "chalk" import fs from "fs" import path from "path" import { Ora } from "ora" import promiseExec from "./promise-exec.js" import { EOL } from "os" import runProcess from "./run-process.js" import getFact from "./get-fact.js" import onProcessTerminated from "./on-process-terminated.js" import boxen from "boxen" type PrepareOptions = { directory: string dbConnectionString: string admin?: { email: string } seed?: boolean spinner?: Ora abortController?: AbortController } const showFact = (lastFact: string, spinner: Ora): string => { const fact = getFact(lastFact) spinner.text = `${boxen(fact, { title: chalk.cyan("Installing Dependencies..."), titleAlignment: "center", textAlignment: "center", padding: 1, margin: 1, float: "center", })}` return fact } export default async ({ directory, dbConnectionString, admin, seed, spinner, abortController, }: PrepareOptions) => { // initialize execution options const execOptions = { cwd: directory, signal: abortController?.signal, } // initialize the invite token to return let inviteToken: string | undefined = undefined // add connection string to project fs.appendFileSync( path.join(directory, `.env`), `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}` ) let interval: NodeJS.Timer | undefined = undefined let fact = "" if (spinner) { spinner.spinner = { frames: [""], } fact = showFact(fact, spinner) interval = setInterval(() => { fact = showFact(fact, spinner) }, 6000) onProcessTerminated(() => clearInterval(interval)) } await
runProcess({
process: async () => { try { await promiseExec(`yarn`, execOptions) } catch (e) { // yarn isn't available // use npm await promiseExec(`npm install`, execOptions) } }, ignoreERESOLVE: true, }) if (interval) { clearInterval(interval) } if (spinner) { spinner.spinner = "dots" spinner.succeed(chalk.green("Installed Dependencies")) spinner.start(chalk.white("Running Migrations...")) } // run migrations await runProcess({ process: async () => { await promiseExec( "npx -y @medusajs/medusa-cli@latest migrations run", execOptions ) }, }) spinner?.succeed(chalk.green("Ran Migrations")).start() if (admin) { // create admin user if (spinner) { spinner.text = chalk.white("Creating an admin user...") } await runProcess({ process: async () => { const proc = await promiseExec( `npx -y @medusajs/medusa-cli@1.3.15-snapshot-20230529090917 user -e ${admin.email} --invite`, execOptions ) // get invite token from stdout const match = proc.stdout.match(/Invite token: (?<token>.+)/) inviteToken = match?.groups?.token }, }) spinner?.succeed(chalk.green("Created admin user")).start() } if (seed) { if (spinner) { spinner.text = chalk.white("Seeding database...") } // check if a seed file exists in the project if (!fs.existsSync(path.join(directory, "data", "seed.jsons"))) { spinner ?.warn( chalk.yellow( "Seed file was not found in the project. Skipping seeding..." ) ) .start() return } if (spinner) { spinner.text = chalk.white("Seeding database with demo data...") } await runProcess({ process: async () => { await promiseExec( `npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join( "data", "seed.json" )}`, execOptions ) }, }) spinner?.succeed(chalk.green("Seeded database with demo data")).start() } return inviteToken }
src/utils/prepare-project.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/run-process.ts", "retrieved_chunk": " do {\n try {\n await process()\n } catch (error) {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error?.code === \"EAGAIN\"\n ) {", "score": 0.7981734275817871 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " ? true\n : \"Please enter a valid email\"\n },\n },\n ])\n const spinner = ora(chalk.white(\"Setting up project\")).start()\n onProcessTerminated(() => spinner.stop())\n // clone repository\n try {\n await cloneRepo({", "score": 0.7922078371047974 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " }\n spinner.succeed(chalk.green(\"Project Prepared\"))\n // close db connection\n await client?.end()\n // start backend\n logMessage({\n message: \"Starting Medusa...\",\n })\n try {\n startMedusa({", "score": 0.7826918959617615 }, { "filename": "src/utils/start-medusa.ts", "retrieved_chunk": " childProcess.stdout?.pipe(process.stdout)\n}", "score": 0.7823916673660278 }, { "filename": "src/utils/get-fact.ts", "retrieved_chunk": " let index = 0\n if (lastFact.length) {\n const lastFactIndex = facts.findIndex((fact) => fact === lastFact)\n if (lastFactIndex !== facts.length - 1) {\n index = lastFactIndex + 1\n }\n }\n return facts[index]\n}", "score": 0.7821841835975647 } ]
typescript
runProcess({
import inquirer from "inquirer" import slugifyType from "slugify" import chalk from "chalk" import pg from "pg" import createDb from "../utils/create-db.js" import postgresClient from "../utils/postgres-client.js" import cloneRepo from "../utils/clone-repo.js" import prepareProject from "../utils/prepare-project.js" import startMedusa from "../utils/start-medusa.js" import open from "open" import waitOn from "wait-on" import formatConnectionString from "../utils/format-connection-string.js" import ora from "ora" import fs from "fs" import { nanoid } from "nanoid" import isEmailImported from "validator/lib/isEmail.js" import logMessage from "../utils/log-message.js" import onProcessTerminated from "../utils/on-process-terminated.js" import createAbortController, { isAbortError, } from "../utils/create-abort-controller.js" const slugify = slugifyType.default const isEmail = isEmailImported.default type CreateOptions = { repoUrl?: string seed?: boolean } export default async ({ repoUrl = "", seed }: CreateOptions) => { const abortController = createAbortController() const { projectName } = await inquirer.prompt([ { type: "input", name: "projectName", message: "What's the name of your project?", default: "my-medusa-store", filter: (input) => { return slugify(input) }, validate: (input) => { if (!input.length) { return "Please enter a project name" } return fs.existsSync(input) && fs.lstatSync(input).isDirectory() ? "A directory already exists with the same name. Please enter a different project name." : true }, }, ]) let client: pg.Client | undefined let dbConnectionString = "" let postgresUsername = "postgres" let postgresPassword = "" // try to log in with default db username and password try { client
= await postgresClient({
user: postgresUsername, password: postgresPassword, }) } catch (e) { // ask for the user's credentials const answers = await inquirer.prompt([ { type: "input", name: "postgresUsername", message: "Enter your Postgres username", default: "postgres", validate: (input) => { return typeof input === "string" && input.length > 0 }, }, { type: "password", name: "postgresPassword", message: "Enter your Postgres password", }, ]) postgresUsername = answers.postgresUsername postgresPassword = answers.postgresPassword try { client = await postgresClient({ user: postgresUsername, password: postgresPassword, }) } catch (e) { logMessage({ message: "Couldn't connect to PostgreSQL. Make sure you have PostgreSQL installed and the credentials you provided are correct.\n\n" + "You can learn how to install PostgreSQL here: https://docs.medusajs.com/development/backend/prepare-environment#postgresql", type: "error", }) } } const { adminEmail } = await inquirer.prompt([ { type: "input", name: "adminEmail", message: "Enter an email for your admin dashboard user", default: !seed ? "admin@medusa-test.com" : undefined, validate: (input) => { return typeof input === "string" && input.length > 0 && isEmail(input) ? true : "Please enter a valid email" }, }, ]) const spinner = ora(chalk.white("Setting up project")).start() onProcessTerminated(() => spinner.stop()) // clone repository try { await cloneRepo({ directoryName: projectName, repoUrl, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while setting up your project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Created project directory")).start() if (client) { spinner.text = chalk.white("Creating database...") const dbName = `medusa-${nanoid(4)}` // create postgres database try { await createDb({ client, db: dbName, }) } catch (e) { logMessage({ message: `An error occurred while trying to create your database: ${e}`, type: "error", }) } // format connection string dbConnectionString = formatConnectionString({ user: postgresUsername, password: postgresPassword, host: client.host, db: dbName, }) spinner.succeed(chalk.green(`Database ${dbName} created`)).start() } spinner.text = chalk.white("Preparing project...") // prepare project let inviteToken: string | undefined = undefined try { inviteToken = await prepareProject({ directory: projectName, dbConnectionString, admin: { email: adminEmail, }, seed, spinner, abortController, }) } catch (e: any) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while preparing project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Project Prepared")) // close db connection await client?.end() // start backend logMessage({ message: "Starting Medusa...", }) try { startMedusa({ directory: projectName, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while starting Medusa`, type: "error", }) } waitOn({ resources: ["http://localhost:9000/health"], }).then(() => open( inviteToken ? `http://localhost:9000/app/invite?token=${inviteToken}` : "http://localhost:9000/app" ) ) }
src/commands/create.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/postgres-client.ts", "retrieved_chunk": "import pg from \"pg\"\nconst { Client } = pg\ntype PostgresConnection = {\n user?: string\n password?: string\n}\nexport default async (connect: PostgresConnection) => {\n const client = new Client(connect)\n await client.connect()\n return client", "score": 0.8808746337890625 }, { "filename": "src/utils/create-db.ts", "retrieved_chunk": "import pg from \"pg\"\ntype CreateDbOptions = {\n client: pg.Client\n db: string\n}\nexport default async ({ client, db }: CreateDbOptions) => {\n await client.query(`CREATE DATABASE \"${db}\"`)\n}", "score": 0.8597605228424072 }, { "filename": "src/utils/format-connection-string.ts", "retrieved_chunk": "type ConnectionStringOptions = {\n user?: string\n password?: string\n host?: string\n db: string\n}\nexport default ({ user, password, host, db }: ConnectionStringOptions) => {\n let connection = `postgres://`\n if (user) {\n connection += user", "score": 0.848856508731842 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}`\n )\n let interval: NodeJS.Timer | undefined = undefined\n let fact = \"\"\n if (spinner) {\n spinner.spinner = {\n frames: [\"\"],\n }\n fact = showFact(fact, spinner)\n interval = setInterval(() => {", "score": 0.7968676090240479 }, { "filename": "src/utils/format-connection-string.ts", "retrieved_chunk": " }\n if (password) {\n connection += `:${password}`\n }\n if (user || password) {\n connection += \"@\"\n }\n connection += `${host}/${db}`\n return connection\n}", "score": 0.7864935398101807 } ]
typescript
= await postgresClient({
import axios from "axios"; import { getOptions, Options } from "../../types/Wikipedia"; import * as cheerio from 'cheerio'; import HttpsProxyAgent from 'https-proxy-agent'; import _url from "../../utils/handleUrl"; import useProxies from "../../utils/useProxies"; import https from 'https'; export class Wikipedia { private options: Options = getOptions(); private updateQueries: (name: string, value: any) => void; constructor(options: Options = getOptions()) { let _options = { ...getOptions(), ...options }; function updateQueries(name: string, value: any) { _options.queries = { ..._options.queries, [name]: value } } this.updateQueries = updateQueries; this.options = _options; } useProxies = useProxies; public async get(query: string): Promise<{}> { const __proxy = this.options.proxy; if (__proxy) { this.options.proxies.push(__proxy); this.options.proxy = undefined; } return await this.useProxies(() => this._get(query)); } private async _get(query: string): Promise<{}> { return new Promise(async (resolve, reject) => { const agent = this.options.proxy ? HttpsProxyAgent({ host: this.options.proxy?.host, port: this.options.proxy?.port, auth: this.options.proxy?.auth ? this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password : undefined }) : new https.Agent({ rejectUnauthorized: false }); return await axios(Object.assign({ url: _url(`https://${this.options.language}.wikipedia.org/wiki/${query.replace(/ /g, '_')}`, this.options.queries), method: 'GET', headers: this.
options.headers, }, (agent ? {
proxy: this.options.proxy ? { host: this.options.proxy?.host, port: this.options.proxy?.port, auth: { username: this.options.proxy?.auth?.username, password: this.options.proxy?.auth?.password } } : undefined, httpsAgent: agent } : {}))).then(response => { const html = response.data; const $ = cheerio.load(html); let result: { title?: string, image?: string, description?: { clean?: string, links?: any[], markdown?: string } infobox?: any[] } = { title: undefined, image: undefined, description: { clean: undefined, links: undefined, markdown: undefined }, infobox: undefined }; const fixText = (text: string) => text.replace(/(\r\n|\n|\r)/gm, '').replace(/\s+/g, ' ').trim(); const formatLink = (text: string) => { let _ = text; const regex = /\(([^)]+)\)/; const match = regex.exec(_); if (match) { const m = match[1]; _ = _.replace(`_(${m})`, ''); } _ = _.replace('/wiki/', '').replace(/_/g, '+').toLowerCase(); if (_.endsWith('.')) _ = _.slice(0, _.length - 1); return `https://nustry.com/search?q=${_}` } $('.mw-parser-output').each((i, element) => { const $element = $(element); const $p = $element.find('p').not('.mw-empty-elt'); $p.find('sup').remove(); $p.first().each((i, element) => { const $element = $(element); const text = $element.text(); const links: any[] = []; $element.find('a').each((i, element) => { const $element = $(element); const href = $element.attr('href'); if (href && href.startsWith('/wiki/')) { links.push({ href: href, text: $element.text() }) } }); result.description.clean = fixText(text); result.description.links = links; result.description.markdown = links.reduce((prev, curr) => { return prev.replace(curr.text, `[${curr.text}](${formatLink(curr.href)})`); }, fixText(text)); }); }); $('.infobox').each((i, element) => { const $element = $(element); result.title = $element.find('caption').first().text(); result.image = $element.find('a.image img').first().attr('src'); const $tr = $element.find('tr'); let values: any[] = []; $tr.each((i, element) => { const $element = $(element); const $th = $element.find('th'); const $td = $element.find('td'); $td.find('sup').remove(); const th = $th.text(); if (!th) return; const isHaveLI = $td.find('li').length > 0; const isHaveTable = $td.find('table').length > 0; const isHaveBR = $td.find('br').length > 0; let res: any = [fixText($td.text())]; if (isHaveLI) { const $li = $td.find('li'); const li: string[] = []; $li.each((i, element) => { const $element = $(element); li.push(fixText($element.text())); }); res = li; } else if (isHaveTable) { const $table = $td.find('table'); const table: { [key: string]: any } = {}; $table.each((i, element) => { const $element = $(element); const $tr = $element.find('tr'); $tr.each((i, element) => { const $element = $(element); const $th = $element.find('th'); const $td = $element.find('td'); const th = fixText($th.text()); if (!th) return; table[th] = fixText($td.text()); }); }); res = table; } else if (isHaveBR) { const removeTags = (text: string) => text.replace(/(<([^>]+)>)/gi, ''); res = $td.html().split('<br>').map((text: string) => { return fixText(removeTags(text)); }) } const response = res; const $a = $td.find('a'); const href = $a.attr('href'); let links: any[] = []; if (href) { $a.map((i, element) => { const $element = $(element); links.push({ href: $element.attr('href'), text: $element.text(), isFound: $element.attr('href').startsWith('/wiki/') }); }); } const _ = { label: th, response: { clean: response, markdown: links.reduce((prev, curr) => { return prev.replace(curr.text, `[${curr.text}](${formatLink(curr.href)})`); }, fixText($td.text())) }, links }; values.push(_); }); result['infobox'] = values }); const data = { result, proxy: this.options.proxy, queries: this.options.queries }; return resolve(data); }).catch(error => { return reject(error); }); }); } }
src/engines/lib/Wikipedia.ts
VoidDevsorg-node-scrapper-470e34a
[ { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " port: this.options.proxy?.port,\n auth: this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password\n }) : new https.Agent({\n rejectUnauthorized: false\n });\n return await axios(Object.assign({\n url: _url(`https://www.google.com/search`, this.options.queries),\n method: 'GET',\n headers: this.options.headers\n }, (agent ? {", "score": 0.9390517473220825 }, { "filename": "src/engines/lib/YouTube.ts", "retrieved_chunk": " }) : new https.Agent({\n rejectUnauthorized: false\n });\n return await axios(Object.assign({\n url: _url(`https://www.youtube.com/results`, this.options.queries),\n method: 'GET',\n headers: this.options.headers\n }, (agent ? {\n proxy: this.options.proxy ? {\n host: this.options.proxy?.host,", "score": 0.9248877167701721 }, { "filename": "src/engines/lib/Bing.ts", "retrieved_chunk": " });\n return await axios(Object.assign({\n url: _url(`https://www.bing.com/search`, this.options.queries),\n method: 'GET',\n headers: this.options.headers\n }, (agent ? {\n proxy: this.options.proxy ? {\n host: this.options.proxy?.host,\n port: this.options.proxy?.port,\n auth: {", "score": 0.9124889969825745 }, { "filename": "src/engines/lib/Bing.ts", "retrieved_chunk": " });\n return await axios(Object.assign({\n url: _url(`https://www.bing.com/AS/Suggestions`, this.options.queries),\n method: 'GET',\n headers: this.options.headers\n }, (agent ? {\n proxy: this.options.proxy ? {\n host: this.options.proxy?.host,\n port: this.options.proxy?.port,\n auth: {", "score": 0.9066566824913025 }, { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " return new Promise(async (resolve, reject) => {\n const agent = this.options.proxy ? HttpsProxyAgent({\n host: this.options.proxy?.host,\n port: this.options.proxy?.port,\n auth: this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password\n }) : new https.Agent({\n rejectUnauthorized: false\n });\n return await axios(Object.assign({\n url: _url(`https://www.google.com/complete/search`, this.options.queries),", "score": 0.900300920009613 } ]
typescript
options.headers, }, (agent ? {
import type { Attributes, ModelStatic, Sequelize, Transaction, } from "sequelize"; import type { IAssociation, JSONAnyObject } from "../types"; import { handleUpdateMany, handleUpdateOne } from "./sequelize.patch"; import { handleBulkCreateHasOne, handleBulkCreateMany, handleCreateHasOne, handleCreateMany, } from "./sequelize.post"; export const getValidAttributesAndAssociations = ( attributes: Attributes<any> | Array<Attributes<any>>, associations: Record<string, IAssociation> | undefined, ) => { const externalAssociations: string[] = []; let currentModelAttributes = attributes; const otherAssociationAttributes: JSONAnyObject = {}; if (associations) { const associationsKeys = Object.keys(associations); const attributeKeys = Array.isArray(currentModelAttributes) ? Object.keys(attributes[0]) : Object.keys(attributes); // GET ALL ASSOCIATION ATTRIBUTES AND SEPARATE THEM FROM DATA LEFT associationsKeys.forEach((association) => { if (attributeKeys.includes(association)) { let data: any; if (Array.isArray(currentModelAttributes)) { data = currentModelAttributes.map((attribute: any) => { const { [association]: _, ...attributesleft } = attribute; const otherAttr = otherAssociationAttributes[association] ?? []; otherAssociationAttributes[association] = [...otherAttr, _]; return attributesleft; }); } else { const { [association]: _, ...attributesLeft } = currentModelAttributes; data = attributesLeft; } currentModelAttributes = data; externalAssociations.push(association); } }); } return { otherAssociationAttributes, externalAssociations, currentModelAttributes, }; }; export const handleCreateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: Attributes<any>, transaction: Transaction, modelId: string, primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne": await handleCreateHasOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId }, transaction, primaryKey, ); break; case "BelongsToMany": case "HasMany": await handleCreateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId }, transaction, primaryKey, ); break; default: break; } } }; export const handleBulkCreateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: JSONAnyObject, transaction: Transaction, modelIds: string[], primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne": await handleBulkCreateHasOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelIds }, transaction, primaryKey, ); break; case "BelongsToMany": case "HasMany": await handleBulkCreateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelIds }, transaction, primaryKey, ); break; default: break; } } }; export const handleUpdateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: Attributes<any>, transaction: Transaction, modelId: string, primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne":
await handleUpdateOne( sequelize, {
details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId, }, transaction, primaryKey, ); break; case "HasMany": case "BelongsToMany": await handleUpdateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId, }, transaction, primaryKey, ); break; default: break; } } };
src/sequelize/associations/index.ts
bitovi-sequelize-create-with-associations-908ee8a
[ { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": " sequelize: Sequelize,\n association: IAssociationBody<Array<Record<string, any>>>,\n model: { name: string; id: string },\n transaction: Transaction,\n primaryKey = \"id\",\n): Promise<void> => {\n const modelName = association.details.model;\n const associatedIds = association.attributes.map((data) => data[primaryKey]);\n const [modelInstance, associatedInstances] = await Promise.all([\n sequelize.models[model.name].findByPk(model[primaryKey], {", "score": 0.8978877067565918 }, { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": " primaryKey = \"id\",\n): Promise<void> => {\n const modelName = association.details.model;\n const associatedId = association.attributes?.[primaryKey] || null;\n const [modelInstance, associatedInstance] = await Promise.all([\n sequelize.models[model.name].findByPk(model[primaryKey], {\n transaction,\n }),\n associatedId\n ? sequelize.models[modelName].findByPk(associatedId, {", "score": 0.896501898765564 }, { "filename": "src/sequelize/associations/sequelize.post.ts", "retrieved_chunk": " const modelName = association.details.model;\n const results = await Promise.allSettled(\n association.attributes.map(async (attribute, index) => {\n const isCreate = !attribute[primaryKey];\n if (isCreate) {\n const id = (\n await sequelize.models[association.details.model].create(\n { ...attribute, through: undefined },\n { transaction },\n )", "score": 0.8917623162269592 }, { "filename": "src/sequelize/associations/sequelize.post.ts", "retrieved_chunk": " throw [new Error(\"Not all models were successfully created\")];\n }\n const modelName = association.details.model;\n await Promise.all(\n association.attributes.map(async (attribute, index) => {\n const isCreate = !attribute[primaryKey];\n if (isCreate) {\n const id = (\n await sequelize.models[modelName].create(attribute, {\n transaction,", "score": 0.8784327507019043 }, { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": "import { pluralize } from \"inflection\";\nimport { Op } from \"sequelize\";\nimport type { Sequelize, Transaction } from \"sequelize\";\nimport { NotFoundError } from \"../types\";\nimport type { IAssociationBody } from \"../types\";\nexport const handleUpdateOne = async (\n sequelize: Sequelize,\n association: IAssociationBody<Array<Record<string, any>>>,\n model: { name: string; id: string },\n transaction: Transaction,", "score": 0.8760186433792114 } ]
typescript
await handleUpdateOne( sequelize, {
import inquirer from "inquirer" import slugifyType from "slugify" import chalk from "chalk" import pg from "pg" import createDb from "../utils/create-db.js" import postgresClient from "../utils/postgres-client.js" import cloneRepo from "../utils/clone-repo.js" import prepareProject from "../utils/prepare-project.js" import startMedusa from "../utils/start-medusa.js" import open from "open" import waitOn from "wait-on" import formatConnectionString from "../utils/format-connection-string.js" import ora from "ora" import fs from "fs" import { nanoid } from "nanoid" import isEmailImported from "validator/lib/isEmail.js" import logMessage from "../utils/log-message.js" import onProcessTerminated from "../utils/on-process-terminated.js" import createAbortController, { isAbortError, } from "../utils/create-abort-controller.js" const slugify = slugifyType.default const isEmail = isEmailImported.default type CreateOptions = { repoUrl?: string seed?: boolean } export default async ({ repoUrl = "", seed }: CreateOptions) => { const abortController = createAbortController() const { projectName } = await inquirer.prompt([ { type: "input", name: "projectName", message: "What's the name of your project?", default: "my-medusa-store", filter: (input) => { return slugify(input) }, validate: (input) => { if (!input.length) { return "Please enter a project name" } return fs.existsSync(input) && fs.lstatSync(input).isDirectory() ? "A directory already exists with the same name. Please enter a different project name." : true }, }, ]) let client: pg.Client | undefined let dbConnectionString = "" let postgresUsername = "postgres" let postgresPassword = "" // try to log in with default db username and password try { client = await postgresClient({ user: postgresUsername, password: postgresPassword, }) } catch (e) { // ask for the user's credentials const answers = await inquirer.prompt([ { type: "input", name: "postgresUsername", message: "Enter your Postgres username", default: "postgres", validate: (input) => { return typeof input === "string" && input.length > 0 }, }, { type: "password", name: "postgresPassword", message: "Enter your Postgres password", }, ]) postgresUsername = answers.postgresUsername postgresPassword = answers.postgresPassword try { client = await postgresClient({ user: postgresUsername, password: postgresPassword, }) } catch (e) { logMessage({ message: "Couldn't connect to PostgreSQL. Make sure you have PostgreSQL installed and the credentials you provided are correct.\n\n" + "You can learn how to install PostgreSQL here: https://docs.medusajs.com/development/backend/prepare-environment#postgresql", type: "error", }) } } const { adminEmail } = await inquirer.prompt([ { type: "input", name: "adminEmail", message: "Enter an email for your admin dashboard user", default: !seed ? "admin@medusa-test.com" : undefined, validate: (input) => { return typeof input === "string" && input.length > 0 && isEmail(input) ? true : "Please enter a valid email" }, }, ]) const spinner = ora(chalk.white("Setting up project")).start() onProcessTerminated(() => spinner.stop()) // clone repository try {
await cloneRepo({
directoryName: projectName, repoUrl, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while setting up your project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Created project directory")).start() if (client) { spinner.text = chalk.white("Creating database...") const dbName = `medusa-${nanoid(4)}` // create postgres database try { await createDb({ client, db: dbName, }) } catch (e) { logMessage({ message: `An error occurred while trying to create your database: ${e}`, type: "error", }) } // format connection string dbConnectionString = formatConnectionString({ user: postgresUsername, password: postgresPassword, host: client.host, db: dbName, }) spinner.succeed(chalk.green(`Database ${dbName} created`)).start() } spinner.text = chalk.white("Preparing project...") // prepare project let inviteToken: string | undefined = undefined try { inviteToken = await prepareProject({ directory: projectName, dbConnectionString, admin: { email: adminEmail, }, seed, spinner, abortController, }) } catch (e: any) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while preparing project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Project Prepared")) // close db connection await client?.end() // start backend logMessage({ message: "Starting Medusa...", }) try { startMedusa({ directory: projectName, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while starting Medusa`, type: "error", }) } waitOn({ resources: ["http://localhost:9000/health"], }).then(() => open( inviteToken ? `http://localhost:9000/app/invite?token=${inviteToken}` : "http://localhost:9000/app" ) ) }
src/commands/create.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " )\n },\n })\n spinner?.succeed(chalk.green(\"Ran Migrations\")).start()\n if (admin) {\n // create admin user\n if (spinner) {\n spinner.text = chalk.white(\"Creating an admin user...\")\n }\n await runProcess({", "score": 0.8346890211105347 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " spinner?.succeed(chalk.green(\"Created admin user\")).start()\n }\n if (seed) {\n if (spinner) {\n spinner.text = chalk.white(\"Seeding database...\")\n }\n // check if a seed file exists in the project\n if (!fs.existsSync(path.join(directory, \"data\", \"seed.jsons\"))) {\n spinner\n ?.warn(", "score": 0.8281493186950684 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " spinner.spinner = \"dots\"\n spinner.succeed(chalk.green(\"Installed Dependencies\"))\n spinner.start(chalk.white(\"Running Migrations...\"))\n }\n // run migrations\n await runProcess({\n process: async () => {\n await promiseExec(\n \"npx -y @medusajs/medusa-cli@latest migrations run\",\n execOptions", "score": 0.8113531470298767 }, { "filename": "src/utils/clone-repo.ts", "retrieved_chunk": " repoUrl,\n abortController,\n}: CloneRepoOptions) => {\n await promiseExec(`git clone ${repoUrl || DEFAULT_REPO} ${directoryName}`, {\n signal: abortController?.signal,\n })\n}", "score": 0.8059251308441162 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " chalk.yellow(\n \"Seed file was not found in the project. Skipping seeding...\"\n )\n )\n .start()\n return\n }\n if (spinner) {\n spinner.text = chalk.white(\"Seeding database with demo data...\")\n }", "score": 0.8057358264923096 } ]
typescript
await cloneRepo({
import chalk from "chalk" import fs from "fs" import path from "path" import { Ora } from "ora" import promiseExec from "./promise-exec.js" import { EOL } from "os" import runProcess from "./run-process.js" import getFact from "./get-fact.js" import onProcessTerminated from "./on-process-terminated.js" import boxen from "boxen" type PrepareOptions = { directory: string dbConnectionString: string admin?: { email: string } seed?: boolean spinner?: Ora abortController?: AbortController } const showFact = (lastFact: string, spinner: Ora): string => { const fact = getFact(lastFact) spinner.text = `${boxen(fact, { title: chalk.cyan("Installing Dependencies..."), titleAlignment: "center", textAlignment: "center", padding: 1, margin: 1, float: "center", })}` return fact } export default async ({ directory, dbConnectionString, admin, seed, spinner, abortController, }: PrepareOptions) => { // initialize execution options const execOptions = { cwd: directory, signal: abortController?.signal, } // initialize the invite token to return let inviteToken: string | undefined = undefined // add connection string to project fs.appendFileSync( path.join(directory, `.env`), `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}` ) let interval: NodeJS.Timer | undefined = undefined let fact = "" if (spinner) { spinner.spinner = { frames: [""], } fact = showFact(fact, spinner) interval = setInterval(() => { fact = showFact(fact, spinner) }, 6000) onProcessTerminated(() => clearInterval(interval)) }
await runProcess({
process: async () => { try { await promiseExec(`yarn`, execOptions) } catch (e) { // yarn isn't available // use npm await promiseExec(`npm install`, execOptions) } }, ignoreERESOLVE: true, }) if (interval) { clearInterval(interval) } if (spinner) { spinner.spinner = "dots" spinner.succeed(chalk.green("Installed Dependencies")) spinner.start(chalk.white("Running Migrations...")) } // run migrations await runProcess({ process: async () => { await promiseExec( "npx -y @medusajs/medusa-cli@latest migrations run", execOptions ) }, }) spinner?.succeed(chalk.green("Ran Migrations")).start() if (admin) { // create admin user if (spinner) { spinner.text = chalk.white("Creating an admin user...") } await runProcess({ process: async () => { const proc = await promiseExec( `npx -y @medusajs/medusa-cli@1.3.15-snapshot-20230529090917 user -e ${admin.email} --invite`, execOptions ) // get invite token from stdout const match = proc.stdout.match(/Invite token: (?<token>.+)/) inviteToken = match?.groups?.token }, }) spinner?.succeed(chalk.green("Created admin user")).start() } if (seed) { if (spinner) { spinner.text = chalk.white("Seeding database...") } // check if a seed file exists in the project if (!fs.existsSync(path.join(directory, "data", "seed.jsons"))) { spinner ?.warn( chalk.yellow( "Seed file was not found in the project. Skipping seeding..." ) ) .start() return } if (spinner) { spinner.text = chalk.white("Seeding database with demo data...") } await runProcess({ process: async () => { await promiseExec( `npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join( "data", "seed.json" )}`, execOptions ) }, }) spinner?.succeed(chalk.green("Seeded database with demo data")).start() } return inviteToken }
src/utils/prepare-project.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/run-process.ts", "retrieved_chunk": " do {\n try {\n await process()\n } catch (error) {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error?.code === \"EAGAIN\"\n ) {", "score": 0.803642988204956 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " ? true\n : \"Please enter a valid email\"\n },\n },\n ])\n const spinner = ora(chalk.white(\"Setting up project\")).start()\n onProcessTerminated(() => spinner.stop())\n // clone repository\n try {\n await cloneRepo({", "score": 0.7977503538131714 }, { "filename": "src/utils/get-fact.ts", "retrieved_chunk": " let index = 0\n if (lastFact.length) {\n const lastFactIndex = facts.findIndex((fact) => fact === lastFact)\n if (lastFactIndex !== facts.length - 1) {\n index = lastFactIndex + 1\n }\n }\n return facts[index]\n}", "score": 0.7949614524841309 }, { "filename": "src/utils/on-process-terminated.ts", "retrieved_chunk": "export default (fn: Function) => {\n process.on(\"SIGTERM\", () => fn())\n process.on(\"SIGINT\", () => fn())\n}", "score": 0.7946091294288635 }, { "filename": "src/utils/start-medusa.ts", "retrieved_chunk": " childProcess.stdout?.pipe(process.stdout)\n}", "score": 0.7921578884124756 } ]
typescript
await runProcess({
import type { Attributes, ModelStatic, Sequelize, Transaction, } from "sequelize"; import type { IAssociation, JSONAnyObject } from "../types"; import { handleUpdateMany, handleUpdateOne } from "./sequelize.patch"; import { handleBulkCreateHasOne, handleBulkCreateMany, handleCreateHasOne, handleCreateMany, } from "./sequelize.post"; export const getValidAttributesAndAssociations = ( attributes: Attributes<any> | Array<Attributes<any>>, associations: Record<string, IAssociation> | undefined, ) => { const externalAssociations: string[] = []; let currentModelAttributes = attributes; const otherAssociationAttributes: JSONAnyObject = {}; if (associations) { const associationsKeys = Object.keys(associations); const attributeKeys = Array.isArray(currentModelAttributes) ? Object.keys(attributes[0]) : Object.keys(attributes); // GET ALL ASSOCIATION ATTRIBUTES AND SEPARATE THEM FROM DATA LEFT associationsKeys.forEach((association) => { if (attributeKeys.includes(association)) { let data: any; if (Array.isArray(currentModelAttributes)) { data = currentModelAttributes.map((attribute: any) => { const { [association]: _, ...attributesleft } = attribute; const otherAttr = otherAssociationAttributes[association] ?? []; otherAssociationAttributes[association] = [...otherAttr, _]; return attributesleft; }); } else { const { [association]: _, ...attributesLeft } = currentModelAttributes; data = attributesLeft; } currentModelAttributes = data; externalAssociations.push(association); } }); } return { otherAssociationAttributes, externalAssociations, currentModelAttributes, }; }; export const handleCreateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: Attributes<any>, transaction: Transaction, modelId: string, primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association];
switch (associationDetails.type) {
case "BelongsTo": case "HasOne": await handleCreateHasOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId }, transaction, primaryKey, ); break; case "BelongsToMany": case "HasMany": await handleCreateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId }, transaction, primaryKey, ); break; default: break; } } }; export const handleBulkCreateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: JSONAnyObject, transaction: Transaction, modelIds: string[], primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne": await handleBulkCreateHasOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelIds }, transaction, primaryKey, ); break; case "BelongsToMany": case "HasMany": await handleBulkCreateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelIds }, transaction, primaryKey, ); break; default: break; } } }; export const handleUpdateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: Attributes<any>, transaction: Transaction, modelId: string, primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne": await handleUpdateOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId, }, transaction, primaryKey, ); break; case "HasMany": case "BelongsToMany": await handleUpdateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId, }, transaction, primaryKey, ); break; default: break; } } };
src/sequelize/associations/index.ts
bitovi-sequelize-create-with-associations-908ee8a
[ { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": " sequelize: Sequelize,\n association: IAssociationBody<Array<Record<string, any>>>,\n model: { name: string; id: string },\n transaction: Transaction,\n primaryKey = \"id\",\n): Promise<void> => {\n const modelName = association.details.model;\n const associatedIds = association.attributes.map((data) => data[primaryKey]);\n const [modelInstance, associatedInstances] = await Promise.all([\n sequelize.models[model.name].findByPk(model[primaryKey], {", "score": 0.9260684251785278 }, { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": " primaryKey = \"id\",\n): Promise<void> => {\n const modelName = association.details.model;\n const associatedId = association.attributes?.[primaryKey] || null;\n const [modelInstance, associatedInstance] = await Promise.all([\n sequelize.models[model.name].findByPk(model[primaryKey], {\n transaction,\n }),\n associatedId\n ? sequelize.models[modelName].findByPk(associatedId, {", "score": 0.9077224731445312 }, { "filename": "src/sequelize/extended.ts", "retrieved_chunk": " await handleCreateAssociations(\n this.sequelize,\n this,\n externalAssociations,\n associations as Record<string, IAssociation>,\n attributes,\n transaction,\n modelData?.[modelPrimaryKey],\n modelPrimaryKey,\n );", "score": 0.887538492679596 }, { "filename": "src/sequelize/associations/sequelize.post.ts", "retrieved_chunk": " }\n let joinId: string | undefined;\n const isCreate = !association.attributes[primaryKey];\n if (isCreate) {\n const model = await sequelize.models[modelName].create(\n association.attributes,\n {\n transaction,\n },\n );", "score": 0.88515305519104 }, { "filename": "src/sequelize/associations/sequelize.post.ts", "retrieved_chunk": " throw [new Error(\"Not all models were successfully created\")];\n }\n const modelName = association.details.model;\n await Promise.all(\n association.attributes.map(async (attribute, index) => {\n const isCreate = !attribute[primaryKey];\n if (isCreate) {\n const id = (\n await sequelize.models[modelName].create(attribute, {\n transaction,", "score": 0.8847132921218872 } ]
typescript
switch (associationDetails.type) {
import chalk from "chalk" import fs from "fs" import path from "path" import { Ora } from "ora" import promiseExec from "./promise-exec.js" import { EOL } from "os" import runProcess from "./run-process.js" import getFact from "./get-fact.js" import onProcessTerminated from "./on-process-terminated.js" import boxen from "boxen" type PrepareOptions = { directory: string dbConnectionString: string admin?: { email: string } seed?: boolean spinner?: Ora abortController?: AbortController } const showFact = (lastFact: string, spinner: Ora): string => { const fact = getFact(lastFact) spinner.text = `${boxen(fact, { title: chalk.cyan("Installing Dependencies..."), titleAlignment: "center", textAlignment: "center", padding: 1, margin: 1, float: "center", })}` return fact } export default async ({ directory, dbConnectionString, admin, seed, spinner, abortController, }: PrepareOptions) => { // initialize execution options const execOptions = { cwd: directory, signal: abortController?.signal, } // initialize the invite token to return let inviteToken: string | undefined = undefined // add connection string to project fs.appendFileSync( path.join(directory, `.env`), `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}` ) let interval: NodeJS.Timer | undefined = undefined let fact = "" if (spinner) { spinner.spinner = { frames: [""], } fact = showFact(fact, spinner) interval = setInterval(() => { fact = showFact(fact, spinner) }, 6000) onProcessTerminated(() => clearInterval(interval)) } await runProcess({ process: async () => { try {
await promiseExec(`yarn`, execOptions) } catch (e) {
// yarn isn't available // use npm await promiseExec(`npm install`, execOptions) } }, ignoreERESOLVE: true, }) if (interval) { clearInterval(interval) } if (spinner) { spinner.spinner = "dots" spinner.succeed(chalk.green("Installed Dependencies")) spinner.start(chalk.white("Running Migrations...")) } // run migrations await runProcess({ process: async () => { await promiseExec( "npx -y @medusajs/medusa-cli@latest migrations run", execOptions ) }, }) spinner?.succeed(chalk.green("Ran Migrations")).start() if (admin) { // create admin user if (spinner) { spinner.text = chalk.white("Creating an admin user...") } await runProcess({ process: async () => { const proc = await promiseExec( `npx -y @medusajs/medusa-cli@1.3.15-snapshot-20230529090917 user -e ${admin.email} --invite`, execOptions ) // get invite token from stdout const match = proc.stdout.match(/Invite token: (?<token>.+)/) inviteToken = match?.groups?.token }, }) spinner?.succeed(chalk.green("Created admin user")).start() } if (seed) { if (spinner) { spinner.text = chalk.white("Seeding database...") } // check if a seed file exists in the project if (!fs.existsSync(path.join(directory, "data", "seed.jsons"))) { spinner ?.warn( chalk.yellow( "Seed file was not found in the project. Skipping seeding..." ) ) .start() return } if (spinner) { spinner.text = chalk.white("Seeding database with demo data...") } await runProcess({ process: async () => { await promiseExec( `npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join( "data", "seed.json" )}`, execOptions ) }, }) spinner?.succeed(chalk.green("Seeded database with demo data")).start() } return inviteToken }
src/utils/prepare-project.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/run-process.ts", "retrieved_chunk": " do {\n try {\n await process()\n } catch (error) {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error?.code === \"EAGAIN\"\n ) {", "score": 0.8285365104675293 }, { "filename": "src/utils/promise-exec.ts", "retrieved_chunk": "import { exec } from \"child_process\"\nimport util from \"util\"\nconst promiseExec = util.promisify(exec)\nexport default promiseExec", "score": 0.817145824432373 }, { "filename": "src/utils/on-process-terminated.ts", "retrieved_chunk": "export default (fn: Function) => {\n process.on(\"SIGTERM\", () => fn())\n process.on(\"SIGINT\", () => fn())\n}", "score": 0.8122586011886597 }, { "filename": "src/utils/start-medusa.ts", "retrieved_chunk": " childProcess.stdout?.pipe(process.stdout)\n}", "score": 0.8075758814811707 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " ? true\n : \"Please enter a valid email\"\n },\n },\n ])\n const spinner = ora(chalk.white(\"Setting up project\")).start()\n onProcessTerminated(() => spinner.stop())\n // clone repository\n try {\n await cloneRepo({", "score": 0.8023667335510254 } ]
typescript
await promiseExec(`yarn`, execOptions) } catch (e) {
import type { Model, CreateOptions, Attributes, UpdateOptions, } from "sequelize"; import type { Col, Fn, Literal, MakeNullishOptional, } from "sequelize/types/utils"; import { getValidAttributesAndAssociations, handleBulkCreateAssociations, handleCreateAssociations, handleUpdateAssociations, } from "./associations"; import { UnexpectedValueError } from "./types"; import type { IAssociation } from "./types"; type AssociationLookup = Record<string, Record<string, IAssociation>>; let associationsLookup: AssociationLookup; function calculateAssociationProp(associations) { const result = {}; Object.keys(associations).forEach((key) => { const association = {}; let propertyName; if (associations[key].hasOwnProperty("options")) { const { associationType, target, foreignKey, throughModel } = associations[key]; propertyName = key.toLocaleLowerCase(); association[propertyName] = { type: associationType, key: foreignKey, model: target.name, joinTable: throughModel, }; } result[propertyName] = association[propertyName]; }); return result; } export function getLookup(sequelize): AssociationLookup { //TODO: Fix associations lookup being static /* if (!associationsLookup) { */ const lookup: any = {}; const models = sequelize.models; const modelKeys = Object.keys(models); modelKeys.forEach((key) => { const associations = calculateAssociationProp(models[key].associations); lookup[key] = associations; }); associationsLookup = lookup; return associationsLookup; } export const extendSequelize = (SequelizeClass: any) => { const origCreate = SequelizeClass.Model.create; const origUpdate = SequelizeClass.Model.update; const origBulkCreate = SequelizeClass.Model.bulkCreate; SequelizeClass.Model.create = async function < M extends Model, O extends CreateOptions<Attributes<M>> = CreateOptions<Attributes<M>>, >( attributes: MakeNullishOptional<M["_creationAttributes"]> | undefined, options?: O, ) { const { sequelize } = this.options; const associations = getLookup(sequelize)[this.name]; const modelPrimaryKey = this.primaryKeyAttribute; let modelData: | undefined | (O extends { returning: false } | { ignoreDuplicates: true } ? void : M); const { externalAssociations, currentModelAttributes } = getValidAttributesAndAssociations(attributes, associations); // If there are no associations, create the model with all attributes. if (!externalAssociations.length) { return origCreate.apply(this, [attributes, options]); } const transaction = options?.transaction ?? (await this.sequelize.transaction()); try { // create the model first if it does not exist if (!modelData) { modelData = await origCreate.apply(this, [ currentModelAttributes, { transaction }, ]); } await handleCreateAssociations( this.sequelize, this, externalAssociations, associations as Record<string, IAssociation>, attributes, transaction, modelData?.[modelPrimaryKey], modelPrimaryKey, ); !options?.transaction && (await transaction.commit()); } catch (error) { !options?.transaction && (await transaction.rollback()); throw error; } return modelData; }; SequelizeClass.Model.bulkCreate = async function < M extends Model, O extends CreateOptions<Attributes<M>> = CreateOptions<Attributes<M>>, >( attributes: Array<MakeNullishOptional<M["_creationAttributes"]>>, options?: O, ) { const { sequelize } = this.options; const associations = getLookup(sequelize)[this.name]; const modelPrimaryKey = this.primaryKeyAttribute; let modelData: | undefined | Array< O extends { returning: false } | { ignoreDuplicates: true } ? void : M >; const { otherAssociationAttributes, externalAssociations, currentModelAttributes, } = getValidAttributesAndAssociations(attributes, associations); // If there are no associations, create the model with all attributes. if (!externalAssociations.length) { return origBulkCreate.apply(this, [attributes, options]); } const transaction = options?.transaction ?? (await this.sequelize.transaction()); try { // create the model first if it does not exist if (!modelData) { modelData = await origBulkCreate.apply(this, [ currentModelAttributes, { transaction }, ]); } const modelIds = modelData?.map((data) => data.getDataValue(modelPrimaryKey), ) as string[]; await handleBulkCreateAssociations( this.sequelize, this, externalAssociations, associations as Record<string, IAssociation>, otherAssociationAttributes, transaction, modelIds, modelPrimaryKey, ); !options?.transaction && (await transaction.commit()); } catch (error) { !options?.transaction && (await transaction.rollback()); throw error; } return modelData; }; SequelizeClass.Model.update = async function <M extends Model<any, any>>( attributes: { [key in keyof Attributes<M>]?: | Fn | Col | Literal | Attributes<M>[key] | undefined; }, ops: Omit<UpdateOptions<Attributes<M>>, "returning"> & { returning: Exclude< UpdateOptions<Attributes<M>>["returning"], undefined | false >; }, ) { const { sequelize } = this.options; const associations = getLookup(sequelize)[this.name]; const modelPrimaryKey = this.primaryKeyAttribute; const modelId = ops.where?.[modelPrimaryKey]; let modelUpdateData: [affectedCount: number, affectedRows: M[]] | undefined; const { externalAssociations, currentModelAttributes } = getValidAttributesAndAssociations(attributes, associations); // If there are no associations, create the model with all attributes. if (!externalAssociations.length) { return origUpdate.apply(this, [attributes, ops]); } else if (!modelId) { throw [ new
UnexpectedValueError({
detail: "Only updating by the primary key is supported", }), ]; } const transaction = await this.sequelize.transaction(); try { if (!modelUpdateData) { modelUpdateData = await origUpdate.apply(this, [ currentModelAttributes, { ...ops, transaction, }, ]); } await handleUpdateAssociations( this.sequelize, this, externalAssociations, associations as Record<string, IAssociation>, attributes, transaction, modelId, modelPrimaryKey, ); !ops?.transaction && (await transaction.commit()); } catch (error) { !ops?.transaction && (await transaction.rollback()); throw error; } return modelUpdateData; }; };
src/sequelize/extended.ts
bitovi-sequelize-create-with-associations-908ee8a
[ { "filename": "src/sequelize/associations/index.ts", "retrieved_chunk": " modelId: string,\n primaryKey = \"id\",\n): Promise<void> => {\n for (const association of validAssociations) {\n const associationDetails = associations[association];\n const associationAttribute = attributes[association];\n switch (associationDetails.type) {\n case \"BelongsTo\":\n case \"HasOne\":\n await handleUpdateOne(", "score": 0.857915997505188 }, { "filename": "src/sequelize/associations/index.ts", "retrieved_chunk": " handleBulkCreateMany,\n handleCreateHasOne,\n handleCreateMany,\n} from \"./sequelize.post\";\nexport const getValidAttributesAndAssociations = (\n attributes: Attributes<any> | Array<Attributes<any>>,\n associations: Record<string, IAssociation> | undefined,\n) => {\n const externalAssociations: string[] = [];\n let currentModelAttributes = attributes;", "score": 0.8493044972419739 }, { "filename": "src/sequelize/associations/index.ts", "retrieved_chunk": " details: associationDetails,\n attributes: associationAttribute,\n },\n { name: model.name, id: modelIds },\n transaction,\n primaryKey,\n );\n break;\n default:\n break;", "score": 0.8483248949050903 }, { "filename": "src/sequelize/associations/index.ts", "retrieved_chunk": " }\n }\n};\nexport const handleUpdateAssociations = async (\n sequelize: Sequelize,\n model: ModelStatic<any>,\n validAssociations: string[],\n associations: Record<string, IAssociation>,\n attributes: Attributes<any>,\n transaction: Transaction,", "score": 0.8446272611618042 }, { "filename": "src/sequelize/associations/index.ts", "retrieved_chunk": " currentModelAttributes,\n };\n};\nexport const handleCreateAssociations = async (\n sequelize: Sequelize,\n model: ModelStatic<any>,\n validAssociations: string[],\n associations: Record<string, IAssociation>,\n attributes: Attributes<any>,\n transaction: Transaction,", "score": 0.8414124250411987 } ]
typescript
UnexpectedValueError({
import {By, until} from 'selenium-webdriver'; import {createDriver} from '../driver'; import {elementGetter} from './elements'; import {isExcludedByTitle} from './isExcludedByTitle'; import {TJob} from '../../types'; export async function jobCollector(locations: string[], keyword: string) { const driver = await createDriver(); const jobs: TJob[] = []; try { for (const location of locations) { const keywords = encodeURI(keyword); await driver.get( `https://www.linkedin.com/jobs/search?keywords=${keywords}&location=${location}&f_TPR=r86400&trk=public_jobs_jobs-search-bar_search-submit&position=1&pageNum=0`, ); /* **FOR Getting All Job Element** const jobCount = await driver.findElement(By.className('results-context-header__job-count'))?.getText(); Math.ceil(+jobCount) with Select on Show More Button! */ for (let i = 0; i < 4; i++) { // Scroll to the bottom of the page await driver.executeScript('window.scrollTo(0, document.body.scrollHeight);'); // Wait for new content to load await driver.wait(until.elementLocated(By.css('ul.jobs-search__results-list>li'))); // Wait for some additional time to allow the page to fully render await driver.sleep(3000); } // Get job listings console.log('before listing...'); const jobElements = await driver.findElements(By.css('ul.jobs-search__results-list>li')); console.log(jobElements.length, `count of jobs for ${location}`); for (const el of jobElements) { const title = await elementGetter({el, selector: 'h3.base-search-card__title'}); const company = await elementGetter({ el, selector: '[data-tracking-control-name="public_jobs_jserp-result_job-search-card-subtitle"]', }); const location = await elementGetter({el, selector: 'span.job-search-card__location'}); const time = await elementGetter({el, selector: 'time'}); const link = await elementGetter({el, selector: 'a.base-card__full-link', method: 'attribute', attr: 'href'}); if
(isExcludedByTitle(title.toLocaleLowerCase()) && link.length > 1) {
jobs.push({ title: title.toLocaleLowerCase(), company, location, time, link, visa: false, description: '', source: 'Linkedin', }); } else { console.log('filtered by title:', title); } } } return jobs; } catch (err) { console.log(err); } finally { // Close the browser await driver?.quit(); } }
src/modules/scraper/jobCollector.ts
sharifiniaa-job-scraper-26ab436
[ { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": " const filteredJobs: TJob[] = [];\n for (const job of jobItems) {\n console.log('finding keywords ...', job.link);\n await driver.get(job.link);\n await jobDescriptionClicker(driver);\n await driver.sleep(3000);\n const element = await driver.findElement(By.className('core-section-container'));\n const text = await element.getText();\n await driver.sleep(3000);\n const companyName = text.toLocaleLowerCase();", "score": 0.8531827330589294 }, { "filename": "src/modules/scraper/elements.ts", "retrieved_chunk": " const element = await el.findElement(By.css(selector));\n name = method == 'text' ? await element.getText() : await element.getAttribute(attr);\n } catch {\n name = '';\n } finally {\n return name;\n }\n}\nexport async function jobDescriptionClicker(el: WebDriver) {\n try {", "score": 0.8520320653915405 }, { "filename": "src/modules/scraper/elements.ts", "retrieved_chunk": "import {By, WebDriver, WebElement} from 'selenium-webdriver';\ntype TElementGetter = {\n el: WebElement;\n selector: string;\n method?: 'text' | 'attribute';\n attr?: string;\n};\nexport async function elementGetter({el, selector, method = 'text', attr = 'href'}: TElementGetter) {\n let name = '';\n try {", "score": 0.8375206589698792 }, { "filename": "src/modules/scraper/getDescription.ts", "retrieved_chunk": "}\nexport async function scrapDescription(link: string) {\n const driver = await createDriver();\n try {\n await driver.get(link);\n await jobDescriptionClicker(driver);\n await driver.sleep(5000);\n const element = await driver.findElement(By.className('core-section-container'));\n const text = await element.getText();\n const editedText = cleanedText(text).substring(0, 3500);", "score": 0.83699631690979 }, { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": " const haveVisa =\n (await prisma.companies.findUnique({where: {name: companyName}})) ||\n text.toLocaleLowerCase().includes('visa sponsorship');\n job.visa = !!haveVisa;\n job.description = cleanedText(text).substring(0, 300) + '...';\n filteredJobs.push(job);\n const handles = await driver.getAllWindowHandles();\n for (let i = 1; i < handles.length; i++) {\n await driver.switchTo().window(handles[i]);\n await driver.close();", "score": 0.8349162936210632 } ]
typescript
(isExcludedByTitle(title.toLocaleLowerCase()) && link.length > 1) {
import {cleanedText} from '../../helper/cleanedText'; import {createDriver} from '../driver'; import {jobDescriptionClicker} from './elements'; import {By} from 'selenium-webdriver'; import prisma from '../db'; export async function getDescription(id: number) { try { const job = await prisma.job.findUnique({ where: { id, }, }); if (!job) { console.log(`Job ${id} is not exist in db`); return null; } if (job.description) { return job.description; } const description = await scrapDescription(job.link); const updatedJob = await prisma.job.update({ where: {id}, data: { description, }, }); return updatedJob?.description; } catch (err) { console.log(err); } } export async function scrapDescription(link: string) { const driver = await createDriver(); try { await driver.get(link); await jobDescriptionClicker(driver); await driver.sleep(5000); const element = await driver.findElement(By.className('core-section-container')); const text = await element.getText(); const editedText
= cleanedText(text).substring(0, 3500);
return editedText; } catch (err) { console.log(err); } finally { driver?.quit(); } }
src/modules/scraper/getDescription.ts
sharifiniaa-job-scraper-26ab436
[ { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": " const filteredJobs: TJob[] = [];\n for (const job of jobItems) {\n console.log('finding keywords ...', job.link);\n await driver.get(job.link);\n await jobDescriptionClicker(driver);\n await driver.sleep(3000);\n const element = await driver.findElement(By.className('core-section-container'));\n const text = await element.getText();\n await driver.sleep(3000);\n const companyName = text.toLocaleLowerCase();", "score": 0.8629099130630493 }, { "filename": "src/modules/scraper/elements.ts", "retrieved_chunk": " const element = await el.findElement(By.css(selector));\n name = method == 'text' ? await element.getText() : await element.getAttribute(attr);\n } catch {\n name = '';\n } finally {\n return name;\n }\n}\nexport async function jobDescriptionClicker(el: WebDriver) {\n try {", "score": 0.8487229347229004 }, { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": "import {TJob} from 'types';\nimport {createDriver} from '../driver';\nimport {By} from 'selenium-webdriver';\nimport prisma from '../db';\nimport {cleanedText} from '../../helper/cleanedText';\nimport {jobDescriptionClicker} from './elements';\nexport async function filterKeyword(jobs: TJob[]): Promise<TJob[]> {\n const driver = await createDriver();\n const jobItems = jobs.filter(job => job.link.length > 1);\n try {", "score": 0.8459852933883667 }, { "filename": "src/modules/scraper/jobCollector.ts", "retrieved_chunk": " const link = await elementGetter({el, selector: 'a.base-card__full-link', method: 'attribute', attr: 'href'});\n if (isExcludedByTitle(title.toLocaleLowerCase()) && link.length > 1) {\n jobs.push({\n title: title.toLocaleLowerCase(),\n company,\n location,\n time,\n link,\n visa: false,\n description: '',", "score": 0.8452459573745728 }, { "filename": "src/modules/scraper/jobCollector.ts", "retrieved_chunk": " const jobElements = await driver.findElements(By.css('ul.jobs-search__results-list>li'));\n console.log(jobElements.length, `count of jobs for ${location}`);\n for (const el of jobElements) {\n const title = await elementGetter({el, selector: 'h3.base-search-card__title'});\n const company = await elementGetter({\n el,\n selector: '[data-tracking-control-name=\"public_jobs_jserp-result_job-search-card-subtitle\"]',\n });\n const location = await elementGetter({el, selector: 'span.job-search-card__location'});\n const time = await elementGetter({el, selector: 'time'});", "score": 0.8387665748596191 } ]
typescript
= cleanedText(text).substring(0, 3500);
import {cleanedText} from '../../helper/cleanedText'; import {createDriver} from '../driver'; import {jobDescriptionClicker} from './elements'; import {By} from 'selenium-webdriver'; import prisma from '../db'; export async function getDescription(id: number) { try { const job = await prisma.job.findUnique({ where: { id, }, }); if (!job) { console.log(`Job ${id} is not exist in db`); return null; } if (job.description) { return job.description; } const description = await scrapDescription(job.link); const updatedJob = await prisma.job.update({ where: {id}, data: { description, }, }); return updatedJob?.description; } catch (err) { console.log(err); } } export async function scrapDescription(link: string) { const driver = await createDriver(); try { await driver.get(link); await jobDescriptionClicker(driver); await driver.sleep(5000); const element = await driver.findElement(By.className('core-section-container')); const text = await element.getText(); const
editedText = cleanedText(text).substring(0, 3500);
return editedText; } catch (err) { console.log(err); } finally { driver?.quit(); } }
src/modules/scraper/getDescription.ts
sharifiniaa-job-scraper-26ab436
[ { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": " const filteredJobs: TJob[] = [];\n for (const job of jobItems) {\n console.log('finding keywords ...', job.link);\n await driver.get(job.link);\n await jobDescriptionClicker(driver);\n await driver.sleep(3000);\n const element = await driver.findElement(By.className('core-section-container'));\n const text = await element.getText();\n await driver.sleep(3000);\n const companyName = text.toLocaleLowerCase();", "score": 0.8637886643409729 }, { "filename": "src/modules/scraper/elements.ts", "retrieved_chunk": " const element = await el.findElement(By.css(selector));\n name = method == 'text' ? await element.getText() : await element.getAttribute(attr);\n } catch {\n name = '';\n } finally {\n return name;\n }\n}\nexport async function jobDescriptionClicker(el: WebDriver) {\n try {", "score": 0.8480342626571655 }, { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": "import {TJob} from 'types';\nimport {createDriver} from '../driver';\nimport {By} from 'selenium-webdriver';\nimport prisma from '../db';\nimport {cleanedText} from '../../helper/cleanedText';\nimport {jobDescriptionClicker} from './elements';\nexport async function filterKeyword(jobs: TJob[]): Promise<TJob[]> {\n const driver = await createDriver();\n const jobItems = jobs.filter(job => job.link.length > 1);\n try {", "score": 0.8474880456924438 }, { "filename": "src/modules/scraper/jobCollector.ts", "retrieved_chunk": " const link = await elementGetter({el, selector: 'a.base-card__full-link', method: 'attribute', attr: 'href'});\n if (isExcludedByTitle(title.toLocaleLowerCase()) && link.length > 1) {\n jobs.push({\n title: title.toLocaleLowerCase(),\n company,\n location,\n time,\n link,\n visa: false,\n description: '',", "score": 0.8467137217521667 }, { "filename": "src/modules/scraper/jobCollector.ts", "retrieved_chunk": " const jobElements = await driver.findElements(By.css('ul.jobs-search__results-list>li'));\n console.log(jobElements.length, `count of jobs for ${location}`);\n for (const el of jobElements) {\n const title = await elementGetter({el, selector: 'h3.base-search-card__title'});\n const company = await elementGetter({\n el,\n selector: '[data-tracking-control-name=\"public_jobs_jserp-result_job-search-card-subtitle\"]',\n });\n const location = await elementGetter({el, selector: 'span.job-search-card__location'});\n const time = await elementGetter({el, selector: 'time'});", "score": 0.8395906090736389 } ]
typescript
editedText = cleanedText(text).substring(0, 3500);
import { parser } from "./parser.js"; import { writer } from "./writer.js"; import { objectToDom } from "./objectToDom.js"; import { toObject } from "./toObject.js"; import type { Xmltv, XmltvAudio, XmltvChannel, XmltvCreditImage, XmltvCredits, XmltvDom, XmltvDisplayName, XmltvEpisodeNumber, XmltvIcon, XmltvImage, XmltvLength, XmltvPerson, XmltvPreviouslyShown, XmltvProgramme, XmltvRating, XmltvReview, XmltvStarRating, XmltvSubtitle, XmltvUrl, XmltvVideo, } from "./types"; import { addAttributeTranslation, addTagTranslation, } from "./xmltvTranslations.js"; type ParseXmltvOptions = { asDom: boolean; }; type WriteXmltvOptions = { fromDom: boolean; }; /** * parseXmltv * * Parses an xmltv file and returns an `Xmltv` object or a DOM tree * * @param xmltvString The xmltv file content as a string * @param options Options to parse the xmltv file * @param options.asDom If true, the xmltv file will be returned as a DOM tree */ function parseXmltv( xmltvString: string, options: ParseXmltvOptions & { asDom: true } ): XmltvDom; function parseXmltv( xmltvString: string, options: ParseXmltvOptions & { asDom: false } ): XmltvDom; function parseXmltv(xmltvString: string): Xmltv; function parseXmltv( xmltvString: string, options: ParseXmltvOptions = { asDom: false } ): Xmltv | XmltvDom { const parsed = parser(xmltvString); if (options.asDom) { return parsed; }
return <Xmltv>toObject(parsed);
} /** * writeXmltv * * Writes an `Xmltv` object or a DOM tree to an xmltv string * * @param xmltv The `Xmltv` object or a DOM tree * @param options Options to write the xmltv file * @param options.fromDom If true, the xmltv file will be written from a DOM tree * @returns The xmltv file content as a string * @throws If `options.fromDom` is true and `xmltv` is an `Xmltv` object */ function writeXmltv( xmltv: XmltvDom, options: WriteXmltvOptions & { fromDom: true } ): string; function writeXmltv( xmltv: Xmltv, options: WriteXmltvOptions & { fromDom: false } ): string; function writeXmltv(xmltv: Xmltv): string; function writeXmltv( xmltv: Xmltv | XmltvDom, options: WriteXmltvOptions = { fromDom: false } ): string { if (options.fromDom) { if (typeof xmltv === "object" && !Array.isArray(xmltv)) { throw new Error( "Cannot write XMLTV from a DOM object that has been converted to an object" ); } return writer(xmltv); } const dom = objectToDom(xmltv); return writer(dom); } export { parseXmltv, writeXmltv, writer, parser, objectToDom, addTagTranslation, addAttributeTranslation, }; export type { Xmltv, XmltvChannel, XmltvDisplayName, XmltvProgramme, XmltvAudio, XmltvCreditImage, XmltvCredits, XmltvEpisodeNumber, XmltvIcon, XmltvImage, XmltvLength, XmltvPerson, XmltvPreviouslyShown, XmltvRating, XmltvReview, XmltvStarRating, XmltvSubtitle, XmltvUrl, XmltvVideo, };
src/main.ts
ektotv-xmltv-03be15c
[ { "filename": "src/parser.ts", "retrieved_chunk": " * Based on the original work of Tobias Nickel (txml)\n * I removed the more generic parts of the parser to focus on working with the XMLTV format\n * Outputs a more fluent object structure matching the Xmltv types\n */\nexport function parser(xmltvString: string): XmltvDom {\n let pos = 0;\n const openBracket = \"<\";\n const closeBracket = \">\";\n const openBracketCC = openBracket.charCodeAt(0);\n const closeBracketCC = closeBracket.charCodeAt(0);", "score": 0.8794900178909302 }, { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type XmltvDom = XmltvDomNode[];", "score": 0.869986355304718 }, { "filename": "src/types.ts", "retrieved_chunk": "export type XmltvDomNode =\n | {\n tagName: string;\n attributes: Record<string, any>;\n children: Array<XmltvDomNode | string>;\n }\n | string;\n/**\n * A collection of XMLTV DOM nodes to form a valid XMLTV document\n *", "score": 0.8620713949203491 }, { "filename": "src/parser.ts", "retrieved_chunk": "import { XmltvDom } from \"./types\";\n/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Tobias Nickel\n *\n * Copyright (c) 2023 Liam Potter\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n * and associated documentation files (the \"Software\"), to deal in the Software without restriction,", "score": 0.8611049652099609 }, { "filename": "src/parser.ts", "retrieved_chunk": " }\n return xmltvString.slice(start, pos);\n }\n function parseNode() {\n pos++;\n const tagName = parseName();\n const attributes: Record<string, any> = {};\n let children: XmltvDom = [];\n // parsing attributes\n while (xmltvString.charCodeAt(pos) !== closeBracketCC && xmltvString[pos]) {", "score": 0.8556916117668152 } ]
typescript
return <Xmltv>toObject(parsed);
import type { Xmltv, XmltvDomNode } from "./types"; import { xmltvTimestampToUtcDate } from "./utils.js"; import { xmltvAttributeTranslations, xmltvTagTranslations, } from "./xmltvTranslations.js"; import type { XmltvTags, XmltvAttributes } from "./xmltvTagsAttributes.js"; const questionMarkCC = "?".charCodeAt(0); /** * Elements that can only be used once wherever they appear. * eg <credits> can only be used once in a <programme> element * but <actor> can be used multiple times in a <credits> element */ const singleUseElements: XmltvTags[] = [ "credits", "date", "language", "orig-language", "length", "country", "previously-shown", "premiere", "last-chance", "new", "video", "audio", // Sub-elements of 'video' "present", "colour", "aspect", "quality", // Sub-elements of 'audio' "present", "stereo", //sub-elements of rating and star rating "value", ]; /** * Elements that do not have children or attributes so can be rendered as a scalar * * eg <date>2020-01-01</date> should render as * { date: "2020-01-01" } * instead of * { date: { _value: "2020-01-01" } } */ const elementsAsScalar: XmltvTags[] = [ "date", "value", "aspect", "present", "colour", "quality", "stereo", ]; /** * Convert an XmltvDom tree to a plain object * * @param children The XmltvDom tree to convert */ type Out = Record<string, any>; export function toObject( children: any[],
parent: XmltvDomNode = { tagName: "tv", attributes: {}, children: [] }
): Out | boolean | string | Xmltv { let out: Out = {}; if (!children.length) { return out; } if ( children.length === 1 && typeof children[0] === "string" && (children[0] === "yes" || children[0] === "no") ) { return children[0] === "yes"; } if ( children.length === 1 && typeof children[0] === "string" && typeof parent !== "string" ) { if (Object.keys(parent.attributes).length) { return { _value: children[0], }; } return children[0]; } // map each object for (let i = 0, n = children.length; i < n; i++) { let child = children[i]; if ( typeof parent !== "string" && parent.tagName === "actor" && typeof child === "string" ) { out._value = child; } if (typeof child !== "object") { continue; } if (child.tagName.charCodeAt(0) === questionMarkCC) continue; if (child.tagName === "new") { out[child.tagName] = true; continue; } if (child.tagName === "tv") { out = {}; } const translatedName = xmltvTagTranslations.get(child.tagName) || child.tagName; if ( !out[translatedName] && singleUseElements.indexOf(child.tagName) === -1 ) { out[translatedName] = []; } let kids: any = toObject(child.children || [], child); if (Object.keys(child.attributes).length) { if (!Array.isArray(kids)) { if (child.attributes.size) { child.attributes.size = Number(child.attributes.size); } if (translatedName === "programmes") { if (child.attributes.stop) { child.attributes.stop = xmltvTimestampToUtcDate( child.attributes.stop ); } if (child.attributes["pdc-start"]) { child.attributes["pdc-start"] = xmltvTimestampToUtcDate( child.attributes["pdc-start"] ); } if (child.attributes["vps-start"]) { child.attributes["vps-start"] = xmltvTimestampToUtcDate( child.attributes["vps-start"] ); } } else if (translatedName === "icon") { if (child.attributes.width) { child.attributes.width = Number(child.attributes.width); } if (child.attributes.height) { child.attributes.height = Number(child.attributes.height); } } else if (child.attributes.units) { kids._value = Number(kids._value); } else if (child.attributes.guest) { child.attributes.guest = child.attributes.guest === "yes"; } if (child.attributes.date) { child.attributes.date = xmltvTimestampToUtcDate( child.attributes.date ); } if (child.attributes.start) { child.attributes.start = xmltvTimestampToUtcDate( child.attributes.start ); } const translatedAttributes = Object.keys(child.attributes).reduce( (acc: Record<string, string>, key: string) => { acc[xmltvAttributeTranslations.get(key as XmltvAttributes) || key] = child.attributes[key]; return acc; }, {} ); Object.assign(kids, translatedAttributes); } } if (translatedName === "subtitles") { if (typeof kids.language === "string") { kids.language = { _value: kids.language }; } out[translatedName].push(kids); continue; } if (translatedName === "tv") { out = kids; continue; } if (translatedName === "date") { out[translatedName] = xmltvTimestampToUtcDate(kids); continue; } if ( typeof kids === "string" && elementsAsScalar.indexOf(child.tagName) === -1 ) { kids = { _value: kids, }; } if (Array.isArray(out[translatedName])) { out[translatedName].push(kids); continue; } out[translatedName] = kids; } return out as Xmltv; }
src/toObject.ts
ektotv-xmltv-03be15c
[ { "filename": "src/types.ts", "retrieved_chunk": "export type XmltvDomNode =\n | {\n tagName: string;\n attributes: Record<string, any>;\n children: Array<XmltvDomNode | string>;\n }\n | string;\n/**\n * A collection of XMLTV DOM nodes to form a valid XMLTV document\n *", "score": 0.8442992568016052 }, { "filename": "src/objectToDom.ts", "retrieved_chunk": "import type { XmltvDomNode } from \"./types\";\nimport { dateToXmltvUtcTimestamp } from \"./utils.js\";\nimport {\n xmltvAttributeTranslationsReversed,\n xmltvTagTranslationsReversed,\n} from \"./xmltvTranslations.js\";\nimport { XmltvAttributes, xmltvAttributes } from \"./xmltvTagsAttributes.js\";\n/**\n * Converts an XMLTV object to a DOM tree\n *", "score": 0.8258101940155029 }, { "filename": "src/main.ts", "retrieved_chunk": "import { parser } from \"./parser.js\";\nimport { writer } from \"./writer.js\";\nimport { objectToDom } from \"./objectToDom.js\";\nimport { toObject } from \"./toObject.js\";\nimport type {\n Xmltv,\n XmltvAudio,\n XmltvChannel,\n XmltvCreditImage,\n XmltvCredits,", "score": 0.8143875598907471 }, { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type XmltvDom = XmltvDomNode[];", "score": 0.8025468587875366 }, { "filename": "src/main.ts", "retrieved_chunk": " xmltv: Xmltv,\n options: WriteXmltvOptions & { fromDom: false }\n): string;\nfunction writeXmltv(xmltv: Xmltv): string;\nfunction writeXmltv(\n xmltv: Xmltv | XmltvDom,\n options: WriteXmltvOptions = { fromDom: false }\n): string {\n if (options.fromDom) {\n if (typeof xmltv === \"object\" && !Array.isArray(xmltv)) {", "score": 0.7987083196640015 } ]
typescript
parent: XmltvDomNode = { tagName: "tv", attributes: {}, children: [] }
import { XmltvDom } from "./types"; /** * The MIT License (MIT) * * Copyright (c) 2015 Tobias Nickel * * Copyright (c) 2023 Liam Potter * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @author: Tobias Nickel * @created: 06.04.2015 * I needed a small xml parser that can be used in a worker. * * @author: Liam Potter * @created: 03.04.2023 * Based on the original work of Tobias Nickel (txml) * I removed the more generic parts of the parser to focus on working with the XMLTV format * Outputs a more fluent object structure matching the Xmltv types */
export function parser(xmltvString: string): XmltvDom {
let pos = 0; const openBracket = "<"; const closeBracket = ">"; const openBracketCC = openBracket.charCodeAt(0); const closeBracketCC = closeBracket.charCodeAt(0); const minusCC = "-".charCodeAt(0); const slashCC = "/".charCodeAt(0); const exclamationCC = "!".charCodeAt(0); const singleQuoteCC = "'".charCodeAt(0); const doubleQuoteCC = '"'.charCodeAt(0); const openCornerBracketCC = "[".charCodeAt(0); const closeCornerBracketCC = "]".charCodeAt(0); const questionMarkCC = "?".charCodeAt(0); const nameSpacer = "\r\n\t>/= "; const noChildNodes = ["new", "icon", "previously-shown"]; /** * parsing a list of entries */ function parseChildren(tagName: string): XmltvDom { const children: XmltvDom = []; while (xmltvString[pos]) { if (xmltvString.charCodeAt(pos) == openBracketCC) { if (xmltvString.charCodeAt(pos + 1) === slashCC) { const closeStart = pos + 2; pos = xmltvString.indexOf(closeBracket, pos); const closeTag = xmltvString.substring(closeStart, pos); if (closeTag.indexOf(tagName) == -1) { const parsedText = xmltvString.substring(0, pos).split("\n"); throw new Error( "Unexpected close tag\nLine: " + (parsedText.length - 1) + "\nColumn: " + (parsedText[parsedText.length - 1].length + 1) + "\nChar: " + xmltvString[pos] ); } if (pos + 1) pos += 1; return children; } else if (xmltvString.charCodeAt(pos + 1) === exclamationCC) { if (xmltvString.charCodeAt(pos + 2) == minusCC) { //comment support while ( pos !== -1 && !( xmltvString.charCodeAt(pos) === closeBracketCC && xmltvString.charCodeAt(pos - 1) == minusCC && xmltvString.charCodeAt(pos - 2) == minusCC && pos != -1 ) ) { pos = xmltvString.indexOf(closeBracket, pos + 1); } if (pos === -1) { pos = xmltvString.length; } } else { // doctype support const startDoctype = pos + 1; pos += 2; let encapsulated = false; while ( (xmltvString.charCodeAt(pos) !== closeBracketCC || encapsulated === true) && xmltvString[pos] ) { if (xmltvString.charCodeAt(pos) === openCornerBracketCC) { encapsulated = true; } else if ( encapsulated === true && xmltvString.charCodeAt(pos) === closeCornerBracketCC ) { encapsulated = false; } pos++; } children.push(xmltvString.substring(startDoctype, pos)); } pos++; continue; } const node = parseNode(); children.push(node); if (node.tagName.charCodeAt(0) === questionMarkCC) { for (let i = 0, x = node.children.length; i < x; i++) { children.push(node.children[i]); } node.children = []; } } else { const text = parseText().trim(); if (text.length > 0) { children.push(text); } pos++; } } return children; } /** * returns the text outside of texts until the first '<' */ function parseText() { const start = pos; pos = xmltvString.indexOf(openBracket, pos) - 1; if (pos === -2) pos = xmltvString.length; return xmltvString.slice(start, pos + 1); } /** * returns text until the first nonAlphabetic letter */ function parseName() { const start = pos; while (nameSpacer.indexOf(xmltvString[pos]) === -1 && xmltvString[pos]) { pos++; } return xmltvString.slice(start, pos); } function parseNode() { pos++; const tagName = parseName(); const attributes: Record<string, any> = {}; let children: XmltvDom = []; // parsing attributes while (xmltvString.charCodeAt(pos) !== closeBracketCC && xmltvString[pos]) { const c = xmltvString.charCodeAt(pos); if ((c > 64 && c < 91) || (c > 96 && c < 123)) { const name = parseName(); // search beginning of the string let code = xmltvString.charCodeAt(pos); let value; while ( code && code !== singleQuoteCC && code !== doubleQuoteCC && !((code > 64 && code < 91) || (code > 96 && code < 123)) && code !== closeBracketCC ) { pos++; code = xmltvString.charCodeAt(pos); } if (code === singleQuoteCC || code === doubleQuoteCC) { value = parseString(); if (pos === -1) { return { tagName, attributes, children, }; } } else { value = null; pos--; } attributes[name] = value; } pos++; } // optional parsing of children if (xmltvString.charCodeAt(pos - 1) !== slashCC) { if (noChildNodes.indexOf(tagName) === -1) { pos++; children = parseChildren(tagName); } else { pos++; } } else { pos++; } return { tagName, attributes, children, }; } function parseString(): string { const startChar = xmltvString[pos]; const start = pos + 1; pos = xmltvString.indexOf(startChar, start); return xmltvString.slice(start, pos); } return parseChildren(""); }
src/parser.ts
ektotv-xmltv-03be15c
[ { "filename": "src/main.ts", "retrieved_chunk": " xmltvString: string,\n options: ParseXmltvOptions & { asDom: false }\n): XmltvDom;\nfunction parseXmltv(xmltvString: string): Xmltv;\nfunction parseXmltv(\n xmltvString: string,\n options: ParseXmltvOptions = { asDom: false }\n): Xmltv | XmltvDom {\n const parsed = parser(xmltvString);\n if (options.asDom) {", "score": 0.8714147806167603 }, { "filename": "src/main.ts", "retrieved_chunk": " *\n * @param xmltvString The xmltv file content as a string\n * @param options Options to parse the xmltv file\n * @param options.asDom If true, the xmltv file will be returned as a DOM tree\n */\nfunction parseXmltv(\n xmltvString: string,\n options: ParseXmltvOptions & { asDom: true }\n): XmltvDom;\nfunction parseXmltv(", "score": 0.831786572933197 }, { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type XmltvDom = XmltvDomNode[];", "score": 0.8306500911712646 }, { "filename": "src/types.ts", "retrieved_chunk": "export type XmltvDomNode =\n | {\n tagName: string;\n attributes: Record<string, any>;\n children: Array<XmltvDomNode | string>;\n }\n | string;\n/**\n * A collection of XMLTV DOM nodes to form a valid XMLTV document\n *", "score": 0.8187693953514099 }, { "filename": "src/main.ts", "retrieved_chunk": "type ParseXmltvOptions = {\n asDom: boolean;\n};\ntype WriteXmltvOptions = {\n fromDom: boolean;\n};\n/**\n * parseXmltv\n *\n * Parses an xmltv file and returns an `Xmltv` object or a DOM tree", "score": 0.8180490732192993 } ]
typescript
export function parser(xmltvString: string): XmltvDom {