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 { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup
= catchAsync(async (req, res) => {
const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": "import express from 'express';\nimport { getMe, login, refresh, signup } from '../service';\nimport { refreshMiddleware } from '../../../middleware/refresh';\nimport { protect } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/auth/signup:\n * post:\n * summary: Creates an account", "score": 0.8420282602310181 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 0.8182651996612549 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": "/**\n * @swagger\n * components:\n * schemas:\n * SignupRequest:\n * type: object\n * required:\n * - email\n * - password\n * - name", "score": 0.8106738924980164 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": "/**\n * @swagger\n * components:\n * schemas:\n * SignupRequest:\n * type: object\n * required:\n * - email\n * - password\n * - name", "score": 0.8105672597885132 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/signup', signup);\n/**\n * @swagger\n * /api/v1/auth/login:\n * post:", "score": 0.8087996244430542 } ]
typescript
= catchAsync(async (req, res) => {
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => {
const newUser = await User.create({
name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 0.8396725654602051 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": "import express from 'express';\nimport { getMe, login, refresh, signup } from '../service';\nimport { refreshMiddleware } from '../../../middleware/refresh';\nimport { protect } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/auth/signup:\n * post:\n * summary: Creates an account", "score": 0.8305689692497253 }, { "filename": "src/modules/auth/model/index.ts", "retrieved_chunk": "import { Document, Model, Schema, model } from 'mongoose';\nimport * as EmailValidator from 'email-validator';\nimport { hash, compare } from 'bcryptjs';\n// import { IUser } from '../types';\ninterface UserAttrs {\n id: string;\n name: string;\n email: string;\n role: 'user' | 'admin';\n password: string;", "score": 0.825439989566803 }, { "filename": "src/modules/auth/model/index.ts", "retrieved_chunk": " password: string;\n}\nconst userSchema = new Schema<IUser>({\n name: {\n type: String,\n required: [true, 'Please tell us your name!'],\n },\n email: {\n type: String,\n required: [true, 'Please provide your email'],", "score": 0.8209323287010193 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/signup', signup);\n/**\n * @swagger\n * /api/v1/auth/login:\n * post:", "score": 0.8161664009094238 } ]
typescript
const newUser = await User.create({
/** * @swagger * components: * schemas: * User: * type: object * required: * - name * - email * properties: * name: * type: string * description: The user name * email: * type: string * format: email * description: The user email address * password: * type: string * description: The user password (hashed) * role: * type: string * enum: [user, admin] * description: The user role * default: user * example: * name: John Doe * email: johndoe@example.com * password: $2a$10$gR06R4K1NM4p4b4ELq.LlOTzq3Dcxj2iPwE5U/O2MDE70o9noemhO * role: user */ import express from 'express'; import { deleteUser, fetchUsers } from '../service'; import { protect, restrictTo } from '../../../middleware'; const router = express.Router(); /** * @swagger * /api/v1/users: * get: * summary: Retrieve all users * tags: [User] * security: * - bearerAuth: [] * responses: * "200": * description: A list of users * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/User' * "401": * description: Unauthorized */ router
.get('/', protect, restrictTo('admin'), fetchUsers);
/** * @swagger * /api/v1/users/{id}: * delete: * summary: Delete a user by ID * tags: [User] * security: * - bearerAuth: [] * parameters: * - in: path * name: id * schema: * type: string * required: true * description: The ID of the user to delete * responses: * "204": * description: User deleted successfully * "401": * description: Unauthorized * "404": * description: User not found */ // A simple case where users can only delete themselves not the admin router.delete('/:id', restrictTo('user'), deleteUser); export default router;
src/modules/auth/controller/users.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * security:\n * - bearerAuth: []\n * responses:\n * \"200\":\n * description: The user profile\n * \"401\":\n * description: Unauthorized\n */\nrouter.post('/me', protect, getMe);\nexport default router;", "score": 0.865368127822876 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/signup', signup);\n/**\n * @swagger\n * /api/v1/auth/login:\n * post:", "score": 0.8393622636795044 }, { "filename": "src/modules/auth/service/index.ts", "retrieved_chunk": " const refresh = refreshToken(user);\n return res.status(200).json({ status: 'sucess', refresh });\n}\nexport async function fetchUsers(req: Request, res: Response) {\n const body = req.body;\n console.log({ body });\n try {\n const users = await User.find();\n return res.status(200).json({ message: 'sucessfully fetch users', data: users });\n } catch (error: any) {", "score": 0.8390259146690369 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * description: The authenticated user.\n * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/login', login);\n/**\n * @swagger\n * /api/v1/auth/refresh:", "score": 0.8332158923149109 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * \"401\":\n * description: Invalid or expired token or refresh token was already used\n */\nrouter.post('/refresh', refreshMiddleware, refresh);\n/**\n * @swagger\n * /api/v1/auth/me:\n * post:\n * summary: Get user profile\n * tags: [Auth]", "score": 0.831079363822937 } ]
typescript
.get('/', protect, restrictTo('admin'), fetchUsers);
/** * @swagger * components: * schemas: * SignupRequest: * type: object * required: * - email * - password * - name * properties: * name: * type: string * description: The user name * email: * type: string * description: The user email address * password: * type: string * description: The user password * example: * name: John Doe * email: johndoe@example.com * password: password123 * LoginRequest: * type: object * required: * - email * - password * properties: * email: * type: string * description: The user email address * password: * type: string * description: The user password * example: * email: johndoe@example.com * password: password123 */ import express from 'express'; import { getMe, login, refresh, signup } from '../service'; import { refreshMiddleware } from '../../../middleware/refresh'; import { protect } from '../../../middleware'; const router = express.Router(); /** * @swagger * /api/v1/auth/signup: * post: * summary: Creates an account * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/SignupRequest' * responses: * "200": * description: The created user. * content: * application/json: * schema: * $ref: '#/components/schemas/User' */ router.post
('/signup', signup);
/** * @swagger * /api/v1/auth/login: * post: * summary: Login User * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/LoginRequest' * responses: * "200": * description: The authenticated user. * content: * application/json: * schema: * $ref: '#/components/schemas/User' */ router.post('/login', login); /** * @swagger * /api/v1/auth/refresh: * post: * summary: Refreshes the access token * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * type: object * required: * - refresh * properties: * refresh: * type: string * description: Refresh token * example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY0NGYwMjg0MWRmNGJlYzliOWI3ZjlhYSIsImlhdCI6MTY4Mjg5OTU4OCwiZXhwIjoxNjgzMDcyMzg4fQ.Bt2kzyxyUEtUy9pLvr0zSzpI8_xTaM6KulO2mwYztbQ * responses: * "200": * description: The new access token * content: * application/json: * schema: * type: object * properties: * accessToken: * type: string * description: Access token * example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKb2huIERvZSIsImlhdCI6MTUxNjIzOTAyMn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c * "400": * description: Invalid request or refresh token is not present * "401": * description: Invalid or expired token or refresh token was already used */ router.post('/refresh', refreshMiddleware, refresh); /** * @swagger * /api/v1/auth/me: * post: * summary: Get user profile * tags: [Auth] * security: * - bearerAuth: [] * responses: * "200": * description: The user profile * "401": * description: Unauthorized */ router.post('/me', protect, getMe); export default router;
src/modules/auth/controller/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/service/index.ts", "retrieved_chunk": " refresh,\n data: {\n name,\n email,\n role,\n },\n });\n};\nexport const signup = catchAsync(async (req, res) => {\n const newUser = await User.create({", "score": 0.8273605704307556 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": "/**\n * @swagger\n * components:\n * schemas:\n * SignupRequest:\n * type: object\n * required:\n * - email\n * - password\n * - name", "score": 0.8253936767578125 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": "router.delete('/:id', restrictTo('user'), deleteUser);\nexport default router;", "score": 0.8125429153442383 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " * items:\n * $ref: '#/components/schemas/User'\n * \"401\":\n * description: Unauthorized\n */\nrouter.get('/', protect, restrictTo('admin'), fetchUsers);\n/**\n * @swagger\n * /api/v1/users/{id}:\n * delete:", "score": 0.7973657846450806 }, { "filename": "src/modules/auth/service/index.ts", "retrieved_chunk": " return next(new AppError('Please provide email and password!', 400));\n }\n // 2) Check if user exists && password is correct\n const user: any = await User.findOne({ email }).select('+password');\n if (!user || !(await user.correctPassword(password, user.password))) {\n return next(new AppError('Incorrect email or password', 401));\n }\n // 3) If everything ok, send token to client\n createSendToken(user, 200, req, res);\n});", "score": 0.7948713302612305 } ]
typescript
('/signup', signup);
/** * @swagger * components: * schemas: * SignupRequest: * type: object * required: * - email * - password * - name * properties: * name: * type: string * description: The user name * email: * type: string * description: The user email address * password: * type: string * description: The user password * example: * name: John Doe * email: johndoe@example.com * password: password123 * LoginRequest: * type: object * required: * - email * - password * properties: * email: * type: string * description: The user email address * password: * type: string * description: The user password * example: * email: johndoe@example.com * password: password123 */ import express from 'express'; import { getMe, login, refresh, signup } from '../service'; import { refreshMiddleware } from '../../../middleware/refresh'; import { protect } from '../../../middleware'; const router = express.Router(); /** * @swagger * /api/v1/auth/signup: * post: * summary: Creates an account * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/SignupRequest' * responses: * "200": * description: The created user. * content: * application/json: * schema: * $ref: '#/components/schemas/User' */ router.post('/signup', signup); /** * @swagger * /api/v1/auth/login: * post: * summary: Login User * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/LoginRequest' * responses: * "200": * description: The authenticated user. * content: * application/json: * schema: * $ref: '#/components/schemas/User' */ router.post('/login', login); /** * @swagger * /api/v1/auth/refresh: * post: * summary: Refreshes the access token * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * type: object * required: * - refresh * properties: * refresh: * type: string * description: Refresh token * example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY0NGYwMjg0MWRmNGJlYzliOWI3ZjlhYSIsImlhdCI6MTY4Mjg5OTU4OCwiZXhwIjoxNjgzMDcyMzg4fQ.Bt2kzyxyUEtUy9pLvr0zSzpI8_xTaM6KulO2mwYztbQ * responses: * "200": * description: The new access token * content: * application/json: * schema: * type: object * properties: * accessToken: * type: string * description: Access token * example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKb2huIERvZSIsImlhdCI6MTUxNjIzOTAyMn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c * "400": * description: Invalid request or refresh token is not present * "401": * description: Invalid or expired token or refresh token was already used */ router.post('/refresh', refreshMiddleware, refresh); /** * @swagger * /api/v1/auth/me: * post: * summary: Get user profile * tags: [Auth] * security: * - bearerAuth: [] * responses: * "200": * description: The user profile * "401": * description: Unauthorized */ router.post(
'/me', protect, getMe);
export default router;
src/modules/auth/controller/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/service/index.ts", "retrieved_chunk": "export const getMe = catchAsync(async (req, res) => {\n const user = req.user;\n // 3) If everything ok, send token to client\n res.status(200).json({ message: 'user sucessfully fetched!', user });\n});\nexport function logout(req: Request, res: Response) {\n res.cookie('jwt', 'loggedout', {\n expires: new Date(Date.now() + 10 * 1000),\n httpOnly: true,\n });", "score": 0.8409225344657898 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " * items:\n * $ref: '#/components/schemas/User'\n * \"401\":\n * description: Unauthorized\n */\nrouter.get('/', protect, restrictTo('admin'), fetchUsers);\n/**\n * @swagger\n * /api/v1/users/{id}:\n * delete:", "score": 0.8221830725669861 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": " * description: Invalid request parameters\n * '401':\n * description: Unauthorized request\n */\nrouter.post('/transfer', protect, transferFund);\nexport default router;", "score": 0.8211737871170044 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " */\nimport express from 'express';\nimport { deleteUser, fetchUsers } from '../service';\nimport { protect, restrictTo } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/users:\n * get:\n * summary: Retrieve all users", "score": 0.8188678026199341 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": "router.delete('/:id', restrictTo('user'), deleteUser);\nexport default router;", "score": 0.8151906132698059 } ]
typescript
'/me', protect, getMe);
/** * @swagger * components: * schemas: * User: * type: object * required: * - name * - email * properties: * name: * type: string * description: The user name * email: * type: string * format: email * description: The user email address * password: * type: string * description: The user password (hashed) * role: * type: string * enum: [user, admin] * description: The user role * default: user * example: * name: John Doe * email: johndoe@example.com * password: $2a$10$gR06R4K1NM4p4b4ELq.LlOTzq3Dcxj2iPwE5U/O2MDE70o9noemhO * role: user */ import express from 'express'; import { deleteUser, fetchUsers } from '../service'; import { protect, restrictTo } from '../../../middleware'; const router = express.Router(); /** * @swagger * /api/v1/users: * get: * summary: Retrieve all users * tags: [User] * security: * - bearerAuth: [] * responses: * "200": * description: A list of users * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/User' * "401": * description: Unauthorized */
router.get('/', protect, restrictTo('admin'), fetchUsers);
/** * @swagger * /api/v1/users/{id}: * delete: * summary: Delete a user by ID * tags: [User] * security: * - bearerAuth: [] * parameters: * - in: path * name: id * schema: * type: string * required: true * description: The ID of the user to delete * responses: * "204": * description: User deleted successfully * "401": * description: Unauthorized * "404": * description: User not found */ // A simple case where users can only delete themselves not the admin router.delete('/:id', restrictTo('user'), deleteUser); export default router;
src/modules/auth/controller/users.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * security:\n * - bearerAuth: []\n * responses:\n * \"200\":\n * description: The user profile\n * \"401\":\n * description: Unauthorized\n */\nrouter.post('/me', protect, getMe);\nexport default router;", "score": 0.8725484609603882 }, { "filename": "src/modules/auth/service/index.ts", "retrieved_chunk": " const refresh = refreshToken(user);\n return res.status(200).json({ status: 'sucess', refresh });\n}\nexport async function fetchUsers(req: Request, res: Response) {\n const body = req.body;\n console.log({ body });\n try {\n const users = await User.find();\n return res.status(200).json({ message: 'sucessfully fetch users', data: users });\n } catch (error: any) {", "score": 0.8481841087341309 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/signup', signup);\n/**\n * @swagger\n * /api/v1/auth/login:\n * post:", "score": 0.8390446305274963 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * \"401\":\n * description: Invalid or expired token or refresh token was already used\n */\nrouter.post('/refresh', refreshMiddleware, refresh);\n/**\n * @swagger\n * /api/v1/auth/me:\n * post:\n * summary: Get user profile\n * tags: [Auth]", "score": 0.8366206884384155 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * description: The authenticated user.\n * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/login', login);\n/**\n * @swagger\n * /api/v1/auth/refresh:", "score": 0.8340569138526917 } ]
typescript
router.get('/', protect, restrictTo('admin'), fetchUsers);
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const
{ name, email, role, ...otherUserData } = user;
res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { NextFunction, Request, Response } from 'express';\nimport jwt from 'jsonwebtoken';\nimport User from '../modules/auth/model';\n// Only for rendered pages, no errors!\nexport async function isLoggedIn(req: Request, res: Response, next: NextFunction) {\n if (req.cookies.jwt) {\n try {\n // 1) verify token\n const decoded: any = await jwt.verify(req.cookies.jwt, process.env.JWT_KEY_SECRET as string);", "score": 0.835082471370697 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 0.8346542119979858 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 0.8329000473022461 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": " } else if (req.cookies.jwt) {\n token = req.cookies.jwt;\n }\n console.log({ token });\n if (!token) {\n return next(new AppError('You are not logged in! Please log in to get access.', 401));\n }\n // 2) Verification token\n const decoded = (await verify(token, process.env.JWT_KEY_SECRET as string)) as JwtPayload;\n console.log({ decoded });", "score": 0.8283773064613342 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\nimport { JwtPayload, verify } from 'jsonwebtoken';\nimport { AppError } from '../utils/appError';\nimport { catchAsync } from '../utils/catchAsync';\nimport User from '../modules/auth/model';\nexport const protect = catchAsync(async (req: Request, res: Response, next: NextFunction) => {\n // 1) Getting token and check of it's there\n let token;\n if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {\n token = req.headers.authorization.split(' ')[1];", "score": 0.8234500288963318 } ]
typescript
{ name, email, role, ...otherUserData } = user;
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync
(async (req, res) => {
const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": "import express from 'express';\nimport { getMe, login, refresh, signup } from '../service';\nimport { refreshMiddleware } from '../../../middleware/refresh';\nimport { protect } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/auth/signup:\n * post:\n * summary: Creates an account", "score": 0.8480143547058105 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 0.8316062688827515 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/signup', signup);\n/**\n * @swagger\n * /api/v1/auth/login:\n * post:", "score": 0.8133172392845154 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": "/**\n * @swagger\n * components:\n * schemas:\n * SignupRequest:\n * type: object\n * required:\n * - email\n * - password\n * - name", "score": 0.8081879615783691 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": "/**\n * @swagger\n * components:\n * schemas:\n * SignupRequest:\n * type: object\n * required:\n * - email\n * - password\n * - name", "score": 0.8080704212188721 } ]
typescript
(async (req, res) => {
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const {
name, email, role, ...otherUserData } = user;
res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 0.8344400525093079 }, { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { NextFunction, Request, Response } from 'express';\nimport jwt from 'jsonwebtoken';\nimport User from '../modules/auth/model';\n// Only for rendered pages, no errors!\nexport async function isLoggedIn(req: Request, res: Response, next: NextFunction) {\n if (req.cookies.jwt) {\n try {\n // 1) verify token\n const decoded: any = await jwt.verify(req.cookies.jwt, process.env.JWT_KEY_SECRET as string);", "score": 0.8343707919120789 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 0.8308120965957642 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": " } else if (req.cookies.jwt) {\n token = req.cookies.jwt;\n }\n console.log({ token });\n if (!token) {\n return next(new AppError('You are not logged in! Please log in to get access.', 401));\n }\n // 2) Verification token\n const decoded = (await verify(token, process.env.JWT_KEY_SECRET as string)) as JwtPayload;\n console.log({ decoded });", "score": 0.8264849185943604 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": " // 3) Check if user still exists\n const currentUser = await User.findById(decoded.id);\n if (!currentUser) {\n return next(new AppError('The user belonging to this token does no longer exist.', 401));\n }\n // GRANT ACCESS TO PROTECTED ROUTE\n req.user = currentUser;\n next();\n});", "score": 0.821225643157959 } ]
typescript
name, email, role, ...otherUserData } = user;
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res
, next) => {
const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/protect.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\nimport { JwtPayload, verify } from 'jsonwebtoken';\nimport { AppError } from '../utils/appError';\nimport { catchAsync } from '../utils/catchAsync';\nimport User from '../modules/auth/model';\nexport const protect = catchAsync(async (req: Request, res: Response, next: NextFunction) => {\n // 1) Getting token and check of it's there\n let token;\n if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {\n token = req.headers.authorization.split(' ')[1];", "score": 0.8590414524078369 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": "import express from 'express';\nimport { getMe, login, refresh, signup } from '../service';\nimport { refreshMiddleware } from '../../../middleware/refresh';\nimport { protect } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/auth/signup:\n * post:\n * summary: Creates an account", "score": 0.8454623818397522 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 0.8450778126716614 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/signup', signup);\n/**\n * @swagger\n * /api/v1/auth/login:\n * post:", "score": 0.8392922878265381 }, { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { NextFunction, Request, Response } from 'express';\nimport jwt from 'jsonwebtoken';\nimport User from '../modules/auth/model';\n// Only for rendered pages, no errors!\nexport async function isLoggedIn(req: Request, res: Response, next: NextFunction) {\n if (req.cookies.jwt) {\n try {\n // 1) verify token\n const decoded: any = await jwt.verify(req.cookies.jwt, process.env.JWT_KEY_SECRET as string);", "score": 0.8378929495811462 } ]
typescript
, next) => {
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct
const user: any = await User.findOne({ email }).select('+password');
if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/protect.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\nimport { JwtPayload, verify } from 'jsonwebtoken';\nimport { AppError } from '../utils/appError';\nimport { catchAsync } from '../utils/catchAsync';\nimport User from '../modules/auth/model';\nexport const protect = catchAsync(async (req: Request, res: Response, next: NextFunction) => {\n // 1) Getting token and check of it's there\n let token;\n if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {\n token = req.headers.authorization.split(' ')[1];", "score": 0.8736763000488281 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": " } else if (req.cookies.jwt) {\n token = req.cookies.jwt;\n }\n console.log({ token });\n if (!token) {\n return next(new AppError('You are not logged in! Please log in to get access.', 401));\n }\n // 2) Verification token\n const decoded = (await verify(token, process.env.JWT_KEY_SECRET as string)) as JwtPayload;\n console.log({ decoded });", "score": 0.865096926689148 }, { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { NextFunction, Request, Response } from 'express';\nimport jwt from 'jsonwebtoken';\nimport User from '../modules/auth/model';\n// Only for rendered pages, no errors!\nexport async function isLoggedIn(req: Request, res: Response, next: NextFunction) {\n if (req.cookies.jwt) {\n try {\n // 1) verify token\n const decoded: any = await jwt.verify(req.cookies.jwt, process.env.JWT_KEY_SECRET as string);", "score": 0.8604113459587097 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 0.8512232303619385 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": " // 3) Check if user still exists\n const currentUser = await User.findById(decoded.id);\n if (!currentUser) {\n return next(new AppError('The user belonging to this token does no longer exist.', 401));\n }\n // GRANT ACCESS TO PROTECTED ROUTE\n req.user = currentUser;\n next();\n});", "score": 0.8496607542037964 } ]
typescript
const user: any = await User.findOne({ email }).select('+password');
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => {
const thread = useStore((state) => state.thread) if (!thread.messages) {
return null; } return ( <> {thread.messages.map((message, index) => { return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 0.8886086344718933 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 0.8657805919647217 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " );\n};\nconst Navbar = () => {\n const resetThread = useStore((state) => state.resetThread);\n const newChatHandler = () => {\n resetThread()\n }\n return (\n <div className=\"flex min-h-0 flex-1 flex-col bg-gray-800\">\n <div className=\"flex flex-1 flex-col overflow-y-auto pb-4\">", "score": 0.8645903468132019 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Sidebar = () => {\n return (\n <div className=\"hidden lg:fixed lg:inset-y-0 lg:flex lg:w-80 lg:flex-col z-40\">\n <Navbar />\n <AccountCorner />\n </div>\n )\n}\nconst StarredChats = () => {\n const threads = useStore((state) => state.threads)", "score": 0.8564234375953674 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": "import { useEffect, useState } from \"react\"\nimport { ArrowRightIcon, BookOpenIcon, CheckCircleIcon, Cog6ToothIcon, DocumentIcon, KeyIcon, LanguageIcon, MicrophoneIcon, UserIcon } from \"@heroicons/react/24/solid\"\nimport useStore from \"~/store/store\"\nimport { api } from \"~/utils/api\"\nimport MessageWindow from \"./MessageWindow\"\nimport type { Message, Model, Usage } from \"~/types/appstate\"\nimport { uuid } from \"../modals/ApiKeyModal\"\nexport const ChatFeatureBody = () => {\n return (\n <div className=\"resize-container relative\" >", "score": 0.8536953330039978 } ]
typescript
const thread = useStore((state) => state.thread) if (!thread.messages) {
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; };
@requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {
return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null) return reject(new KretaError('Failed to get access token: Invalid credentials')); else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 0.8614031672477722 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\taxios.defaults.proxy = proxy;\n\t\treturn this;\n\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t}\n\tprivate buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string {\n\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';", "score": 0.841577410697937 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\tthis.institute_code = options?.institute_code || '';\n\t\taxios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0';\n\t\tthis.Global = new Global();\n\t\tthis.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\tthis.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t}\n\tpublic get _username() {\n\t\treturn this.username;", "score": 0.8399890065193176 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t}\n\tpublic get _password() {\n\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\t@requireParam('proxy.host')\n\t@requireParam('proxy.port')\n\tpublic setProxy(proxy: AxiosProxyConfig): this {", "score": 0.8265578746795654 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 0.8169519305229187 } ]
typescript
@requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => { const thread = useStore((state) => state.thread) if (!thread.messages) { return null; } return ( <>
{thread.messages.map((message, index) => {
return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 0.8785554766654968 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 0.8763703107833862 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " );\n};\nconst Navbar = () => {\n const resetThread = useStore((state) => state.resetThread);\n const newChatHandler = () => {\n resetThread()\n }\n return (\n <div className=\"flex min-h-0 flex-1 flex-col bg-gray-800\">\n <div className=\"flex flex-1 flex-col overflow-y-auto pb-4\">", "score": 0.8662304878234863 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " return (\n <div className=\"flex-1 pb-4\">\n {threads.map((thread) => {\n return (\n <SidebarChatButton {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n )\n })}\n </div>\n )\n}", "score": 0.8616960644721985 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const [message, setMessage] = useState<string>(\"\")\n const sendMessage = () => {\n if (message.length > 0) {\n if (thread.messages.length === 0) {\n const id = uuid()\n const messages = [\n { role: 'system', content: thread.initialSystemInstruction },\n { role: 'user', content: message }\n ] as Message[]\n mutate({", "score": 0.8510151505470276 } ]
typescript
{thread.messages.map((message, index) => {
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0';
this.Global = new Global();
this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 0.9185726642608643 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "import KretaError from './errors/KretaError';\nimport requireParam from '../decorators/requireParam';\nimport tryRequest from '../utils/tryRequest';\nimport requireCredentials from '../decorators/requireCredentials';\nexport class Authentication {\n\tprivate readonly username: string;\n\tprivate readonly password: string;\n\tprivate readonly institute_code: string;\n\tprivate readonly client_id: string = 'kreta-ellenorzo-mobile-android';\n\tprivate readonly grant_type: string = 'password';", "score": 0.8785384297370911 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\tprivate readonly auth_policy_version: string = 'v2';\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t}\n\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {", "score": 0.8645949363708496 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "} from '../types';\nimport { Authentication } from './Authentication';\nimport requireCredentials from '../decorators/requireCredentials';\nimport tryRequest from '../utils/tryRequest';\nimport requireParam from '../decorators/requireParam';\nexport default class Administration {\n\tprivate readonly username: string;\n\tprivate readonly password: string;\n\tprivate readonly institute_code: string;\n\tprivate authenticate: Authentication;", "score": 0.8584216237068176 }, { "filename": "src/types.ts", "retrieved_chunk": "\ttoken_type: string | null;\n}\nexport interface KretaOptions extends AuthenticationFields {\n}\nexport interface AuthenticationResponse {\n\taccess_token: string;\n\texpires_in: number;\n\tid_token: string | null;\n\trefresh_token: string;\n\tscope: string;", "score": 0.8569279909133911 } ]
typescript
this.Global = new Global();
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => { const thread =
useStore((state) => state.thread) if (!thread.messages) {
return null; } return ( <> {thread.messages.map((message, index) => { return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 0.8913347721099854 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 0.8716422319412231 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " );\n};\nconst Navbar = () => {\n const resetThread = useStore((state) => state.resetThread);\n const newChatHandler = () => {\n resetThread()\n }\n return (\n <div className=\"flex min-h-0 flex-1 flex-col bg-gray-800\">\n <div className=\"flex flex-1 flex-col overflow-y-auto pb-4\">", "score": 0.8712756037712097 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Sidebar = () => {\n return (\n <div className=\"hidden lg:fixed lg:inset-y-0 lg:flex lg:w-80 lg:flex-col z-40\">\n <Navbar />\n <AccountCorner />\n </div>\n )\n}\nconst StarredChats = () => {\n const threads = useStore((state) => state.threads)", "score": 0.8566752672195435 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": "import { useEffect, useState } from \"react\"\nimport { ArrowRightIcon, BookOpenIcon, CheckCircleIcon, Cog6ToothIcon, DocumentIcon, KeyIcon, LanguageIcon, MicrophoneIcon, UserIcon } from \"@heroicons/react/24/solid\"\nimport useStore from \"~/store/store\"\nimport { api } from \"~/utils/api\"\nimport MessageWindow from \"./MessageWindow\"\nimport type { Message, Model, Usage } from \"~/types/appstate\"\nimport { uuid } from \"../modals/ApiKeyModal\"\nexport const ChatFeatureBody = () => {\n return (\n <div className=\"resize-container relative\" >", "score": 0.8565487861633301 } ]
typescript
useStore((state) => state.thread) if (!thread.messages) {
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; } @requireCredentials public getAddresseeType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => {
await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {
headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\tpublic getInstitute(): Promise<Institution> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Institution>) => resolve(r.data)));", "score": 0.8339371681213379 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;\n\t}\n\t@requireParam('api_key')\n\tpublic getInstituteList(api_key: string): Promise<Institute[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json');\n\t\t\tawait tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {\n\t\t\t\theaders: {\n\t\t\t\t\tapiKey: api_key\n\t\t\t\t}", "score": 0.8239650726318359 }, { "filename": "src/lib/Global.ts", "retrieved_chunk": "import axios, { AxiosResponse } from 'axios';\nimport { API, Endpoints, InstituteGlobal } from '../types';\nimport tryRequest from '../utils/tryRequest';\nexport default class Global {\n\tconstructor() {\n\t}\n\tpublic getInstituteList(): Promise<InstituteGlobal[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.GLOBAL + Endpoints.PublikusIntezmenyek, {\n\t\t\t\theaders: {", "score": 0.8187087774276733 }, { "filename": "src/types.ts", "retrieved_chunk": "\tEloadasok = '/Lep/Eloadasok',\n\tEszkozAllapot = '/TargyiEszkoz/IsEszkozKiosztva'\n}\nexport enum AdministrationEndpoints {\n\tCimzettTipusok = '/adatszotarak/cimzetttipusok',\n\tKerelemTipusok = '/adatszotarak/kerelemtipusok',\n\tTmgiIgazolasTipusok = '/adatszotarak/tmgiigazolastipusok',\n\tEsemenyek = '/belepteto/kartyaesemenyek/sajat',\n\tJelenlegiIntezmenyModulok = '/intezmenyek/sajat/modulok',\n\tCimezhetoTipusok = '/kommunikacio/cimezhetotipusok',", "score": 0.8147372603416443 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uids')\n\tpublic getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 0.8095877170562744 } ]
typescript
await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; }
@requireCredentials public getAddresseeType(): Promise<AddresseType[]> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;\n\t}\n\t@requireParam('api_key')\n\tpublic getInstituteList(api_key: string): Promise<Institute[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json');\n\t\t\tawait tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {\n\t\t\t\theaders: {\n\t\t\t\t\tapiKey: api_key\n\t\t\t\t}", "score": 0.8325649499893188 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\tpublic getInstitute(): Promise<Institution> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Institution>) => resolve(r.data)));", "score": 0.8206185102462769 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<Institute[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getStudent(): Promise<Student> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 0.7974862456321716 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> {", "score": 0.7961053252220154 }, { "filename": "src/lib/Global.ts", "retrieved_chunk": "import axios, { AxiosResponse } from 'axios';\nimport { API, Endpoints, InstituteGlobal } from '../types';\nimport tryRequest from '../utils/tryRequest';\nexport default class Global {\n\tconstructor() {\n\t}\n\tpublic getInstituteList(): Promise<InstituteGlobal[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.GLOBAL + Endpoints.PublikusIntezmenyek, {\n\t\t\t\theaders: {", "score": 0.7887219786643982 } ]
typescript
@requireCredentials public getAddresseeType(): Promise<AddresseType[]> {
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; } @requireCredentials public getAddresseeType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @
requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uids')\n\tpublic getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 0.8362792730331421 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst ops: {", "score": 0.8154686689376831 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Lesson[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uid')\n\tpublic getLesson(uid: string | number): Promise<Lesson> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), {", "score": 0.8104562759399414 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> {", "score": 0.8044695854187012 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Homework[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uid')\n\tpublic getHomework(uid: string | number): Promise<Homework> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), {\n\t\t\t\theaders: {", "score": 0.8022772073745728 } ]
typescript
requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> {
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; }; @requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username }); await
tryRequest(axios.post(API.IDP + Endpoints.Token, {
institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null) return reject(new KretaError('Failed to get access token: Invalid credentials')); else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 0.8977566361427307 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 0.8463743925094604 }, { "filename": "src/types.ts", "retrieved_chunk": "\ttoken_type: string | null;\n}\nexport interface KretaOptions extends AuthenticationFields {\n}\nexport interface AuthenticationResponse {\n\taccess_token: string;\n\texpires_in: number;\n\tid_token: string | null;\n\trefresh_token: string;\n\tscope: string;", "score": 0.8263327479362488 }, { "filename": "src/types.ts", "retrieved_chunk": "\tGlobalMobileApiUrlTEST: string;\n\tGlobalMobileApiUrlUAT: string;\n}\nexport interface NonceHashOptions {\n\tinstitute_code: string;\n\tnonce: string;\n\tusername: string;\n}\nexport interface AuthenticationFields {\n\tinstitute_code: string;", "score": 0.8256498575210571 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\tthis.institute_code = options?.institute_code || '';\n\t\taxios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0';\n\t\tthis.Global = new Global();\n\t\tthis.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\tthis.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t}\n\tpublic get _username() {\n\t\treturn this.username;", "score": 0.8255524635314941 } ]
typescript
tryRequest(axios.post(API.IDP + Endpoints.Token, {
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; }; @requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null)
return reject(new KretaError('Failed to get access token: Invalid credentials'));
else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/types.ts", "retrieved_chunk": "\ttoken_type: string | null;\n}\nexport interface KretaOptions extends AuthenticationFields {\n}\nexport interface AuthenticationResponse {\n\taccess_token: string;\n\texpires_in: number;\n\tid_token: string | null;\n\trefresh_token: string;\n\tscope: string;", "score": 0.8532363772392273 }, { "filename": "src/types.ts", "retrieved_chunk": "\tpassword: string;\n\tusername: string;\n}\nexport interface RequestRefreshTokenOptions {\n\trefreshUserData: boolean;\n\trefreshToken: string;\n}\nexport interface AccessToken {\n\taccess_token: string | null;\n\trefresh_token: string | null;", "score": 0.8404535055160522 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 0.8175305128097534 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 0.8166604042053223 }, { "filename": "src/types.ts", "retrieved_chunk": "\ttoken_type: string;\n}\nexport interface PreBuiltAuthenticationToken {\n\ttoken: string;\n\taccess_token: string;\n\trefresh_token: string;\n}\ninterface ResponseErrorItem {\n\tPropertyName: string;\n\tMessage: string;", "score": 0.8137394785881042 } ]
typescript
return reject(new KretaError('Failed to get access token: Invalid credentials'));
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try {
const users = await User.find();
return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " */\nimport express from 'express';\nimport { deleteUser, fetchUsers } from '../service';\nimport { protect, restrictTo } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/users:\n * get:\n * summary: Retrieve all users", "score": 0.8513675332069397 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 0.8505203127861023 }, { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { NextFunction, Request, Response } from 'express';\nimport jwt from 'jsonwebtoken';\nimport User from '../modules/auth/model';\n// Only for rendered pages, no errors!\nexport async function isLoggedIn(req: Request, res: Response, next: NextFunction) {\n if (req.cookies.jwt) {\n try {\n // 1) verify token\n const decoded: any = await jwt.verify(req.cookies.jwt, process.env.JWT_KEY_SECRET as string);", "score": 0.840906023979187 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 0.8314695358276367 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": " } else if (req.cookies.jwt) {\n token = req.cookies.jwt;\n }\n console.log({ token });\n if (!token) {\n return next(new AppError('You are not logged in! Please log in to get access.', 401));\n }\n // 2) Verification token\n const decoded = (await verify(token, process.env.JWT_KEY_SECRET as string)) as JwtPayload;\n console.log({ decoded });", "score": 0.8238646984100342 } ]
typescript
const users = await User.find();
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await
User.deleteOne({ _id: id });
return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": "router.delete('/:id', restrictTo('user'), deleteUser);\nexport default router;", "score": 0.8614174127578735 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " */\nimport express from 'express';\nimport { deleteUser, fetchUsers } from '../service';\nimport { protect, restrictTo } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/users:\n * get:\n * summary: Retrieve all users", "score": 0.8356690406799316 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " * items:\n * $ref: '#/components/schemas/User'\n * \"401\":\n * description: Unauthorized\n */\nrouter.get('/', protect, restrictTo('admin'), fetchUsers);\n/**\n * @swagger\n * /api/v1/users/{id}:\n * delete:", "score": 0.8291543126106262 }, { "filename": "src/middleware/error.ts", "retrieved_chunk": "};\nconst handleValidationErrorDB = (err: any) => {\n const errors = Object.values(err.errors).map((el: any) => el.message);\n const message = `Invalid input data. ${errors.join('. ')}`;\n return new AppError(message, 400);\n};\nconst handleJWTError = () => new AppError('Invalid token. Please log in again!', 401);\nconst handleJWTExpiredError = () => new AppError('Your token has expired! Please log in again.', 401);\nconst sendErrorDev = (err: any, req: Request, res: Response) => {\n // A) API", "score": 0.806191086769104 }, { "filename": "src/middleware/error.ts", "retrieved_chunk": " return res.status(err.statusCode).json({\n status: err.status,\n error: err,\n message: err.message,\n stack: err.stack,\n });\n};\nconst sendErrorProd = (err: any, req: Request, res: Response) => {\n // A) API\n if (req.originalUrl.startsWith('/api')) {", "score": 0.8026835322380066 } ]
typescript
User.deleteOne({ _id: id });
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new
Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });
} public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 0.9204505085945129 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\tprivate readonly auth_policy_version: string = 'v2';\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t}\n\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {", "score": 0.8924167156219482 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\t\t\tinstitute_code: this.institute_code,\n\t\t\t\tusername: this.username\n\t\t\t});\n\t\t\tawait tryRequest(axios.post(API.IDP + Endpoints.Token, {\n\t\t\t\trefresh_token: options.refreshToken,\n\t\t\t\tinstitute_code: this.institute_code,\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.client_id,\n\t\t\t\trefresh_user_data: options.refreshUserData\n\t\t\t}, {", "score": 0.8539478778839111 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "} from '../types';\nimport { Authentication } from './Authentication';\nimport requireCredentials from '../decorators/requireCredentials';\nimport tryRequest from '../utils/tryRequest';\nimport requireParam from '../decorators/requireParam';\nexport default class Administration {\n\tprivate readonly username: string;\n\tprivate readonly password: string;\n\tprivate readonly institute_code: string;\n\tprivate authenticate: Authentication;", "score": 0.8517662882804871 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 0.8494582176208496 } ]
typescript
Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';
return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;
} @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {\n\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\tprivate buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string {", "score": 0.8649442791938782 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 0.8368147611618042 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\t@requireParam('proxy.host')\n\t@requireParam('proxy.port')\n\tpublic setProxy(proxy: AxiosProxyConfig): this {\n\t\taxios.defaults.proxy = proxy;\n\t\treturn this;", "score": 0.8082059621810913 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';\n\t\treturn API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams;\n\t}\n\t@requireCredentials\n\tpublic getAddresseeType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 0.7967686057090759 }, { "filename": "src/types.ts", "retrieved_chunk": "export enum Endpoints {\n\tToken = '/connect/token',\n\tNonce = '/nonce',\n\tPublikusIntezmenyek = '/intezmenyek/kreta/publikus',\n\tFeljegyzesek = '/Sajat/Feljegyzesek',\n\tFaliujsagElemek = '/Sajat/FaliujsagElemek',\n\tTanulo = '/Sajat/TanuloAdatlap',\n\tErtekelesek = '/Sajat/Ertekelesek',\n\tTantargyiAtlagok = '/Sajat/Ertekelesek/Atlagok/TantargyiAtlagok',\n\tMulasztasok = '/Sajat/Mulasztasok',", "score": 0.7815284729003906 } ]
typescript
return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;
/** * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS: * 1. You want to modify request context (see Part 1). * 2. You want to create a new middleware or type of procedure (see Part 3). * * TL;DR - This is where all the tRPC server stuff is created and plugged in. The pieces you will * need to use are documented accordingly near the end. */ /** * 1. CONTEXT * * This section defines the "contexts" that are available in the backend API. * * These allow you to access things when processing a request, like the database, the session, etc. */ import { type CreateNextContextOptions } from "@trpc/server/adapters/next"; import { type Session } from "next-auth"; import { getServerAuthSession } from "~/server/auth"; import { prisma } from "~/server/db"; type CreateContextOptions = { session: Session | null; }; /** * This helper generates the "internals" for a tRPC context. If you need to use it, you can export * it from here. * * Examples of things you may need it for: * - testing, so we don't have to mock Next.js' req/res * - tRPC's `createSSGHelpers`, where we don't have req/res * * @see https://create.t3.gg/en/usage/trpc#-servertrpccontextts */ const createInnerTRPCContext = (opts: CreateContextOptions) => { return { session: opts.session, prisma, }; }; /** * This is the actual context you will use in your router. It will be used to process every request * that goes through your tRPC endpoint. * * @see https://trpc.io/docs/context */ export const createTRPCContext = async (opts: CreateNextContextOptions) => { const { req, res } = opts; // Get the session from the server using the getServerSession wrapper function
const session = await getServerAuthSession({ req, res });
return createInnerTRPCContext({ session, }); }; /** * 2. INITIALIZATION * * This is where the tRPC API is initialized, connecting the context and transformer. We also parse * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation * errors on the backend. */ import { initTRPC, TRPCError } from "@trpc/server"; import superjson from "superjson"; import { ZodError } from "zod"; const t = initTRPC.context<typeof createTRPCContext>().create({ transformer: superjson, errorFormatter({ shape, error }) { return { ...shape, data: { ...shape.data, zodError: error.cause instanceof ZodError ? error.cause.flatten() : null, }, }; }, }); /** * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) * * These are the pieces you use to build your tRPC API. You should import these a lot in the * "/src/server/api/routers" directory. */ /** * This is how you create new routers and sub-routers in your tRPC API. * * @see https://trpc.io/docs/router */ export const createTRPCRouter = t.router; /** * Public (unauthenticated) procedure * * This is the base piece you use to build new queries and mutations on your tRPC API. It does not * guarantee that a user querying is authorized, but you can still access user session data if they * are logged in. */ export const publicProcedure = t.procedure; /** Reusable middleware that enforces users are logged in before running the procedure. */ const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCError({ code: "UNAUTHORIZED" }); } return next({ ctx: { // infers the `session` as non-nullable session: { ...ctx.session, user: ctx.session.user }, }, }); }); /** * Protected (authenticated) procedure * * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies * the session is valid and guarantees `ctx.session.user` is not null. * * @see https://trpc.io/docs/procedures */ export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);
src/server/api/trpc.ts
cloudnothings-better-gpt-f1ad4fa
[ { "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.8597224950790405 }, { "filename": "src/server/auth.ts", "retrieved_chunk": "};\n/**\n * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file.\n *\n * @see https://next-auth.js.org/configuration/nextjs\n */\nexport const getServerAuthSession = (ctx: {\n req: GetServerSidePropsContext[\"req\"];\n res: GetServerSidePropsContext[\"res\"];\n}) => {", "score": 0.8418426513671875 }, { "filename": "src/utils/api.ts", "retrieved_chunk": "/**\n * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which\n * contains the Next.js App-wrapper, as well as your type-safe React Query hooks.\n *\n * We also create a few inference helpers for input and output types.\n */\nimport { httpBatchLink, loggerLink } from \"@trpc/client\";\nimport { createTRPCNext } from \"@trpc/next\";\nimport { type inferRouterInputs, type inferRouterOutputs } from \"@trpc/server\";\nimport superjson from \"superjson\";", "score": 0.8384287357330322 }, { "filename": "src/server/api/root.ts", "retrieved_chunk": "import { createTRPCRouter } from \"~/server/api/trpc\";\nimport { exampleRouter } from \"~/server/api/routers/example\";\nimport { gptRouter } from \"./routers/gpt\";\n/**\n * This is the primary router for your server.\n *\n * All routers added in /api/routers should be manually added here.\n */\nexport const appRouter = createTRPCRouter({\n example: exampleRouter,", "score": 0.8316441178321838 }, { "filename": "src/utils/api.ts", "retrieved_chunk": "import { type AppRouter } from \"~/server/api/root\";\nconst getBaseUrl = () => {\n if (typeof window !== \"undefined\") return \"\"; // browser should use relative url\n if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url\n return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost\n};\n/** A set of type-safe react-query hooks for your tRPC API. */\nexport const api = createTRPCNext<AppRouter>({\n config() {\n return {", "score": 0.8232043981552124 } ]
typescript
const session = await getServerAuthSession({ req, res });
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "", } as Thread; export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds
.map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[];
return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " const threads = profile.threadIds.map((id) => {\n return getThread(id)\n }) as Thread[]\n setThreads(threads)\n }\n }\n }\n }, [selectedProfile, setProfile, setThreads]);\n return (\n <>", "score": 0.8869624137878418 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " if (data.threads) {\n setThreads(data.threads)\n }\n }, [setProfile, setProfiles, setThreads, setSelectedProfile]);\n useEffect(() => {\n if (selectedProfile) {\n const profile = getProfile(selectedProfile)\n if (profile) {\n setProfile(profile)\n if (profile.threadIds) {", "score": 0.878676176071167 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Home: NextPage = () => {\n const setProfile = useStore((state) => state.setProfile);\n const setProfiles = useStore((state) => state.setProfiles);\n const setThreads = useStore((state) => state.setThreads);\n const selectedProfile = useStore((state) => state.selectedProfile);\n const setSelectedProfile = useStore((state) => state.setSelectedProfile);\n useEffect(() => {\n const data = loadData();\n if (!data) {\n return", "score": 0.8582552671432495 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 0.836045503616333 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n if (data.selectedProfile) {\n setSelectedProfile(data.selectedProfile)\n }\n if (data.profile) {\n setProfile(data.profile)\n }\n if (data.profiles) {\n setProfiles(data.profiles)\n }", "score": 0.8351589441299438 } ]
typescript
.map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[];
import { TRPCError } from "@trpc/server"; import { Configuration, OpenAIApi } from "openai"; import { type AxiosError } from "axios"; import { z } from "zod"; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import type { Message } from "~/types/appstate"; export type ChatResponse = { id: string; created: number; model: string; choices: [ { finish_reason: string; index: number; message: Message; } ]; object: string; usage: { completion_tokens: number; prompt_tokens: number; total_tokens: number; }; }; export const gptRouter = createTRPCRouter({ post: publicProcedure .input( z.object({ apiKey: z.string(), model: z.string(), messages: z.array( z.object({ role: z.enum(["user", "system", "assistant"]), content: z.string(), }) ), }) ) .mutation(async ({ input }) => { const configuration = new Configuration({ apiKey: input.apiKey, }); const openai = new OpenAIApi(configuration); const response = await openai .createChatCompletion({ model: input.model, messages: input.messages, }) .catch((error: AxiosError) => { console.error(error); if (error.response) { console.log(error.response.status); console.log(error.response.data); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", cause: error.response.data, message: error.message, }); } else { console.log(error.message); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: error.message, }); } }); return
response.data as ChatResponse;
}), });
src/server/api/routers/gpt.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": " ? ({ path, error }) => {\n console.error(\n `❌ tRPC failed on ${path ?? \"<no-path>\"}: ${error.message}`,\n );\n }\n : undefined,\n});", "score": 0.823889434337616 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": "import superjson from \"superjson\";\nimport { ZodError } from \"zod\";\nconst t = initTRPC.context<typeof createTRPCContext>().create({\n transformer: superjson,\n errorFormatter({ shape, error }) {\n return {\n ...shape,\n data: {\n ...shape.data,\n zodError:", "score": 0.8061168789863586 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " });\n};\n/**\n * 2. INITIALIZATION\n *\n * This is where the tRPC API is initialized, connecting the context and transformer. We also parse\n * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation\n * errors on the backend.\n */\nimport { initTRPC, TRPCError } from \"@trpc/server\";", "score": 0.7908081412315369 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " error.cause instanceof ZodError ? error.cause.flatten() : null,\n },\n };\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.7871081829071045 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " })\n setMessage(\"\")\n },\n onError: (e) => {\n alert(e.message)\n }\n })\n } else\n mutate({ model: thread.model.id, apiKey: profile.key, messages: [...thread.messages, { content: message, role: \"user\" }] }, {\n onSuccess: (data) => {", "score": 0.782785177230835 } ]
typescript
response.data as ChatResponse;
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => { const
thread = useStore((state) => state.thread) if (!thread.messages) {
return null; } return ( <> {thread.messages.map((message, index) => { return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 0.8794267773628235 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 0.8634105920791626 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " );\n};\nconst Navbar = () => {\n const resetThread = useStore((state) => state.resetThread);\n const newChatHandler = () => {\n resetThread()\n }\n return (\n <div className=\"flex min-h-0 flex-1 flex-col bg-gray-800\">\n <div className=\"flex flex-1 flex-col overflow-y-auto pb-4\">", "score": 0.8625488877296448 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const [message, setMessage] = useState<string>(\"\")\n const sendMessage = () => {\n if (message.length > 0) {\n if (thread.messages.length === 0) {\n const id = uuid()\n const messages = [\n { role: 'system', content: thread.initialSystemInstruction },\n { role: 'user', content: message }\n ] as Message[]\n mutate({", "score": 0.8532156944274902 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": "import { useEffect, useState } from \"react\"\nimport { ArrowRightIcon, BookOpenIcon, CheckCircleIcon, Cog6ToothIcon, DocumentIcon, KeyIcon, LanguageIcon, MicrophoneIcon, UserIcon } from \"@heroicons/react/24/solid\"\nimport useStore from \"~/store/store\"\nimport { api } from \"~/utils/api\"\nimport MessageWindow from \"./MessageWindow\"\nimport type { Message, Model, Usage } from \"~/types/appstate\"\nimport { uuid } from \"../modals/ApiKeyModal\"\nexport const ChatFeatureBody = () => {\n return (\n <div className=\"resize-container relative\" >", "score": 0.8515337705612183 } ]
typescript
thread = useStore((state) => state.thread) if (!thread.messages) {
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => { const thread = useStore((state) => state.thread) if (!thread.messages) { return null; } return ( <> {thread
.messages.map((message, index) => {
return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 0.8786619305610657 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 0.878130316734314 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " return (\n <div className=\"flex-1 pb-4\">\n {threads.map((thread) => {\n return (\n <SidebarChatButton {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n )\n })}\n </div>\n )\n}", "score": 0.861371636390686 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " );\n};\nconst Navbar = () => {\n const resetThread = useStore((state) => state.resetThread);\n const newChatHandler = () => {\n resetThread()\n }\n return (\n <div className=\"flex min-h-0 flex-1 flex-col bg-gray-800\">\n <div className=\"flex flex-1 flex-col overflow-y-auto pb-4\">", "score": 0.8556668162345886 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const [message, setMessage] = useState<string>(\"\")\n const sendMessage = () => {\n if (message.length > 0) {\n if (thread.messages.length === 0) {\n const id = uuid()\n const messages = [\n { role: 'system', content: thread.initialSystemInstruction },\n { role: 'user', content: message }\n ] as Message[]\n mutate({", "score": 0.8490263819694519 } ]
typescript
.messages.map((message, index) => {
/** * 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
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/server/api/root.ts", "retrieved_chunk": " gpt: gptRouter,\n});\n// export type definition of API\nexport type AppRouter = typeof appRouter;", "score": 0.8104987144470215 }, { "filename": "src/server/api/routers/example.ts", "retrieved_chunk": "import { z } from \"zod\";\nimport {\n createTRPCRouter,\n publicProcedure,\n protectedProcedure,\n} from \"~/server/api/trpc\";\nexport const exampleRouter = createTRPCRouter({\n hello: publicProcedure\n .input(z.object({ text: z.string() }))\n .query(({ input }) => {", "score": 0.8009988069534302 }, { "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.7926017642021179 }, { "filename": "src/server/api/root.ts", "retrieved_chunk": "import { createTRPCRouter } from \"~/server/api/trpc\";\nimport { exampleRouter } from \"~/server/api/routers/example\";\nimport { gptRouter } from \"./routers/gpt\";\n/**\n * This is the primary router for your server.\n *\n * All routers added in /api/routers should be manually added here.\n */\nexport const appRouter = createTRPCRouter({\n example: exampleRouter,", "score": 0.7888026237487793 }, { "filename": "src/server/api/routers/gpt.ts", "retrieved_chunk": "import { TRPCError } from \"@trpc/server\";\nimport { Configuration, OpenAIApi } from \"openai\";\nimport { type AxiosError } from \"axios\";\nimport { z } from \"zod\";\nimport {\n createTRPCRouter,\n publicProcedure,\n protectedProcedure,\n} from \"~/server/api/trpc\";\nimport type { Message } from \"~/types/appstate\";", "score": 0.7792505621910095 } ]
typescript
export type RouterInputs = inferRouterInputs<AppRouter>;
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "", } as Thread; export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds .map((id) => getThread(id)) .filter(
(t) => t !== undefined) as Thread[];
return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " const threads = profile.threadIds.map((id) => {\n return getThread(id)\n }) as Thread[]\n setThreads(threads)\n }\n }\n }\n }, [selectedProfile, setProfile, setThreads]);\n return (\n <>", "score": 0.8808178305625916 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " if (data.threads) {\n setThreads(data.threads)\n }\n }, [setProfile, setProfiles, setThreads, setSelectedProfile]);\n useEffect(() => {\n if (selectedProfile) {\n const profile = getProfile(selectedProfile)\n if (profile) {\n setProfile(profile)\n if (profile.threadIds) {", "score": 0.8741735219955444 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Home: NextPage = () => {\n const setProfile = useStore((state) => state.setProfile);\n const setProfiles = useStore((state) => state.setProfiles);\n const setThreads = useStore((state) => state.setThreads);\n const selectedProfile = useStore((state) => state.selectedProfile);\n const setSelectedProfile = useStore((state) => state.setSelectedProfile);\n useEffect(() => {\n const data = loadData();\n if (!data) {\n return", "score": 0.8600227236747742 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 0.833850622177124 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n if (data.selectedProfile) {\n setSelectedProfile(data.selectedProfile)\n }\n if (data.profile) {\n setProfile(data.profile)\n }\n if (data.profiles) {\n setProfiles(data.profiles)\n }", "score": 0.8322540521621704 } ]
typescript
(t) => t !== undefined) as Thread[];
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "", } as Thread; export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds .map((id) => getThread(id)) .
filter((t) => t !== undefined) as Thread[];
return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " const threads = profile.threadIds.map((id) => {\n return getThread(id)\n }) as Thread[]\n setThreads(threads)\n }\n }\n }\n }, [selectedProfile, setProfile, setThreads]);\n return (\n <>", "score": 0.8791013956069946 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " if (data.threads) {\n setThreads(data.threads)\n }\n }, [setProfile, setProfiles, setThreads, setSelectedProfile]);\n useEffect(() => {\n if (selectedProfile) {\n const profile = getProfile(selectedProfile)\n if (profile) {\n setProfile(profile)\n if (profile.threadIds) {", "score": 0.872551441192627 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Home: NextPage = () => {\n const setProfile = useStore((state) => state.setProfile);\n const setProfiles = useStore((state) => state.setProfiles);\n const setThreads = useStore((state) => state.setThreads);\n const selectedProfile = useStore((state) => state.selectedProfile);\n const setSelectedProfile = useStore((state) => state.setSelectedProfile);\n useEffect(() => {\n const data = loadData();\n if (!data) {\n return", "score": 0.8572671413421631 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 0.8320413827896118 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n if (data.selectedProfile) {\n setSelectedProfile(data.selectedProfile)\n }\n if (data.profile) {\n setProfile(data.profile)\n }\n if (data.profiles) {\n setProfiles(data.profiles)\n }", "score": 0.8290743827819824 } ]
typescript
filter((t) => t !== undefined) as Thread[];
import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import AzureADProvider from "next-auth/providers/azure-ad"; 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: [ AzureADProvider({
clientId: env.AZURE_CLIENT_ID, clientSecret: env.AZURE_CLIENT_SECRET, }), /** * ...add more providers here. * * Most other providers require a bit more work than the Discord provider. For example, the * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account * model. Refer to the NextAuth.js docs for the provider you want to use. Example: * * @see https://next-auth.js.org/providers/github */ ], }; /** * 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
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " return next({\n ctx: {\n // infers the `session` as non-nullable\n session: { ...ctx.session, user: ctx.session.user },\n },\n });\n});\n/**\n * Protected (authenticated) procedure\n *", "score": 0.7830052971839905 }, { "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.7816963195800781 }, { "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\";\nconst MyApp: AppType<{ session: Session | null }> = ({\n Component,\n pageProps: { session, ...pageProps },\n}) => {\n return (", "score": 0.7759462594985962 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " *\n * This section defines the \"contexts\" that are available in the backend API.\n *\n * These allow you to access things when processing a request, like the database, the session, etc.\n */\nimport { type CreateNextContextOptions } from \"@trpc/server/adapters/next\";\nimport { type Session } from \"next-auth\";\nimport { getServerAuthSession } from \"~/server/auth\";\nimport { prisma } from \"~/server/db\";\ntype CreateContextOptions = {", "score": 0.7751239538192749 }, { "filename": "src/server/api/routers/gpt.ts", "retrieved_chunk": " .input(\n z.object({\n apiKey: z.string(),\n model: z.string(),\n messages: z.array(\n z.object({\n role: z.enum([\"user\", \"system\", \"assistant\"]),\n content: z.string(),\n })\n ),", "score": 0.7651554346084595 } ]
typescript
adapter: PrismaAdapter(prisma), providers: [ AzureADProvider({
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json');
await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {
headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {\n\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\tprivate buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string {", "score": 0.8628984689712524 }, { "filename": "src/lib/Global.ts", "retrieved_chunk": "import axios, { AxiosResponse } from 'axios';\nimport { API, Endpoints, InstituteGlobal } from '../types';\nimport tryRequest from '../utils/tryRequest';\nexport default class Global {\n\tconstructor() {\n\t}\n\tpublic getInstituteList(): Promise<InstituteGlobal[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.GLOBAL + Endpoints.PublikusIntezmenyek, {\n\t\t\t\theaders: {", "score": 0.8591025471687317 }, { "filename": "src/lib/Global.ts", "retrieved_chunk": "\t\t\t\t\t'api-version': 'v1'\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<InstituteGlobal[]>) => resolve(r.data)));\n\t\t});\n\t}\n}", "score": 0.8473261594772339 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';\n\t\treturn API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams;\n\t}\n\t@requireCredentials\n\tpublic getAddresseeType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 0.8372890949249268 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), {", "score": 0.8102493286132812 } ]
typescript
await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "",
} as Thread;
export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds .map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[]; return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/types/appstate.ts", "retrieved_chunk": " promptCost?: number;\n completionCost?: number;\n usageCost?: number;\n note?: string;\n}\nexport type Thread = {\n id: string;\n profileId: string;\n messages: Message[];\n model: Model;", "score": 0.8875889182090759 }, { "filename": "src/types/appstate.ts", "retrieved_chunk": " cost: number;\n budget: number;\n threadIds: string[];\n};\nexport interface Model {\n id: string;\n maxTokens: number;\n name: string;\n description: string;\n trainingData: string;", "score": 0.8638857007026672 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " model: thread.model.id,\n apiKey: profile.key,\n messages\n }, {\n onSuccess: (data) => {\n const cost = calculateCost(data.usage, thread.model)\n setThread({\n ...thread,\n profileId: profile.id,\n id,", "score": 0.8534453511238098 }, { "filename": "src/types/appstate.ts", "retrieved_chunk": " initialSystemInstruction: string;\n title: string;\n description: string;\n starred: boolean;\n cost: number;\n budget: number;\n};", "score": 0.8480478525161743 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " title: 'New Chat',\n cost: thread.cost + cost,\n messages: [...thread.messages, { content: message, role: \"user\" },\n data.choices[0].message] as Message[]\n })\n setProfile({\n ...profile,\n cost: profile.cost + cost,\n usage: increaseUsage(profile.usage, data.usage),\n threadIds: [...profile.threadIds, id]", "score": 0.8386701345443726 } ]
typescript
} as Thread;
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); }
@requireCredentials public getStudent(): Promise<Student> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Global.ts", "retrieved_chunk": "\t\t\t\t\t'api-version': 'v1'\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<InstituteGlobal[]>) => resolve(r.data)));\n\t\t});\n\t}\n}", "score": 0.85880047082901 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getTeachers(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), {\n\t\t\t\theaders: {", "score": 0.8555919528007507 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getClassMasters(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), {\n\t\t\t\theaders: {", "score": 0.8434727787971497 }, { "filename": "src/lib/Global.ts", "retrieved_chunk": "import axios, { AxiosResponse } from 'axios';\nimport { API, Endpoints, InstituteGlobal } from '../types';\nimport tryRequest from '../utils/tryRequest';\nexport default class Global {\n\tconstructor() {\n\t}\n\tpublic getInstituteList(): Promise<InstituteGlobal[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.GLOBAL + Endpoints.PublikusIntezmenyek, {\n\t\t\t\theaders: {", "score": 0.8431662917137146 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data)));\n\t\t});\n\t}\n}", "score": 0.8401850461959839 } ]
typescript
@requireCredentials public getStudent(): Promise<Student> {
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "", } as Thread; export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds .
map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[];
return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " const threads = profile.threadIds.map((id) => {\n return getThread(id)\n }) as Thread[]\n setThreads(threads)\n }\n }\n }\n }, [selectedProfile, setProfile, setThreads]);\n return (\n <>", "score": 0.880139172077179 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " if (data.threads) {\n setThreads(data.threads)\n }\n }, [setProfile, setProfiles, setThreads, setSelectedProfile]);\n useEffect(() => {\n if (selectedProfile) {\n const profile = getProfile(selectedProfile)\n if (profile) {\n setProfile(profile)\n if (profile.threadIds) {", "score": 0.8735814690589905 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Home: NextPage = () => {\n const setProfile = useStore((state) => state.setProfile);\n const setProfiles = useStore((state) => state.setProfiles);\n const setThreads = useStore((state) => state.setThreads);\n const selectedProfile = useStore((state) => state.selectedProfile);\n const setSelectedProfile = useStore((state) => state.setSelectedProfile);\n useEffect(() => {\n const data = loadData();\n if (!data) {\n return", "score": 0.8567985892295837 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 0.8301752209663391 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n if (data.selectedProfile) {\n setSelectedProfile(data.selectedProfile)\n }\n if (data.profile) {\n setProfile(data.profile)\n }\n if (data.profiles) {\n setProfiles(data.profiles)\n }", "score": 0.8297394514083862 } ]
typescript
map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[];
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; }; @requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username });
await tryRequest(axios.post(API.IDP + Endpoints.Token, {
institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null) return reject(new KretaError('Failed to get access token: Invalid credentials')); else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 0.8750126361846924 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 0.8371448516845703 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\tthis.institute_code = options?.institute_code || '';\n\t\taxios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0';\n\t\tthis.Global = new Global();\n\t\tthis.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\tthis.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t}\n\tpublic get _username() {\n\t\treturn this.username;", "score": 0.8196648359298706 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst ops: { datumTol?: string; datumIg?: string } = {};\n\t\t\tif (options?.dateFrom)\n\t\t\t\tops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));\n\t\t\tif (options?.dateTo)\n\t\t\t\tops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD'));\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 0.818578839302063 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\tpublic getInstitute(): Promise<Institution> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Institution>) => resolve(r.data)));", "score": 0.8183388710021973 } ]
typescript
await tryRequest(axios.post(API.IDP + Endpoints.Token, {
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; } @requireCredentials public getAddresseeType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await
tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {
headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\tpublic getInstitute(): Promise<Institution> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Institution>) => resolve(r.data)));", "score": 0.8193591833114624 }, { "filename": "src/types.ts", "retrieved_chunk": "\tEloadasok = '/Lep/Eloadasok',\n\tEszkozAllapot = '/TargyiEszkoz/IsEszkozKiosztva'\n}\nexport enum AdministrationEndpoints {\n\tCimzettTipusok = '/adatszotarak/cimzetttipusok',\n\tKerelemTipusok = '/adatszotarak/kerelemtipusok',\n\tTmgiIgazolasTipusok = '/adatszotarak/tmgiigazolastipusok',\n\tEsemenyek = '/belepteto/kartyaesemenyek/sajat',\n\tJelenlegiIntezmenyModulok = '/intezmenyek/sajat/modulok',\n\tCimezhetoTipusok = '/kommunikacio/cimezhetotipusok',", "score": 0.8160766363143921 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Homework[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uid')\n\tpublic getHomework(uid: string | number): Promise<Homework> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), {\n\t\t\t\theaders: {", "score": 0.8140100836753845 }, { "filename": "src/lib/Global.ts", "retrieved_chunk": "import axios, { AxiosResponse } from 'axios';\nimport { API, Endpoints, InstituteGlobal } from '../types';\nimport tryRequest from '../utils/tryRequest';\nexport default class Global {\n\tconstructor() {\n\t}\n\tpublic getInstituteList(): Promise<InstituteGlobal[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.GLOBAL + Endpoints.PublikusIntezmenyek, {\n\t\t\t\theaders: {", "score": 0.8112097382545471 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\taxios.defaults.proxy = proxy;\n\t\treturn this;\n\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t}\n\tprivate buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string {\n\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';", "score": 0.8083150386810303 } ]
typescript
tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.
datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getTeachers(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), {\n\t\t\t\theaders: {", "score": 0.8213887810707092 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getClassMasters(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), {\n\t\t\t\theaders: {", "score": 0.812777042388916 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAccessControlSystemEvents(): Promise<CardEvent[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 0.8114401698112488 }, { "filename": "src/types.ts", "retrieved_chunk": "\tdateFrom?: string;\n\tdateTo?: string;\n}\nexport interface RequestDateRangeRequiredOptions {\n\tdateFrom: string;\n\tdateTo: string;\n}\nexport interface RequestClassAveragesOptions {\n\toktatasiNevelesiFeladatUid?: string;\n\tsubjectUid?: string;", "score": 0.8114047050476074 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCurrentInstitutionModules(): Promise<string[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 0.8059467077255249 } ]
typescript
datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; }; @requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null) return
reject(new KretaError('Failed to get access token: Invalid credentials'));
else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/types.ts", "retrieved_chunk": "\ttoken_type: string | null;\n}\nexport interface KretaOptions extends AuthenticationFields {\n}\nexport interface AuthenticationResponse {\n\taccess_token: string;\n\texpires_in: number;\n\tid_token: string | null;\n\trefresh_token: string;\n\tscope: string;", "score": 0.8520869612693787 }, { "filename": "src/types.ts", "retrieved_chunk": "\tpassword: string;\n\tusername: string;\n}\nexport interface RequestRefreshTokenOptions {\n\trefreshUserData: boolean;\n\trefreshToken: string;\n}\nexport interface AccessToken {\n\taccess_token: string | null;\n\trefresh_token: string | null;", "score": 0.8422414064407349 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 0.8231488466262817 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 0.822026252746582 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\tpublic getInstitute(): Promise<Institution> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Institution>) => resolve(r.data)));", "score": 0.8142477869987488 } ]
typescript
reject(new KretaError('Failed to get access token: Invalid credentials'));
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; } @
requireCredentials public getAddresseeType(): Promise<AddresseType[]> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;\n\t}\n\t@requireParam('api_key')\n\tpublic getInstituteList(api_key: string): Promise<Institute[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json');\n\t\t\tawait tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {\n\t\t\t\theaders: {\n\t\t\t\t\tapiKey: api_key\n\t\t\t\t}", "score": 0.8334308862686157 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\tpublic getInstitute(): Promise<Institution> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Institution>) => resolve(r.data)));", "score": 0.8287240266799927 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<Institute[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getStudent(): Promise<Student> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 0.8068989515304565 }, { "filename": "src/types.ts", "retrieved_chunk": "}\nexport interface SchoolYearCalendarEntry {\n\tDatum: string;\n\tElteroOrarendSzerintiTanitasiNap: ValueDescriptor | null;\n\tNaptipus: ValueDescriptor;\n\tOrarendiNapHetirendje: ValueDescriptor;\n\tOsztalyCsoport: UidStructure | null;\n\tUid: string;\n}\nexport interface AddresseType {", "score": 0.8057716488838196 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> {", "score": 0.7964779138565063 } ]
typescript
requireCredentials public getAddresseeType(): Promise<AddresseType[]> {
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @
requireCredentials public getStudent(): Promise<Student> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Global.ts", "retrieved_chunk": "\t\t\t\t\t'api-version': 'v1'\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<InstituteGlobal[]>) => resolve(r.data)));\n\t\t});\n\t}\n}", "score": 0.8680824041366577 }, { "filename": "src/lib/Global.ts", "retrieved_chunk": "import axios, { AxiosResponse } from 'axios';\nimport { API, Endpoints, InstituteGlobal } from '../types';\nimport tryRequest from '../utils/tryRequest';\nexport default class Global {\n\tconstructor() {\n\t}\n\tpublic getInstituteList(): Promise<InstituteGlobal[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.GLOBAL + Endpoints.PublikusIntezmenyek, {\n\t\t\t\theaders: {", "score": 0.8442066311836243 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getTeachers(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), {\n\t\t\t\theaders: {", "score": 0.8437023162841797 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data)));\n\t\t});\n\t}\n}", "score": 0.8428546190261841 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), {", "score": 0.8337724208831787 } ]
typescript
requireCredentials public getStudent(): Promise<Student> {
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom)
ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getTeachers(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), {\n\t\t\t\theaders: {", "score": 0.8163871765136719 }, { "filename": "src/types.ts", "retrieved_chunk": "\tdateFrom?: string;\n\tdateTo?: string;\n}\nexport interface RequestDateRangeRequiredOptions {\n\tdateFrom: string;\n\tdateTo: string;\n}\nexport interface RequestClassAveragesOptions {\n\toktatasiNevelesiFeladatUid?: string;\n\tsubjectUid?: string;", "score": 0.8134242296218872 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAccessControlSystemEvents(): Promise<CardEvent[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 0.8086307644844055 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getClassMasters(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), {\n\t\t\t\theaders: {", "score": 0.8080769777297974 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCurrentInstitutionModules(): Promise<string[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 0.8035091757774353 } ]
typescript
ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
import debugPackage from "debug"; import { bold, cyan, dim, red, reset, yellow } from "kleur/colors"; import * as readline from "readline"; import { Writable } from "stream"; import stringWidth from "string-width"; import { dateTimeFormat, error, info, warn } from "./core.js"; type ConsoleStream = Writable & { fd: 1 | 2; }; let lastMessage: string; let lastMessageCount = 1; export const nodeLogDestination = new Writable({ objectMode: true, write(event: LogMessage, _, callback) { let dest: ConsoleStream = process.stderr; if (levels[event.level] < levels["error"]) { dest = process.stdout; } function getPrefix() { let prefix = ""; let type = event.type; if (type) { // hide timestamp when type is undefined prefix += dim(dateTimeFormat.format(new Date()) + " "); if (event.level === "info") { type = bold(cyan(`[${type}]`)); } else if (event.level === "warn") { type = bold(yellow(`[${type}]`)); } else if (event.level === "error") { type = bold(red(`[${type}]`)); } prefix += `${type} `; } return reset(prefix); } // console.log({msg: event.message, args: event.args}); let message = event.message; // For repeat messages, only update the message counter if (message === lastMessage) { lastMessageCount++; if (levels[event.level] < levels["error"]) { let lines = 1; let len = stringWidth(`${getPrefix()}${message}`); let cols = (dest as unknown as typeof process.stdout).columns; if (len > cols) { lines = Math.ceil(len / cols); } for (let i = 0; i < lines; i++) { readline.clearLine(dest, 0); readline.cursorTo(dest, 0); readline.moveCursor(dest, 0, -1); } } message = `${message} ${yellow(`(x${lastMessageCount})`)}`; } else { lastMessage = message; lastMessageCount = 1; } dest.write(getPrefix()); dest.write(message); dest.write("\n"); callback(); }, }); interface LogWritable<T> { write: (chunk: T) => boolean; } export type LoggerLevel = "debug" | "info" | "warn" | "error" | "silent"; // same as Pino export type LoggerEvent = "info" | "warn" | "error"; export interface LogOptions { dest?: LogWritable<LogMessage>; level?: LoggerLevel; } export const nodeLogOptions: Required<LogOptions> = { dest: nodeLogDestination, level: "info", }; export interface LogMessage { type: string | null; level: LoggerLevel; message: string; } export const levels: Record<LoggerLevel, number> = { debug: 20, info: 30, warn: 40, error: 50, silent: 90, }; const debuggers: Record<string, debugPackage.Debugger["log"]> = {}; /** * Emit a message only shown in debug mode. * Astro (along with many of its dependencies) uses the `debug` package for debug logging. * You can enable these logs with the `DEBUG=astro:*` environment variable. * More info https://github.com/debug-js/debug#environment-variables */ export function debug(type: string, ...messages: Array<any>) { const namespace = `astro:${type}`; debuggers[namespace] = debuggers[namespace] || debugPackage(namespace); return debuggers[namespace](...messages); } // This is gross, but necessary since we are depending on globals. (globalThis as any)._astroGlobalDebug = debug; // A default logger for when too lazy to pass LogOptions around. export const logger = { info: info.bind(null, nodeLogOptions), warn: warn.bind(null, nodeLogOptions), error:
error.bind(null, nodeLogOptions), };
export function enableVerboseLogging() { debug("cli", '--verbose flag enabled! Enabling: DEBUG="*,-babel"'); debug( "cli", 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".' ); }
src/astro/logger/node.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\nexport let defaultLogLevel: LoggerLevel;\nif (typeof process !== \"undefined\") {\n // This could be a shimmed environment so we don't know that `process` is the full\n // NodeJS.process. This code treats it as a plain object so TS doesn't let us\n // get away with incorrect assumptions.\n let proc: object = process;\n if (\"argv\" in proc && Array.isArray(proc.argv)) {\n if (proc.argv.includes(\"--verbose\")) {\n defaultLogLevel = \"debug\";", "score": 0.8371034860610962 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n/** Emit a warning message. Useful for high-priority messages that aren't necessarily errors. */\nexport function warn(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"warn\", type, message);\n}\n/** Emit a error message, Useful when Astro can't recover from some error. */\nexport function error(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"error\", type, message);\n}\ntype LogFn = typeof info | typeof warn | typeof error;", "score": 0.8338992595672607 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export function table(opts: LogOptions, columns: number[]) {\n return function logTable(logFn: LogFn, ...input: Array<any>) {\n const message = columns\n .map((len, i) => padStr(input[i].toString(), len))\n .join(\" \");\n logFn(opts, null, message);\n };\n}\nexport function debug(...args: any[]) {\n if (\"_astroGlobalDebug\" in globalThis) {", "score": 0.8310648202896118 }, { "filename": "src/integration/integration.ts", "retrieved_chunk": "import path from \"node:path\";\nimport type { AstroConfig, AstroIntegration } from \"astro\";\nimport dedent from \"dedent\";\nimport fg from \"fast-glob\";\nimport fs from \"fs-extra\";\nimport slash from \"slash\";\nimport { logger } from \"../astro/logger/node\";\nimport { removeLeadingForwardSlashWindows } from \"../astro/internal-helpers/path\";\nimport { defaultI18nConfig } from \"../shared/configs\";\nimport type { UserI18nConfig, I18nConfig } from \"../shared/configs\";", "score": 0.8229368925094604 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export const levels: Record<LoggerLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n silent: 90,\n};\n/** Full logging API */\nexport function log(\n opts: LogOptions,", "score": 0.8066450953483582 } ]
typescript
error.bind(null, nodeLogOptions), };
import debugPackage from "debug"; import { bold, cyan, dim, red, reset, yellow } from "kleur/colors"; import * as readline from "readline"; import { Writable } from "stream"; import stringWidth from "string-width"; import { dateTimeFormat, error, info, warn } from "./core.js"; type ConsoleStream = Writable & { fd: 1 | 2; }; let lastMessage: string; let lastMessageCount = 1; export const nodeLogDestination = new Writable({ objectMode: true, write(event: LogMessage, _, callback) { let dest: ConsoleStream = process.stderr; if (levels[event.level] < levels["error"]) { dest = process.stdout; } function getPrefix() { let prefix = ""; let type = event.type; if (type) { // hide timestamp when type is undefined prefix += dim(dateTimeFormat.format(new Date()) + " "); if (event.level === "info") { type = bold(cyan(`[${type}]`)); } else if (event.level === "warn") { type = bold(yellow(`[${type}]`)); } else if (event.level === "error") { type = bold(red(`[${type}]`)); } prefix += `${type} `; } return reset(prefix); } // console.log({msg: event.message, args: event.args}); let message = event.message; // For repeat messages, only update the message counter if (message === lastMessage) { lastMessageCount++; if (levels[event.level] < levels["error"]) { let lines = 1; let len = stringWidth(`${getPrefix()}${message}`); let cols = (dest as unknown as typeof process.stdout).columns; if (len > cols) { lines = Math.ceil(len / cols); } for (let i = 0; i < lines; i++) { readline.clearLine(dest, 0); readline.cursorTo(dest, 0); readline.moveCursor(dest, 0, -1); } } message = `${message} ${yellow(`(x${lastMessageCount})`)}`; } else { lastMessage = message; lastMessageCount = 1; } dest.write(getPrefix()); dest.write(message); dest.write("\n"); callback(); }, }); interface LogWritable<T> { write: (chunk: T) => boolean; } export type LoggerLevel = "debug" | "info" | "warn" | "error" | "silent"; // same as Pino export type LoggerEvent = "info" | "warn" | "error"; export interface LogOptions { dest?: LogWritable<LogMessage>; level?: LoggerLevel; } export const nodeLogOptions: Required<LogOptions> = { dest: nodeLogDestination, level: "info", }; export interface LogMessage { type: string | null; level: LoggerLevel; message: string; } export const levels: Record<LoggerLevel, number> = { debug: 20, info: 30, warn: 40, error: 50, silent: 90, }; const debuggers: Record<string, debugPackage.Debugger["log"]> = {}; /** * Emit a message only shown in debug mode. * Astro (along with many of its dependencies) uses the `debug` package for debug logging. * You can enable these logs with the `DEBUG=astro:*` environment variable. * More info https://github.com/debug-js/debug#environment-variables */ export function debug(type: string, ...messages: Array<any>) { const namespace = `astro:${type}`; debuggers[namespace] = debuggers[namespace] || debugPackage(namespace); return debuggers[namespace](...messages); } // This is gross, but necessary since we are depending on globals. (globalThis as any)._astroGlobalDebug = debug; // A default logger for when too lazy to pass LogOptions around. export const logger = { info: info.bind(null, nodeLogOptions),
warn: warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
export function enableVerboseLogging() { debug("cli", '--verbose flag enabled! Enabling: DEBUG="*,-babel"'); debug( "cli", 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".' ); }
src/astro/logger/node.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export function table(opts: LogOptions, columns: number[]) {\n return function logTable(logFn: LogFn, ...input: Array<any>) {\n const message = columns\n .map((len, i) => padStr(input[i].toString(), len))\n .join(\" \");\n logFn(opts, null, message);\n };\n}\nexport function debug(...args: any[]) {\n if (\"_astroGlobalDebug\" in globalThis) {", "score": 0.8389616012573242 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\nexport let defaultLogLevel: LoggerLevel;\nif (typeof process !== \"undefined\") {\n // This could be a shimmed environment so we don't know that `process` is the full\n // NodeJS.process. This code treats it as a plain object so TS doesn't let us\n // get away with incorrect assumptions.\n let proc: object = process;\n if (\"argv\" in proc && Array.isArray(proc.argv)) {\n if (proc.argv.includes(\"--verbose\")) {\n defaultLogLevel = \"debug\";", "score": 0.8206468820571899 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n/** Emit a warning message. Useful for high-priority messages that aren't necessarily errors. */\nexport function warn(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"warn\", type, message);\n}\n/** Emit a error message, Useful when Astro can't recover from some error. */\nexport function error(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"error\", type, message);\n}\ntype LogFn = typeof info | typeof warn | typeof error;", "score": 0.8201455473899841 }, { "filename": "src/integration/integration.ts", "retrieved_chunk": "import path from \"node:path\";\nimport type { AstroConfig, AstroIntegration } from \"astro\";\nimport dedent from \"dedent\";\nimport fg from \"fast-glob\";\nimport fs from \"fs-extra\";\nimport slash from \"slash\";\nimport { logger } from \"../astro/logger/node\";\nimport { removeLeadingForwardSlashWindows } from \"../astro/internal-helpers/path\";\nimport { defaultI18nConfig } from \"../shared/configs\";\nimport type { UserI18nConfig, I18nConfig } from \"../shared/configs\";", "score": 0.8062593340873718 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export const levels: Record<LoggerLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n silent: 90,\n};\n/** Full logging API */\nexport function log(\n opts: LogOptions,", "score": 0.7981454133987427 } ]
typescript
warn: warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return
dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;
} @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {\n\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\tprivate buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string {", "score": 0.8622578978538513 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 0.8439509868621826 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\t@requireParam('proxy.host')\n\t@requireParam('proxy.port')\n\tpublic setProxy(proxy: AxiosProxyConfig): this {\n\t\taxios.defaults.proxy = proxy;\n\t\treturn this;", "score": 0.7981436252593994 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';\n\t\treturn API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams;\n\t}\n\t@requireCredentials\n\tpublic getAddresseeType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 0.7951529026031494 }, { "filename": "src/types.ts", "retrieved_chunk": "export enum Endpoints {\n\tToken = '/connect/token',\n\tNonce = '/nonce',\n\tPublikusIntezmenyek = '/intezmenyek/kreta/publikus',\n\tFeljegyzesek = '/Sajat/Feljegyzesek',\n\tFaliujsagElemek = '/Sajat/FaliujsagElemek',\n\tTanulo = '/Sajat/TanuloAdatlap',\n\tErtekelesek = '/Sajat/Ertekelesek',\n\tTantargyiAtlagok = '/Sajat/Ertekelesek/Atlagok/TantargyiAtlagok',\n\tMulasztasok = '/Sajat/Mulasztasok',", "score": 0.7788561582565308 } ]
typescript
dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;
import path from "node:path"; import type { AstroConfig, AstroIntegration } from "astro"; import dedent from "dedent"; import fg from "fast-glob"; import fs from "fs-extra"; import slash from "slash"; import { logger } from "../astro/logger/node"; import { removeLeadingForwardSlashWindows } from "../astro/internal-helpers/path"; import { defaultI18nConfig } from "../shared/configs"; import type { UserI18nConfig, I18nConfig } from "../shared/configs"; // injectRoute doesn't generate build pages https://github.com/withastro/astro/issues/5096 // workaround: copy pages folder when command === "build" /** * The i18n integration for Astro * * See the full [astro-i18n-aut](https://github.com/jlarmstrongiv/astro-i18n-aut#readme) documentation */ export function i18n(userI18nConfig: UserI18nConfig): AstroIntegration { const i18nConfig: I18nConfig = Object.assign( defaultI18nConfig, userI18nConfig ); const { defaultLocale, locales, exclude, include, redirectDefaultLocale } = i18nConfig; ensureValidLocales(locales, defaultLocale); let pagesPathTmp: Record<string, string> = {}; async function removePagesPathTmp(): Promise<void> { await Promise.all( Object.values(pagesPathTmp).map((pagePathTmp) => fs.remove(pagePathTmp)) ); } return { name: "astro-i18n-integration", hooks: { "astro:config:setup": async ({ config, command, injectRoute }) => { await ensureValidConfigs(config, i18nConfig); const configSrcDirPathname = path.normalize( removeLeadingForwardSlashWindows(config.srcDir.pathname) ); let included: string[] = ensureGlobsHaveConfigSrcDirPathname( typeof include === "string" ? [include] : include, configSrcDirPathname ); let excluded: string[] = ensureGlobsHaveConfigSrcDirPathname( typeof exclude === "string" ? [exclude] : exclude, configSrcDirPathname ); const pagesPath = path.join(configSrcDirPathname, "pages"); const pagesPathTmpRoot = path.join( configSrcDirPathname, // tmp filename from https://github.com/withastro/astro/blob/e6bff651ff80466b3e862e637d2a6a3334d8cfda/packages/astro/src/core/routing/manifest/create.ts#L279 "astro_tmp_pages" ); for (const locale of Object.keys(locales)) { pagesPathTmp[locale] = `${pagesPathTmpRoot}_${locale}`; } await removePagesPathTmp(); if (command === "build") { await Promise.all( Object.keys(locales) .filter((locale) => { if (redirectDefaultLocale === false) { return locale !== defaultLocale; } else { return true; } }) .map((locale) => fs.copy(pagesPath, pagesPathTmp[locale])) ); } const entries = fg.stream(included, { ignore: excluded, onlyFiles: true, }); // typing https://stackoverflow.com/a/68358341 let entry: string; // @ts-expect-error for await (entry of entries) { const parsedPath = path.parse(entry); const relativePath = path.relative(pagesPath, parsedPath.dir); const extname = parsedPath.ext.slice(1).toLowerCase(); // warn on files that cannot be translated with specific and actionable warnings // astro pages file types https://docs.astro.build/en/core-concepts/astro-pages/#supported-page-files // any file that is not included as an astro page file types, will be automatically warned about by astro if (extname !== "astro") { warnIsInvalidPage( extname, path.join(relativePath, parsedPath.base), configSrcDirPathname ); continue; } for (const locale of Object.keys(locales)) { // ignore defaultLocale if redirectDefaultLocale is false if (redirectDefaultLocale === false && locale === defaultLocale) { continue; } const entryPoint = command === "build" ? path.join(pagesPathTmp[locale], relativePath, parsedPath.base) : path.join(pagesPath, relativePath, parsedPath.base); const pattern = slash( path.join( config.base, locale, relativePath, parsedPath.name.endsWith("index") ? "" : parsedPath.name, config.build.format === "directory" ? "/" : "" ) ); injectRoute({ entryPoint, pattern, }); } } }, "astro:build:done": async () => { await removePagesPathTmp(); }, "astro:server:done": async () => { await removePagesPathTmp(); }, }, }; } function ensureValidLocales( locales: Record<string, string>, defaultLocale: string ) { if (!Object.keys(locales).includes(defaultLocale)) { const errorMessage = `locales ${JSON.stringify( locales )} does not include "${defaultLocale}"`; logger
.error("astro-i18n-aut", errorMessage);
throw new Error(errorMessage); } } async function ensureValidConfigs(config: AstroConfig, i18nConfig: I18nConfig) { if (config.trailingSlash === "ignore" && config.output === "static") { logger.warn( "astro-i18n-aut", `avoid setting config.trailingSlash = "ignore" when config.output = "static"` ); logger.warn( "astro-i18n-aut", `config.trailingSlash = "always" && config.build.format = "directory"` ); logger.warn( "astro-i18n-aut", `config.trailingSlash = "never" && config.build.format = "file"` ); logger.warn( "astro-i18n-aut", `setting config.trailingSlash = "${config.trailingSlash}"` ); config.trailingSlash = config.build.format === "directory" ? "always" : "never"; } if (i18nConfig.redirectDefaultLocale) { const configSrcDirPathname = path.normalize( removeLeadingForwardSlashWindows(config.srcDir.pathname) ); // all possible locations of middleware const defaultMiddlewarePath = path.join( configSrcDirPathname, "middleware/index.ts" ); const middlewarePaths = [ path.join(configSrcDirPathname, "middleware.js"), path.join(configSrcDirPathname, "middleware.ts"), path.join(configSrcDirPathname, "middleware/index.js"), defaultMiddlewarePath, ]; // check if middleware exists const pathsExist = await Promise.all( middlewarePaths.map((middlewarePath) => fs.exists(middlewarePath)) ); const pathExists = pathsExist.includes(true); // warn and create middleware if it does not exist if (pathExists === false) { logger.warn("astro-i18n-aut", `cannot find any Astro middleware files:`); middlewarePaths.forEach((middlewarePath) => { logger.warn("astro-i18n-aut", `- ${middlewarePath}`); }); logger.warn( "astro-i18n-aut", `creating ${defaultMiddlewarePath} with defaultLocale = "en"` ); await fs.outputFile( defaultMiddlewarePath, dedent(` import { sequence } from "astro/middleware"; import { i18nMiddleware } from "astro-i18n-aut"; const i18n = i18nMiddleware({ defaultLocale: "en" }); export const onRequest = sequence(i18n); `) ); } } } function ensureGlobsHaveConfigSrcDirPathname( filePaths: string[], configSrcDirPathname: string ) { return filePaths.map((filePath) => { filePath = path.normalize(removeLeadingForwardSlashWindows(filePath)); if (filePath.includes(configSrcDirPathname)) { filePath = path.relative(configSrcDirPathname, filePath); } // fast-glob prefers unix paths https://www.npmjs.com/package/fast-glob#how-to-write-patterns-on-windows filePath = path.posix.join( fg.convertPathToPattern(configSrcDirPathname), slash(filePath) ); return filePath; }); } let hasWarnedIsInvalidPage = false; function warnIsInvalidPage( extname: string, filePath: string, configSrcDirPathname: string ): boolean { // astro pages file types https://docs.astro.build/en/core-concepts/astro-pages/#supported-page-files if (["js", "ts", "md", "mdx", "html"].includes(extname)) { if (hasWarnedIsInvalidPage === false) { logger.warn( "astro-i18n-aut", `exclude or remove non-astro files from "${configSrcDirPathname}pages", as they cannot be translated` ); hasWarnedIsInvalidPage = true; } logger.warn( "astro-i18n-aut", path.join(configSrcDirPathname, "pages", filePath) ); return true; } return false; }
src/integration/integration.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/shared/configs.ts", "retrieved_chunk": " * fr: \"fr-CA\",\n * };\n * ```\n */\n locales: Record<string, string>;\n /**\n * the default language locale\n *\n * the `defaultLocale` value must present in `locales` keys\n *", "score": 0.793294370174408 }, { "filename": "src/edge-runtime/middleware.ts", "retrieved_chunk": "import type { ValidRedirectStatus } from \"astro\";\nimport { defineMiddleware } from \"astro/middleware\";\nimport { defaultI18nMiddlewareConfig } from \"../shared/configs\";\nimport type {\n UserI18nMiddlewareConfig,\n I18nMiddlewareConfig,\n} from \"../shared/configs\";\nconst redirectDefaultLocaleDisabledMiddleware = defineMiddleware((_, next) =>\n next()\n);", "score": 0.7892681956291199 }, { "filename": "src/shared/defaultLocaleSitemapFilter.ts", "retrieved_chunk": "import type { UserDefaultLocaleSitemapFilterConfig } from \"./configs\";\n// sitemap filter https://docs.astro.build/en/guides/integrations-guide/sitemap/#filter\nexport function defaultLocaleSitemapFilter({\n defaultLocale,\n}: UserDefaultLocaleSitemapFilterConfig) {\n return function filter(page: string) {\n const pagePathname = new URL(page).pathname;\n return (\n // avoid catching urls that start with \"/en\" like \"/enigma\"\n pagePathname !== `/${defaultLocale}` &&", "score": 0.7776248455047607 }, { "filename": "src/shared/configs.ts", "retrieved_chunk": " */\n exclude?: string | string[];\n /**\n * all language locales\n *\n * @example\n * ```ts\n * const locales = {\n * en: \"en-US\", // the `defaultLocale` value must present in `locales` keys\n * es: \"es-ES\",", "score": 0.7761148810386658 }, { "filename": "src/shared/configs.ts", "retrieved_chunk": " [K in keyof T as T[K] extends Required<T>[K] ? never : K]: T[K];\n};\n/**\n * The default values for I18nConfig\n */\nexport const defaultI18nConfig: Required<PartialFieldsOnly<UserI18nConfig>> = {\n include: [\"pages/**/*\"],\n exclude: [\"pages/api/**/*\"],\n redirectDefaultLocale: true,\n};", "score": 0.7750392556190491 } ]
typescript
.error("astro-i18n-aut", errorMessage);
import debugPackage from "debug"; import { bold, cyan, dim, red, reset, yellow } from "kleur/colors"; import * as readline from "readline"; import { Writable } from "stream"; import stringWidth from "string-width"; import { dateTimeFormat, error, info, warn } from "./core.js"; type ConsoleStream = Writable & { fd: 1 | 2; }; let lastMessage: string; let lastMessageCount = 1; export const nodeLogDestination = new Writable({ objectMode: true, write(event: LogMessage, _, callback) { let dest: ConsoleStream = process.stderr; if (levels[event.level] < levels["error"]) { dest = process.stdout; } function getPrefix() { let prefix = ""; let type = event.type; if (type) { // hide timestamp when type is undefined prefix += dim(dateTimeFormat.format(new Date()) + " "); if (event.level === "info") { type = bold(cyan(`[${type}]`)); } else if (event.level === "warn") { type = bold(yellow(`[${type}]`)); } else if (event.level === "error") { type = bold(red(`[${type}]`)); } prefix += `${type} `; } return reset(prefix); } // console.log({msg: event.message, args: event.args}); let message = event.message; // For repeat messages, only update the message counter if (message === lastMessage) { lastMessageCount++; if (levels[event.level] < levels["error"]) { let lines = 1; let len = stringWidth(`${getPrefix()}${message}`); let cols = (dest as unknown as typeof process.stdout).columns; if (len > cols) { lines = Math.ceil(len / cols); } for (let i = 0; i < lines; i++) { readline.clearLine(dest, 0); readline.cursorTo(dest, 0); readline.moveCursor(dest, 0, -1); } } message = `${message} ${yellow(`(x${lastMessageCount})`)}`; } else { lastMessage = message; lastMessageCount = 1; } dest.write(getPrefix()); dest.write(message); dest.write("\n"); callback(); }, }); interface LogWritable<T> { write: (chunk: T) => boolean; } export type LoggerLevel = "debug" | "info" | "warn" | "error" | "silent"; // same as Pino export type LoggerEvent = "info" | "warn" | "error"; export interface LogOptions { dest?: LogWritable<LogMessage>; level?: LoggerLevel; } export const nodeLogOptions: Required<LogOptions> = { dest: nodeLogDestination, level: "info", }; export interface LogMessage { type: string | null; level: LoggerLevel; message: string; } export const levels: Record<LoggerLevel, number> = { debug: 20, info: 30, warn: 40, error: 50, silent: 90, }; const debuggers: Record<string, debugPackage.Debugger["log"]> = {}; /** * Emit a message only shown in debug mode. * Astro (along with many of its dependencies) uses the `debug` package for debug logging. * You can enable these logs with the `DEBUG=astro:*` environment variable. * More info https://github.com/debug-js/debug#environment-variables */ export function debug(type: string, ...messages: Array<any>) { const namespace = `astro:${type}`; debuggers[namespace] = debuggers[namespace] || debugPackage(namespace); return debuggers[namespace](...messages); } // This is gross, but necessary since we are depending on globals. (globalThis as any)._astroGlobalDebug = debug; // A default logger for when too lazy to pass LogOptions around. export const logger = { info: info.bind(null, nodeLogOptions), warn:
warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
export function enableVerboseLogging() { debug("cli", '--verbose flag enabled! Enabling: DEBUG="*,-babel"'); debug( "cli", 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".' ); }
src/astro/logger/node.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\nexport let defaultLogLevel: LoggerLevel;\nif (typeof process !== \"undefined\") {\n // This could be a shimmed environment so we don't know that `process` is the full\n // NodeJS.process. This code treats it as a plain object so TS doesn't let us\n // get away with incorrect assumptions.\n let proc: object = process;\n if (\"argv\" in proc && Array.isArray(proc.argv)) {\n if (proc.argv.includes(\"--verbose\")) {\n defaultLogLevel = \"debug\";", "score": 0.8368367552757263 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n/** Emit a warning message. Useful for high-priority messages that aren't necessarily errors. */\nexport function warn(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"warn\", type, message);\n}\n/** Emit a error message, Useful when Astro can't recover from some error. */\nexport function error(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"error\", type, message);\n}\ntype LogFn = typeof info | typeof warn | typeof error;", "score": 0.8326092958450317 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export function table(opts: LogOptions, columns: number[]) {\n return function logTable(logFn: LogFn, ...input: Array<any>) {\n const message = columns\n .map((len, i) => padStr(input[i].toString(), len))\n .join(\" \");\n logFn(opts, null, message);\n };\n}\nexport function debug(...args: any[]) {\n if (\"_astroGlobalDebug\" in globalThis) {", "score": 0.8311222791671753 }, { "filename": "src/integration/integration.ts", "retrieved_chunk": "import path from \"node:path\";\nimport type { AstroConfig, AstroIntegration } from \"astro\";\nimport dedent from \"dedent\";\nimport fg from \"fast-glob\";\nimport fs from \"fs-extra\";\nimport slash from \"slash\";\nimport { logger } from \"../astro/logger/node\";\nimport { removeLeadingForwardSlashWindows } from \"../astro/internal-helpers/path\";\nimport { defaultI18nConfig } from \"../shared/configs\";\nimport type { UserI18nConfig, I18nConfig } from \"../shared/configs\";", "score": 0.8230010271072388 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export const levels: Record<LoggerLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n silent: 90,\n};\n/** Full logging API */\nexport function log(\n opts: LogOptions,", "score": 0.8059767484664917 } ]
typescript
warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
require('dotenv').config(); import { AnyThreadChannel, ApplicationCommandOptionType, ApplicationCommandType, Channel, ChannelType, CommandInteraction, Guild, TextChannel } from 'discord.js'; import { GetTasks, SetThreadId, Task, TasksToString } from '../tasks'; import { Command } from '../types/Command'; import { ToDoClient } from '../types/ToDoClient'; export const Taskboard: Command = { name: "taskboard", description: "Set taskboard channel", type: ApplicationCommandType.ChatInput, options: [ { name: "channel", description: "The channel you want to set as the taskboard channel", required: true, type: ApplicationCommandOptionType.Channel } ], run: async (interaction: CommandInteraction, client: ToDoClient) => { let channelID = interaction.options.get('channel').value.toString(); let channel: Channel = await client.channels.fetch(channelID); let content = ""; if (channel.type == ChannelType.GuildText) { client.taskboardID = channelID; content = "okey taskboard is now channel with id: `" + channelID + "` aka " + channel.toString(); channel.send(`## This is the taskboard\n\n${TasksToString()}`); for (let task of GetTasks()) { let threadId = await CreateThreadForTask(task, client); SetThreadId(task.id, threadId); } } else { content = "bro this is not text channel, id `" + channelID + "` type: `" + channel.type + "` (https://discord.com/developers/docs/resources/channel) aka " + channel.toString(); } await interaction.followUp({ ephemeral: false, content }) } } export async function CreateThreadForTask(task: Task, client: ToDoClient): Promise<string> { let channel: TextChannel = await GetTaskboardTextChannel(client); let taskThread = await channel.threads.create({ name: `${task.id} | ${task.description} | <@${task.assignee}>`, type: ChannelType.PublicThread, }) taskThread.send(`${task.description}, for <@${task.assignee}> | ${task.id}`); return taskThread.id; } export async function CloseThreadForTask(task: Task, client: ToDoClient): Promise<AnyThreadChannel<boolean>> { let channel: TextChannel = await GetTaskboardTextChannel(client); let thread = await channel.
threads.fetch(task.threadId);
await thread.send("Task remove. Closing thread."); return await thread.setArchived(); } async function GetTaskboardTextChannel(client: ToDoClient): Promise<TextChannel> { return await client.channels.fetch(client.taskboardID) as TextChannel; } export async function SendMessageToThread(task: Task, client: ToDoClient): Promise<string> { // TODO return "" }
src/commands/taskboard.ts
savipauk-ToDoBot-a21f22e
[ { "filename": "src/commands/todo.ts", "retrieved_chunk": " if (client.taskboardID != null) {\n let threadId = await CreateThreadForTask(task, client);\n SetThreadId(task.id, threadId);\n }\n let content = `Set task \"${taskDesc}\" (ID ${task.id}) for ${user}`;\n await interaction.followUp({\n ephemeral: false,\n content\n })\n }", "score": 0.8626793026924133 }, { "filename": "src/commands/remove.ts", "retrieved_chunk": " let newTaskList = TasksToString();\n let content = \"Task doesn't exist\";\n if (task != null) {\n content = `Task \"${task.description}\" removed, ${interaction.user}\\n\\n${newTaskList}`;\n if (client.taskboardID != null) {\n await CloseThreadForTask(task, client);\n }\n }\n await interaction.followUp({\n ephemeral: false,", "score": 0.8551217913627625 }, { "filename": "src/tasks.ts", "retrieved_chunk": " return removedTask;\n}\nexport function SetThreadId(id: number, threadId: string): Task {\n let tasks = GetTasks();\n FlushTasks();\n let editedTask: Task = null;\n for (let task of tasks) {\n if (task.id == id) {\n if (threadId != undefined) task.threadId = threadId;\n editedTask = task;", "score": 0.8209189176559448 }, { "filename": "src/tasks.ts", "retrieved_chunk": "export function AddTask(description: string, assignee: string, threadId?: string): Task {\n let id = FindLastId();\n let task: Task = {\n id, description, assignee, threadId\n }\n _AddTask(task);\n return task;\n}\nexport function RemoveTask(id: number): Task {\n let tasks = GetTasks();", "score": 0.8180214166641235 }, { "filename": "src/commands/todo.ts", "retrieved_chunk": "import { ApplicationCommandOptionType, ApplicationCommandType, CommandInteraction, TextChannel } from 'discord.js';\nimport { AddTask, SetThreadId } from '../tasks';\nimport { Command } from '../types/Command';\nimport { ToDoClient } from '../types/ToDoClient';\nimport { CreateThreadForTask } from './taskboard';\nexport const Todo: Command = {\n name: \"todo\",\n description: \"Create a new task\",\n type: ApplicationCommandType.ChatInput,\n options: [", "score": 0.8089883923530579 } ]
typescript
threads.fetch(task.threadId);
import debugPackage from "debug"; import { bold, cyan, dim, red, reset, yellow } from "kleur/colors"; import * as readline from "readline"; import { Writable } from "stream"; import stringWidth from "string-width"; import { dateTimeFormat, error, info, warn } from "./core.js"; type ConsoleStream = Writable & { fd: 1 | 2; }; let lastMessage: string; let lastMessageCount = 1; export const nodeLogDestination = new Writable({ objectMode: true, write(event: LogMessage, _, callback) { let dest: ConsoleStream = process.stderr; if (levels[event.level] < levels["error"]) { dest = process.stdout; } function getPrefix() { let prefix = ""; let type = event.type; if (type) { // hide timestamp when type is undefined prefix += dim(dateTimeFormat.format(new Date()) + " "); if (event.level === "info") { type = bold(cyan(`[${type}]`)); } else if (event.level === "warn") { type = bold(yellow(`[${type}]`)); } else if (event.level === "error") { type = bold(red(`[${type}]`)); } prefix += `${type} `; } return reset(prefix); } // console.log({msg: event.message, args: event.args}); let message = event.message; // For repeat messages, only update the message counter if (message === lastMessage) { lastMessageCount++; if (levels[event.level] < levels["error"]) { let lines = 1; let len = stringWidth(`${getPrefix()}${message}`); let cols = (dest as unknown as typeof process.stdout).columns; if (len > cols) { lines = Math.ceil(len / cols); } for (let i = 0; i < lines; i++) { readline.clearLine(dest, 0); readline.cursorTo(dest, 0); readline.moveCursor(dest, 0, -1); } } message = `${message} ${yellow(`(x${lastMessageCount})`)}`; } else { lastMessage = message; lastMessageCount = 1; } dest.write(getPrefix()); dest.write(message); dest.write("\n"); callback(); }, }); interface LogWritable<T> { write: (chunk: T) => boolean; } export type LoggerLevel = "debug" | "info" | "warn" | "error" | "silent"; // same as Pino export type LoggerEvent = "info" | "warn" | "error"; export interface LogOptions { dest?: LogWritable<LogMessage>; level?: LoggerLevel; } export const nodeLogOptions: Required<LogOptions> = { dest: nodeLogDestination, level: "info", }; export interface LogMessage { type: string | null; level: LoggerLevel; message: string; } export const levels: Record<LoggerLevel, number> = { debug: 20, info: 30, warn: 40, error: 50, silent: 90, }; const debuggers: Record<string, debugPackage.Debugger["log"]> = {}; /** * Emit a message only shown in debug mode. * Astro (along with many of its dependencies) uses the `debug` package for debug logging. * You can enable these logs with the `DEBUG=astro:*` environment variable. * More info https://github.com/debug-js/debug#environment-variables */ export function debug(type: string, ...messages: Array<any>) { const namespace = `astro:${type}`; debuggers[namespace] = debuggers[namespace] || debugPackage(namespace); return debuggers[namespace](...messages); } // This is gross, but necessary since we are depending on globals. (globalThis as any)._astroGlobalDebug = debug; // A default logger for when too lazy to pass LogOptions around. export const logger = { info: info.bind(null, nodeLogOptions), warn: warn.bind(null, nodeLogOptions),
error: error.bind(null, nodeLogOptions), };
export function enableVerboseLogging() { debug("cli", '--verbose flag enabled! Enabling: DEBUG="*,-babel"'); debug( "cli", 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".' ); }
src/astro/logger/node.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export function table(opts: LogOptions, columns: number[]) {\n return function logTable(logFn: LogFn, ...input: Array<any>) {\n const message = columns\n .map((len, i) => padStr(input[i].toString(), len))\n .join(\" \");\n logFn(opts, null, message);\n };\n}\nexport function debug(...args: any[]) {\n if (\"_astroGlobalDebug\" in globalThis) {", "score": 0.8389616012573242 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\nexport let defaultLogLevel: LoggerLevel;\nif (typeof process !== \"undefined\") {\n // This could be a shimmed environment so we don't know that `process` is the full\n // NodeJS.process. This code treats it as a plain object so TS doesn't let us\n // get away with incorrect assumptions.\n let proc: object = process;\n if (\"argv\" in proc && Array.isArray(proc.argv)) {\n if (proc.argv.includes(\"--verbose\")) {\n defaultLogLevel = \"debug\";", "score": 0.8206468820571899 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n/** Emit a warning message. Useful for high-priority messages that aren't necessarily errors. */\nexport function warn(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"warn\", type, message);\n}\n/** Emit a error message, Useful when Astro can't recover from some error. */\nexport function error(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"error\", type, message);\n}\ntype LogFn = typeof info | typeof warn | typeof error;", "score": 0.8201455473899841 }, { "filename": "src/integration/integration.ts", "retrieved_chunk": "import path from \"node:path\";\nimport type { AstroConfig, AstroIntegration } from \"astro\";\nimport dedent from \"dedent\";\nimport fg from \"fast-glob\";\nimport fs from \"fs-extra\";\nimport slash from \"slash\";\nimport { logger } from \"../astro/logger/node\";\nimport { removeLeadingForwardSlashWindows } from \"../astro/internal-helpers/path\";\nimport { defaultI18nConfig } from \"../shared/configs\";\nimport type { UserI18nConfig, I18nConfig } from \"../shared/configs\";", "score": 0.8062593340873718 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export const levels: Record<LoggerLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n silent: 90,\n};\n/** Full logging API */\nexport function log(\n opts: LogOptions,", "score": 0.7981454133987427 } ]
typescript
error: error.bind(null, nodeLogOptions), };
require('dotenv').config(); import { AnyThreadChannel, ApplicationCommandOptionType, ApplicationCommandType, Channel, ChannelType, CommandInteraction, Guild, TextChannel } from 'discord.js'; import { GetTasks, SetThreadId, Task, TasksToString } from '../tasks'; import { Command } from '../types/Command'; import { ToDoClient } from '../types/ToDoClient'; export const Taskboard: Command = { name: "taskboard", description: "Set taskboard channel", type: ApplicationCommandType.ChatInput, options: [ { name: "channel", description: "The channel you want to set as the taskboard channel", required: true, type: ApplicationCommandOptionType.Channel } ], run: async (interaction: CommandInteraction, client: ToDoClient) => { let channelID = interaction.options.get('channel').value.toString(); let channel: Channel = await client.channels.fetch(channelID); let content = ""; if (channel.type == ChannelType.GuildText) { client.taskboardID = channelID; content = "okey taskboard is now channel with id: `" + channelID + "` aka " + channel.toString(); channel.send(`## This is the taskboard\n\n${TasksToString()}`); for (let task of GetTasks()) { let threadId = await CreateThreadForTask(task, client); SetThreadId(task.id, threadId); } } else { content = "bro this is not text channel, id `" + channelID + "` type: `" + channel.type + "` (https://discord.com/developers/docs/resources/channel) aka " + channel.toString(); } await interaction.followUp({ ephemeral: false, content }) } }
export async function CreateThreadForTask(task: Task, client: ToDoClient): Promise<string> {
let channel: TextChannel = await GetTaskboardTextChannel(client); let taskThread = await channel.threads.create({ name: `${task.id} | ${task.description} | <@${task.assignee}>`, type: ChannelType.PublicThread, }) taskThread.send(`${task.description}, for <@${task.assignee}> | ${task.id}`); return taskThread.id; } export async function CloseThreadForTask(task: Task, client: ToDoClient): Promise<AnyThreadChannel<boolean>> { let channel: TextChannel = await GetTaskboardTextChannel(client); let thread = await channel.threads.fetch(task.threadId); await thread.send("Task remove. Closing thread."); return await thread.setArchived(); } async function GetTaskboardTextChannel(client: ToDoClient): Promise<TextChannel> { return await client.channels.fetch(client.taskboardID) as TextChannel; } export async function SendMessageToThread(task: Task, client: ToDoClient): Promise<string> { // TODO return "" }
src/commands/taskboard.ts
savipauk-ToDoBot-a21f22e
[ { "filename": "src/commands/todo.ts", "retrieved_chunk": " if (client.taskboardID != null) {\n let threadId = await CreateThreadForTask(task, client);\n SetThreadId(task.id, threadId);\n }\n let content = `Set task \"${taskDesc}\" (ID ${task.id}) for ${user}`;\n await interaction.followUp({\n ephemeral: false,\n content\n })\n }", "score": 0.8920907974243164 }, { "filename": "src/commands/remove.ts", "retrieved_chunk": " let newTaskList = TasksToString();\n let content = \"Task doesn't exist\";\n if (task != null) {\n content = `Task \"${task.description}\" removed, ${interaction.user}\\n\\n${newTaskList}`;\n if (client.taskboardID != null) {\n await CloseThreadForTask(task, client);\n }\n }\n await interaction.followUp({\n ephemeral: false,", "score": 0.8688467741012573 }, { "filename": "src/ready.ts", "retrieved_chunk": " /*\n TODO:\n Creates a ToDoBot channel category and a Taskboard text channel in it. Discuss. \n let server: Guild = await client.guilds.fetch(process.env.guildId);\n let category: CategoryChannel = await server.channels.create({\n name: \"ToDoBot\",\n type: ChannelType.GuildCategory\n });\n await server.channels.create({\n name: \"Taskboard\",", "score": 0.8374136686325073 }, { "filename": "src/commands/assign.ts", "retrieved_chunk": " content = `Task \"${task.description}\" assigned to ${user}`;\n }\n await interaction.followUp({\n ephemeral: false,\n content\n })\n }\n}", "score": 0.8317302465438843 }, { "filename": "src/commands/todo.ts", "retrieved_chunk": "import { ApplicationCommandOptionType, ApplicationCommandType, CommandInteraction, TextChannel } from 'discord.js';\nimport { AddTask, SetThreadId } from '../tasks';\nimport { Command } from '../types/Command';\nimport { ToDoClient } from '../types/ToDoClient';\nimport { CreateThreadForTask } from './taskboard';\nexport const Todo: Command = {\n name: \"todo\",\n description: \"Create a new task\",\n type: ApplicationCommandType.ChatInput,\n options: [", "score": 0.8256314396858215 } ]
typescript
export async function CreateThreadForTask(task: Task, client: ToDoClient): Promise<string> {
import path from "node:path"; import type { AstroConfig, AstroIntegration } from "astro"; import dedent from "dedent"; import fg from "fast-glob"; import fs from "fs-extra"; import slash from "slash"; import { logger } from "../astro/logger/node"; import { removeLeadingForwardSlashWindows } from "../astro/internal-helpers/path"; import { defaultI18nConfig } from "../shared/configs"; import type { UserI18nConfig, I18nConfig } from "../shared/configs"; // injectRoute doesn't generate build pages https://github.com/withastro/astro/issues/5096 // workaround: copy pages folder when command === "build" /** * The i18n integration for Astro * * See the full [astro-i18n-aut](https://github.com/jlarmstrongiv/astro-i18n-aut#readme) documentation */ export function i18n(userI18nConfig: UserI18nConfig): AstroIntegration { const i18nConfig: I18nConfig = Object.assign( defaultI18nConfig, userI18nConfig ); const { defaultLocale, locales, exclude, include, redirectDefaultLocale } = i18nConfig; ensureValidLocales(locales, defaultLocale); let pagesPathTmp: Record<string, string> = {}; async function removePagesPathTmp(): Promise<void> { await Promise.all( Object.values(pagesPathTmp).map((pagePathTmp) => fs.remove(pagePathTmp)) ); } return { name: "astro-i18n-integration", hooks: { "astro:config:setup": async ({ config, command, injectRoute }) => { await ensureValidConfigs(config, i18nConfig); const configSrcDirPathname = path.normalize( removeLeadingForwardSlashWindows(config.srcDir.pathname) ); let included: string[] = ensureGlobsHaveConfigSrcDirPathname( typeof include === "string" ? [include] : include, configSrcDirPathname ); let excluded: string[] = ensureGlobsHaveConfigSrcDirPathname( typeof exclude === "string" ? [exclude] : exclude, configSrcDirPathname ); const pagesPath = path.join(configSrcDirPathname, "pages"); const pagesPathTmpRoot = path.join( configSrcDirPathname, // tmp filename from https://github.com/withastro/astro/blob/e6bff651ff80466b3e862e637d2a6a3334d8cfda/packages/astro/src/core/routing/manifest/create.ts#L279 "astro_tmp_pages" ); for (const locale of Object.keys(locales)) { pagesPathTmp[locale] = `${pagesPathTmpRoot}_${locale}`; } await removePagesPathTmp(); if (command === "build") { await Promise.all( Object.keys(locales) .filter((locale) => { if (redirectDefaultLocale === false) { return locale !== defaultLocale; } else { return true; } }) .map((locale) => fs.copy(pagesPath, pagesPathTmp[locale])) ); } const entries = fg.stream(included, { ignore: excluded, onlyFiles: true, }); // typing https://stackoverflow.com/a/68358341 let entry: string; // @ts-expect-error for await (entry of entries) { const parsedPath = path.parse(entry); const relativePath = path.relative(pagesPath, parsedPath.dir); const extname = parsedPath.ext.slice(1).toLowerCase(); // warn on files that cannot be translated with specific and actionable warnings // astro pages file types https://docs.astro.build/en/core-concepts/astro-pages/#supported-page-files // any file that is not included as an astro page file types, will be automatically warned about by astro if (extname !== "astro") { warnIsInvalidPage( extname, path.join(relativePath, parsedPath.base), configSrcDirPathname ); continue; } for (const locale of Object.keys(locales)) { // ignore defaultLocale if redirectDefaultLocale is false if (redirectDefaultLocale === false && locale === defaultLocale) { continue; } const entryPoint = command === "build" ? path.join(pagesPathTmp[locale], relativePath, parsedPath.base) : path.join(pagesPath, relativePath, parsedPath.base); const pattern = slash( path.join( config.base, locale, relativePath, parsedPath.name.endsWith("index") ? "" : parsedPath.name, config.build.format === "directory" ? "/" : "" ) ); injectRoute({ entryPoint, pattern, }); } } }, "astro:build:done": async () => { await removePagesPathTmp(); }, "astro:server:done": async () => { await removePagesPathTmp(); }, }, }; } function ensureValidLocales( locales: Record<string, string>, defaultLocale: string ) { if (!Object.keys(locales).includes(defaultLocale)) { const errorMessage = `locales ${JSON.stringify( locales )} does not include "${defaultLocale}"`; logger.error("astro-i18n-aut", errorMessage); throw new Error(errorMessage); } } async function ensureValidConfigs(config: AstroConfig, i18nConfig: I18nConfig) { if (config.trailingSlash === "ignore" && config.output === "static") {
logger.warn( "astro-i18n-aut", `avoid setting config.trailingSlash = "ignore" when config.output = "static"` );
logger.warn( "astro-i18n-aut", `config.trailingSlash = "always" && config.build.format = "directory"` ); logger.warn( "astro-i18n-aut", `config.trailingSlash = "never" && config.build.format = "file"` ); logger.warn( "astro-i18n-aut", `setting config.trailingSlash = "${config.trailingSlash}"` ); config.trailingSlash = config.build.format === "directory" ? "always" : "never"; } if (i18nConfig.redirectDefaultLocale) { const configSrcDirPathname = path.normalize( removeLeadingForwardSlashWindows(config.srcDir.pathname) ); // all possible locations of middleware const defaultMiddlewarePath = path.join( configSrcDirPathname, "middleware/index.ts" ); const middlewarePaths = [ path.join(configSrcDirPathname, "middleware.js"), path.join(configSrcDirPathname, "middleware.ts"), path.join(configSrcDirPathname, "middleware/index.js"), defaultMiddlewarePath, ]; // check if middleware exists const pathsExist = await Promise.all( middlewarePaths.map((middlewarePath) => fs.exists(middlewarePath)) ); const pathExists = pathsExist.includes(true); // warn and create middleware if it does not exist if (pathExists === false) { logger.warn("astro-i18n-aut", `cannot find any Astro middleware files:`); middlewarePaths.forEach((middlewarePath) => { logger.warn("astro-i18n-aut", `- ${middlewarePath}`); }); logger.warn( "astro-i18n-aut", `creating ${defaultMiddlewarePath} with defaultLocale = "en"` ); await fs.outputFile( defaultMiddlewarePath, dedent(` import { sequence } from "astro/middleware"; import { i18nMiddleware } from "astro-i18n-aut"; const i18n = i18nMiddleware({ defaultLocale: "en" }); export const onRequest = sequence(i18n); `) ); } } } function ensureGlobsHaveConfigSrcDirPathname( filePaths: string[], configSrcDirPathname: string ) { return filePaths.map((filePath) => { filePath = path.normalize(removeLeadingForwardSlashWindows(filePath)); if (filePath.includes(configSrcDirPathname)) { filePath = path.relative(configSrcDirPathname, filePath); } // fast-glob prefers unix paths https://www.npmjs.com/package/fast-glob#how-to-write-patterns-on-windows filePath = path.posix.join( fg.convertPathToPattern(configSrcDirPathname), slash(filePath) ); return filePath; }); } let hasWarnedIsInvalidPage = false; function warnIsInvalidPage( extname: string, filePath: string, configSrcDirPathname: string ): boolean { // astro pages file types https://docs.astro.build/en/core-concepts/astro-pages/#supported-page-files if (["js", "ts", "md", "mdx", "html"].includes(extname)) { if (hasWarnedIsInvalidPage === false) { logger.warn( "astro-i18n-aut", `exclude or remove non-astro files from "${configSrcDirPathname}pages", as they cannot be translated` ); hasWarnedIsInvalidPage = true; } logger.warn( "astro-i18n-aut", path.join(configSrcDirPathname, "pages", filePath) ); return true; } return false; }
src/integration/integration.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/edge-runtime/middleware.ts", "retrieved_chunk": "import type { ValidRedirectStatus } from \"astro\";\nimport { defineMiddleware } from \"astro/middleware\";\nimport { defaultI18nMiddlewareConfig } from \"../shared/configs\";\nimport type {\n UserI18nMiddlewareConfig,\n I18nMiddlewareConfig,\n} from \"../shared/configs\";\nconst redirectDefaultLocaleDisabledMiddleware = defineMiddleware((_, next) =>\n next()\n);", "score": 0.8138044476509094 }, { "filename": "src/edge-runtime/middleware.ts", "retrieved_chunk": "export function i18nMiddleware(\n userI18nMiddlewareConfig: UserI18nMiddlewareConfig\n) {\n const i18nMiddlewareConfig: I18nMiddlewareConfig = Object.assign(\n defaultI18nMiddlewareConfig,\n userI18nMiddlewareConfig\n );\n const { defaultLocale, redirectDefaultLocale } = i18nMiddlewareConfig;\n if (redirectDefaultLocale === false) {\n return redirectDefaultLocaleDisabledMiddleware;", "score": 0.8009786009788513 }, { "filename": "src/astro/logger/node.ts", "retrieved_chunk": " debug(\"cli\", '--verbose flag enabled! Enabling: DEBUG=\"*,-babel\"');\n debug(\n \"cli\",\n 'Tip: Set the DEBUG env variable directly for more control. Example: \"DEBUG=astro:*,vite:* astro build\".'\n );\n}", "score": 0.7989752292633057 }, { "filename": "src/shared/configs.ts", "retrieved_chunk": "import type { ValidRedirectStatus } from \"astro\";\nexport interface UserI18nConfig {\n /**\n * glob pattern(s) to include\n * @defaultValue [\"pages\\/\\*\\*\\/\\*\"]\n */\n include?: string | string[];\n /**\n * glob pattern(s) to exclude\n * @defaultValue [\"pages\\/api\\/\\*\\*\\/\\*\"]", "score": 0.7853068113327026 }, { "filename": "src/astro/logger/node.ts", "retrieved_chunk": "}\n// This is gross, but necessary since we are depending on globals.\n(globalThis as any)._astroGlobalDebug = debug;\n// A default logger for when too lazy to pass LogOptions around.\nexport const logger = {\n info: info.bind(null, nodeLogOptions),\n warn: warn.bind(null, nodeLogOptions),\n error: error.bind(null, nodeLogOptions),\n};\nexport function enableVerboseLogging() {", "score": 0.7838829755783081 } ]
typescript
logger.warn( "astro-i18n-aut", `avoid setting config.trailingSlash = "ignore" when config.output = "static"` );
import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { Developer, DeveloperDocument } from './schemas/developer.schema'; import { IDeveloperService } from '../core/interfaces/IDeveloperService'; @Injectable() export class DeveloperService implements IDeveloperService { constructor( @InjectModel(Developer.name) private developerModel: Model<DeveloperDocument>, @Inject(CACHE_MANAGER) private readonly cacheManager: Cache, ) {} async create(dto: DeveloperDTO): Promise<DeveloperDocument> { try { const developer = await this.developerModel.create(dto); if (!developer) throw new NotFoundException(`failed to create developer!`); return developer; } catch (error) { throw new NotFoundException(`failed to create developer for duplicate email!`); } } async readBatch(): Promise<DeveloperDocument[]> { return await this.developerModel.find().exec(); } async read(id: string): Promise<DeveloperDocument> { try { const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) { return JSON.parse(cached as unknown as string); } const developer = await this.developerModel.findById(id); if (!developer) throw new NotFoundException(`developer not found!`); await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } catch (error) { throw new NotFoundException(`developer not found!`); } } async
filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {
try { const cacheKey = `developers:${dto.level}`; const cached = await this.cacheManager.get(cacheKey); if (cached) return JSON.parse(cached as unknown as string); const developers = await this.developerModel.find({ level: dto.level }).exec(); if (developers) { await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0); } return developers; } catch (error) { throw new NotFoundException(`failed to filter developer!`); } } async update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument> { const { _id } = await this.read(id); const developer = await this.developerModel.findByIdAndUpdate(_id, dto, { new: true, }); if (!developer) throw new NotFoundException(`failed to update developer!`); const cacheKey = `developer:${id}`; await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } async delete(id: string): Promise<HttpException> { const developer = await this.developerModel.findByIdAndDelete(id); if (!developer) throw new NotFoundException(`failed to delete developer!`); const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) await this.cacheManager.del(cacheKey); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } }
src/developer/developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " throw new NotFoundException(`developer not found!`);\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {\n const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n return developers.filter(\n (developer: { level: string }) => developer.level === dto.level,\n );\n }\n async update(id: string, dto: PartialDeveloperDTO): Promise<object> {", "score": 0.9570481777191162 }, { "filename": "src/core/interfaces/IDeveloperService.ts", "retrieved_chunk": " * get all the developers by level\n */\n filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[] | object[]>;\n /**\n * update a single record\n */\n update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument | object>;\n /**\n * delete a single record\n */", "score": 0.9144660234451294 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " return this.developerService.filterByLevel(dto);\n }\n @Get()\n getDevelopers(): object {\n return this.developerService.readBatch();\n }\n @Get(':id')\n getDeveloper(@Param('id') id: string): object {\n return this.developerService.read(id);\n }", "score": 0.9035961031913757 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n const index = developers.findIndex(\n (developer: { _id: { toString: () => string } }) => developer._id.toString() === id,\n );\n if (index < 0) throw new NotFoundException(`failed to update developer!`);\n const updated = Object.assign(developers[index], dto);\n developers[index] = updated;\n await this.cacheManager.del(this.key);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);", "score": 0.8958123326301575 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " async read(id: string): Promise<object> {\n const cached = await this.cacheManager.get(this.key);\n if (cached) {\n const developers = JSON.parse(cached as unknown as string);\n const developer = developers.find(\n (developer: { _id: string }) => developer._id === id,\n );\n if (!developer) throw new NotFoundException(`developer not found!`);\n return developer;\n }", "score": 0.8824928998947144 } ]
typescript
filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { randomUUID } from 'crypto'; import { IDeveloperService, IDeveloper } from 'src/core/interfaces/IDeveloperService'; @Injectable() export class InMemoryDeveloperService implements IDeveloperService { private key = 'developers'; constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {} async create(dto: DeveloperDTO): Promise<object> { const data: IDeveloper = { _id: this.uuid(), name: dto.name, email: dto.email, level: dto.level, }; const cached = await this.cacheManager.get(this.key); if (cached) { const jsonArray = JSON.parse(cached as unknown as string); jsonArray.push(data); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(jsonArray), 0); return data; } const developers = []; developers.push(data); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return data; } async readBatch(): Promise<object[]> { const cached = await this.cacheManager.get(this.key); return JSON.parse(cached as unknown as string); } async read(id: string): Promise<object> { const cached = await this.cacheManager.get(this.key); if (cached) { const developers = JSON.parse(cached as unknown as string); const developer = developers.find( (developer: { _id: string }) => developer._id === id, ); if (!developer) throw new NotFoundException(`developer not found!`); return developer; } throw new NotFoundException(`developer not found!`); } async filterByLevel
(dto: PartialDeveloperDTO): Promise<object[]> {
const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); return developers.filter( (developer: { level: string }) => developer.level === dto.level, ); } async update(id: string, dto: PartialDeveloperDTO): Promise<object> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex( (developer: { _id: { toString: () => string } }) => developer._id.toString() === id, ); if (index < 0) throw new NotFoundException(`failed to update developer!`); const updated = Object.assign(developers[index], dto); developers[index] = updated; await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return updated; } async delete(id: string): Promise<HttpException> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex((developer) => developer._id === id); if (index === -1) throw new NotFoundException(`failed to delete developer!`); developers.splice(index, 1); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } private uuid(): string { return randomUUID(); } }
src/developer/in-memory-developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const developer = await this.developerModel.findById(id);\n if (!developer) throw new NotFoundException(`developer not found!`);\n await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0);\n return developer;\n } catch (error) {\n throw new NotFoundException(`developer not found!`);\n }\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {\n try {", "score": 0.9591481685638428 }, { "filename": "src/core/interfaces/IDeveloperService.ts", "retrieved_chunk": " * get all the developers by level\n */\n filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[] | object[]>;\n /**\n * update a single record\n */\n update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument | object>;\n /**\n * delete a single record\n */", "score": 0.9210008978843689 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const cacheKey = `developers:${dto.level}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) return JSON.parse(cached as unknown as string);\n const developers = await this.developerModel.find({ level: dto.level }).exec();\n if (developers) {\n await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0);\n }\n return developers;\n } catch (error) {\n throw new NotFoundException(`failed to filter developer!`);", "score": 0.905495285987854 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " return this.developerService.filterByLevel(dto);\n }\n @Get()\n getDevelopers(): object {\n return this.developerService.readBatch();\n }\n @Get(':id')\n getDeveloper(@Param('id') id: string): object {\n return this.developerService.read(id);\n }", "score": 0.9029146432876587 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " : DeveloperService,\n )\n private readonly developerService: DeveloperService,\n ) {}\n @Post()\n postDeveloper(@Body() dto: DeveloperDTO): object {\n return this.developerService.create(dto);\n }\n @Post('filter')\n filterDevelopersByLevel(@Body() dto: PartialDeveloperDTO): object {", "score": 0.885204553604126 } ]
typescript
(dto: PartialDeveloperDTO): Promise<object[]> {
import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { Developer, DeveloperDocument } from './schemas/developer.schema'; import { IDeveloperService } from '../core/interfaces/IDeveloperService'; @Injectable() export class DeveloperService implements IDeveloperService { constructor( @InjectModel(Developer.name) private developerModel: Model<DeveloperDocument>, @Inject(CACHE_MANAGER) private readonly cacheManager: Cache, ) {} async create(dto: DeveloperDTO): Promise<DeveloperDocument> { try { const developer = await this.developerModel.create(dto); if (!developer) throw new NotFoundException(`failed to create developer!`); return developer; } catch (error) { throw new NotFoundException(`failed to create developer for duplicate email!`); } } async readBatch(): Promise<DeveloperDocument[]> { return await this.developerModel.find().exec(); } async read(id: string): Promise<DeveloperDocument> { try { const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) { return JSON.parse(cached as unknown as string); } const developer = await this.developerModel.findById(id); if (!developer) throw new NotFoundException(`developer not found!`); await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } catch (error) { throw new NotFoundException(`developer not found!`); } } async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> { try {
const cacheKey = `developers:${dto.level}`;
const cached = await this.cacheManager.get(cacheKey); if (cached) return JSON.parse(cached as unknown as string); const developers = await this.developerModel.find({ level: dto.level }).exec(); if (developers) { await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0); } return developers; } catch (error) { throw new NotFoundException(`failed to filter developer!`); } } async update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument> { const { _id } = await this.read(id); const developer = await this.developerModel.findByIdAndUpdate(_id, dto, { new: true, }); if (!developer) throw new NotFoundException(`failed to update developer!`); const cacheKey = `developer:${id}`; await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } async delete(id: string): Promise<HttpException> { const developer = await this.developerModel.findByIdAndDelete(id); if (!developer) throw new NotFoundException(`failed to delete developer!`); const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) await this.cacheManager.del(cacheKey); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } }
src/developer/developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " throw new NotFoundException(`developer not found!`);\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {\n const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n return developers.filter(\n (developer: { level: string }) => developer.level === dto.level,\n );\n }\n async update(id: string, dto: PartialDeveloperDTO): Promise<object> {", "score": 0.9472185373306274 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n const index = developers.findIndex(\n (developer: { _id: { toString: () => string } }) => developer._id.toString() === id,\n );\n if (index < 0) throw new NotFoundException(`failed to update developer!`);\n const updated = Object.assign(developers[index], dto);\n developers[index] = updated;\n await this.cacheManager.del(this.key);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);", "score": 0.8878757953643799 }, { "filename": "src/core/interfaces/IDeveloperService.ts", "retrieved_chunk": " * get all the developers by level\n */\n filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[] | object[]>;\n /**\n * update a single record\n */\n update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument | object>;\n /**\n * delete a single record\n */", "score": 0.8852930665016174 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " return this.developerService.filterByLevel(dto);\n }\n @Get()\n getDevelopers(): object {\n return this.developerService.readBatch();\n }\n @Get(':id')\n getDeveloper(@Param('id') id: string): object {\n return this.developerService.read(id);\n }", "score": 0.883374810218811 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " : DeveloperService,\n )\n private readonly developerService: DeveloperService,\n ) {}\n @Post()\n postDeveloper(@Body() dto: DeveloperDTO): object {\n return this.developerService.create(dto);\n }\n @Post('filter')\n filterDevelopersByLevel(@Body() dto: PartialDeveloperDTO): object {", "score": 0.8752191066741943 } ]
typescript
const cacheKey = `developers:${dto.level}`;
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { randomUUID } from 'crypto'; import { IDeveloperService, IDeveloper } from 'src/core/interfaces/IDeveloperService'; @Injectable() export class InMemoryDeveloperService implements IDeveloperService { private key = 'developers'; constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {} async create(dto: DeveloperDTO): Promise<object> { const data: IDeveloper = { _id: this.uuid(), name: dto.name, email: dto.email, level: dto.level, }; const cached = await this.cacheManager.get(this.key); if (cached) { const jsonArray = JSON.parse(cached as unknown as string); jsonArray.push(data); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(jsonArray), 0); return data; } const developers = []; developers.push(data); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return data; } async readBatch(): Promise<object[]> { const cached = await this.cacheManager.get(this.key); return JSON.parse(cached as unknown as string); } async read(id: string): Promise<object> { const cached = await this.cacheManager.get(this.key); if (cached) { const developers = JSON.parse(cached as unknown as string); const developer = developers.find( (developer: { _id: string }) => developer._id === id, ); if (!developer) throw new NotFoundException(`developer not found!`); return developer; } throw new NotFoundException(`developer not found!`); } async
filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {
const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); return developers.filter( (developer: { level: string }) => developer.level === dto.level, ); } async update(id: string, dto: PartialDeveloperDTO): Promise<object> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex( (developer: { _id: { toString: () => string } }) => developer._id.toString() === id, ); if (index < 0) throw new NotFoundException(`failed to update developer!`); const updated = Object.assign(developers[index], dto); developers[index] = updated; await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return updated; } async delete(id: string): Promise<HttpException> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex((developer) => developer._id === id); if (index === -1) throw new NotFoundException(`failed to delete developer!`); developers.splice(index, 1); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } private uuid(): string { return randomUUID(); } }
src/developer/in-memory-developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const developer = await this.developerModel.findById(id);\n if (!developer) throw new NotFoundException(`developer not found!`);\n await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0);\n return developer;\n } catch (error) {\n throw new NotFoundException(`developer not found!`);\n }\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {\n try {", "score": 0.9615985751152039 }, { "filename": "src/core/interfaces/IDeveloperService.ts", "retrieved_chunk": " * get all the developers by level\n */\n filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[] | object[]>;\n /**\n * update a single record\n */\n update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument | object>;\n /**\n * delete a single record\n */", "score": 0.9192712306976318 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const cacheKey = `developers:${dto.level}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) return JSON.parse(cached as unknown as string);\n const developers = await this.developerModel.find({ level: dto.level }).exec();\n if (developers) {\n await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0);\n }\n return developers;\n } catch (error) {\n throw new NotFoundException(`failed to filter developer!`);", "score": 0.9068834781646729 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " return this.developerService.filterByLevel(dto);\n }\n @Get()\n getDevelopers(): object {\n return this.developerService.readBatch();\n }\n @Get(':id')\n getDeveloper(@Param('id') id: string): object {\n return this.developerService.read(id);\n }", "score": 0.901935338973999 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " : DeveloperService,\n )\n private readonly developerService: DeveloperService,\n ) {}\n @Post()\n postDeveloper(@Body() dto: DeveloperDTO): object {\n return this.developerService.create(dto);\n }\n @Post('filter')\n filterDevelopersByLevel(@Body() dto: PartialDeveloperDTO): object {", "score": 0.881657600402832 } ]
typescript
filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { randomUUID } from 'crypto'; import { IDeveloperService, IDeveloper } from 'src/core/interfaces/IDeveloperService'; @Injectable() export class InMemoryDeveloperService implements IDeveloperService { private key = 'developers'; constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {} async create(dto: DeveloperDTO): Promise<object> { const data: IDeveloper = { _id: this.uuid(), name: dto.name, email: dto.email, level: dto.level, }; const cached = await this.cacheManager.get(this.key); if (cached) { const jsonArray = JSON.parse(cached as unknown as string); jsonArray.push(data); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(jsonArray), 0); return data; } const developers = []; developers.push(data); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return data; } async readBatch(): Promise<object[]> { const cached = await this.cacheManager.get(this.key); return JSON.parse(cached as unknown as string); } async read(id: string): Promise<object> { const cached = await this.cacheManager.get(this.key); if (cached) { const developers = JSON.parse(cached as unknown as string); const developer = developers.find( (developer: { _id: string }) => developer._id === id, ); if (!developer) throw new NotFoundException(`developer not found!`); return developer; } throw new NotFoundException(`developer not found!`); }
async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {
const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); return developers.filter( (developer: { level: string }) => developer.level === dto.level, ); } async update(id: string, dto: PartialDeveloperDTO): Promise<object> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex( (developer: { _id: { toString: () => string } }) => developer._id.toString() === id, ); if (index < 0) throw new NotFoundException(`failed to update developer!`); const updated = Object.assign(developers[index], dto); developers[index] = updated; await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return updated; } async delete(id: string): Promise<HttpException> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex((developer) => developer._id === id); if (index === -1) throw new NotFoundException(`failed to delete developer!`); developers.splice(index, 1); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } private uuid(): string { return randomUUID(); } }
src/developer/in-memory-developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const developer = await this.developerModel.findById(id);\n if (!developer) throw new NotFoundException(`developer not found!`);\n await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0);\n return developer;\n } catch (error) {\n throw new NotFoundException(`developer not found!`);\n }\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {\n try {", "score": 0.9686604738235474 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const cacheKey = `developers:${dto.level}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) return JSON.parse(cached as unknown as string);\n const developers = await this.developerModel.find({ level: dto.level }).exec();\n if (developers) {\n await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0);\n }\n return developers;\n } catch (error) {\n throw new NotFoundException(`failed to filter developer!`);", "score": 0.926166832447052 }, { "filename": "src/core/interfaces/IDeveloperService.ts", "retrieved_chunk": " * get all the developers by level\n */\n filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[] | object[]>;\n /**\n * update a single record\n */\n update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument | object>;\n /**\n * delete a single record\n */", "score": 0.9103637933731079 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " return this.developerService.filterByLevel(dto);\n }\n @Get()\n getDevelopers(): object {\n return this.developerService.readBatch();\n }\n @Get(':id')\n getDeveloper(@Param('id') id: string): object {\n return this.developerService.read(id);\n }", "score": 0.8962534666061401 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " : DeveloperService,\n )\n private readonly developerService: DeveloperService,\n ) {}\n @Post()\n postDeveloper(@Body() dto: DeveloperDTO): object {\n return this.developerService.create(dto);\n }\n @Post('filter')\n filterDevelopersByLevel(@Body() dto: PartialDeveloperDTO): object {", "score": 0.8726511001586914 } ]
typescript
async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {
import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { Developer, DeveloperDocument } from './schemas/developer.schema'; import { IDeveloperService } from '../core/interfaces/IDeveloperService'; @Injectable() export class DeveloperService implements IDeveloperService { constructor( @InjectModel(Developer.name) private developerModel: Model<DeveloperDocument>, @Inject(CACHE_MANAGER) private readonly cacheManager: Cache, ) {} async create(dto: DeveloperDTO): Promise<DeveloperDocument> { try { const developer = await this.developerModel.create(dto); if (!developer) throw new NotFoundException(`failed to create developer!`); return developer; } catch (error) { throw new NotFoundException(`failed to create developer for duplicate email!`); } } async readBatch(): Promise<DeveloperDocument[]> { return await this.developerModel.find().exec(); } async read(id: string): Promise<DeveloperDocument> { try { const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) { return JSON.parse(cached as unknown as string); } const developer = await this.developerModel.findById(id); if (!developer) throw new NotFoundException(`developer not found!`); await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } catch (error) { throw new NotFoundException(`developer not found!`); } }
async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {
try { const cacheKey = `developers:${dto.level}`; const cached = await this.cacheManager.get(cacheKey); if (cached) return JSON.parse(cached as unknown as string); const developers = await this.developerModel.find({ level: dto.level }).exec(); if (developers) { await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0); } return developers; } catch (error) { throw new NotFoundException(`failed to filter developer!`); } } async update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument> { const { _id } = await this.read(id); const developer = await this.developerModel.findByIdAndUpdate(_id, dto, { new: true, }); if (!developer) throw new NotFoundException(`failed to update developer!`); const cacheKey = `developer:${id}`; await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } async delete(id: string): Promise<HttpException> { const developer = await this.developerModel.findByIdAndDelete(id); if (!developer) throw new NotFoundException(`failed to delete developer!`); const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) await this.cacheManager.del(cacheKey); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } }
src/developer/developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " throw new NotFoundException(`developer not found!`);\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {\n const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n return developers.filter(\n (developer: { level: string }) => developer.level === dto.level,\n );\n }\n async update(id: string, dto: PartialDeveloperDTO): Promise<object> {", "score": 0.9581365585327148 }, { "filename": "src/core/interfaces/IDeveloperService.ts", "retrieved_chunk": " * get all the developers by level\n */\n filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[] | object[]>;\n /**\n * update a single record\n */\n update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument | object>;\n /**\n * delete a single record\n */", "score": 0.9150381088256836 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " return this.developerService.filterByLevel(dto);\n }\n @Get()\n getDevelopers(): object {\n return this.developerService.readBatch();\n }\n @Get(':id')\n getDeveloper(@Param('id') id: string): object {\n return this.developerService.read(id);\n }", "score": 0.9033264517784119 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n const index = developers.findIndex(\n (developer: { _id: { toString: () => string } }) => developer._id.toString() === id,\n );\n if (index < 0) throw new NotFoundException(`failed to update developer!`);\n const updated = Object.assign(developers[index], dto);\n developers[index] = updated;\n await this.cacheManager.del(this.key);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);", "score": 0.8938421607017517 }, { "filename": "src/developer/developer.controller.ts", "retrieved_chunk": " : DeveloperService,\n )\n private readonly developerService: DeveloperService,\n ) {}\n @Post()\n postDeveloper(@Body() dto: DeveloperDTO): object {\n return this.developerService.create(dto);\n }\n @Post('filter')\n filterDevelopersByLevel(@Body() dto: PartialDeveloperDTO): object {", "score": 0.8828577399253845 } ]
typescript
async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {
import { chunkAtEnd, isNumber, zeroPad } from "./utils"; import { numberUnits, tenUnits, thousandUnits } from "./constant"; export function formatNumber(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { const unit = thousandUnits[index] ?? ""; if (!Number(item)) { return acc; } return `${Number(item)}${unit} ${acc}`; }, "") .trim(); } export function formatNumberAll(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { if (!Number(item)) { return acc; } let numberUnit = ""; const zeroItem = zeroPad(item, 4); for (let i = 0; i < 4; i++) { const number = Number(zeroItem[i]); if (number) { const unit = tenUnits[3 - i]; numberUnit += `${ unit &&
number === 1 ? "" : numberUnits[number] }${unit}`;
} } const thousandUnit = thousandUnits[index] ?? ""; return `${numberUnit}${numberUnit ? thousandUnit : ""} ${acc}`; }, "") .trim(); }
src/formatNumber.ts
hyukson-hangul-util-505feaa
[ { "filename": "src/utils.ts", "retrieved_chunk": " const _key = typeof key === \"string\" ? splitByKey(key) : key;\n if (!_key.length) return undefined;\n return _key?.reduce((acc, v) => acc?.[v], object);\n}\nexport function zeroPad(\n string: number | string = \"\",\n pow: number = 0,\n pad: string = \"0\"\n) {\n let result = String(string);", "score": 0.8192123174667358 }, { "filename": "src/formatDate.ts", "retrieved_chunk": " s: second,\n ss: zeroPad(second, 2, \"0\"),\n }[match] || match\n );\n }\n return (\n formatStyle\n .replace(DATE_REGEXER, matcher)\n // \"년년\" 방지 -> \"년\"\n .replace(/(년|월|일|시|분|초{1})(년|월|일|시|분|초{1})+/g, \"$1\")", "score": 0.7879254221916199 }, { "filename": "src/formatDate.ts", "retrieved_chunk": "import { zeroPad } from \"./utils\";\nimport { WEEK_DAY } from \"./constant\";\nconst DATE_REGEXER = /Y{2,4}|M{1,2}|D{1,2}|d{1,2}|H{1,2}|m{1,2}|s{1,2}/g;\n/**\n * @example\n * YY - 22, YYYY - 2022\n * M: 2, MM: 02,\n * D: 2, DD: 02,\n * d: 3, dd: '화',\n * H: 2, HH: 02,", "score": 0.7872133851051331 }, { "filename": "src/combine.ts", "retrieved_chunk": " combineLoop(item.join(\"\").split(\"\"))\n )\n );\n }\n }\n result.push(combineLoop(_temp));\n return result.join(\"\");\n}\nconst REVERSE_JUNG_COMPLETE = reverseByObject(JUNG_COMPLETE_HANGUL);\nconst REVERSE_JONG_COMPLETE = reverseByObject(JONG_COMPLETE_HANGUL);", "score": 0.7841168642044067 }, { "filename": "src/constant.ts", "retrieved_chunk": "// use formatNumber function\nexport const numberUnits = [\"\", \"일\", \"이\", \"삼\", \"사\", \"오\", \"육\", \"칠\", \"팔\", \"구\"];\nexport const tenUnits = [\"\", \"십\", \"백\", \"천\"];\nexport const thousandUnits = [\"\", \"만\", \"억\", \"조\", \"경\", \"해\"];\n// use formatDate function\nexport const WEEK_DAY = [\"일\", \"월\", \"화\", \"수\", \"목\", \"금\", \"토\"];\n// use josa function\nexport const JOSA_LIST: Record<string, string> = {\n 이: \"이/가\",\n 가: \"이/가\",", "score": 0.7688418626785278 } ]
typescript
number === 1 ? "" : numberUnits[number] }${unit}`;
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" }
${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
} get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " this.lineNumber = error.lineNumber;\n portal.appendChild(this.#container);\n const markdown = editor.value;\n const [line = \"\", ...prevLines] = markdown\n .split(\"\\n\")\n .slice(0, this.lineNumber)\n .reverse();\n const startCol = (error.errorRange?.[0] ?? 1) - 1;\n const length = error.errorRange?.[1] ?? line.length - startCol;\n const startIndex = prevLines.reduce(", "score": 0.7899606823921204 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.7797936201095581 }, { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": " handleRuleFailures: true,\n customRules: markdownlintGitHub,\n })\n .content?.map((error) => ({\n ...error,\n justification: error.ruleNames\n .map((name) => ruleJustifications[name])\n .join(\" \"),\n })) ?? [];\nexport const ruleJustifications: Partial<Record<string, string>> = {", "score": 0.7750773429870605 }, { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": "import markdownlint from \"markdownlint\";\nimport markdownlintGitHub from \"@github/markdownlint-github\";\nexport interface LintError extends markdownlint.LintError {\n justification?: string;\n}\nexport const lintMarkdown = (markdown: string): LintError[] =>\n markdownlint\n .sync({\n strings: {\n content: markdown,", "score": 0.7657952904701233 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " offset: number\n ): [node: Node, offsetIntoNode: number] | undefined {\n let prevChars = 0;\n for (const line of lines) {\n for (const node of line) {\n const length = node.textContent?.length ?? 0;\n if (offset <= prevChars + length) return [node, offset - prevChars];\n prevChars += length;\n }\n prevChars++; // For the newline", "score": 0.7653128504753113 } ]
typescript
${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number;
#_annotations: readonly LintErrorAnnotation[] = [];
set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.858736515045166 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " );\n this.#element = target;\n this.#range = document.createRange();\n }\n getClientRects(range: NumberRange): Rect[] {\n const lineNodes = Array.from(\n this.#element.querySelectorAll(\".CodeMirror-line\")\n );\n const lines = lineNodes.map((line) =>\n CodeMirrorRangeRectCalculator.#getAllTextNodes(line)", "score": 0.8179210424423218 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " return this.#elements.some((el) =>\n // scale slightly so we don't show two tooltips at touching horizontal edges\n new Rect(el.getBoundingClientRect()).scaleY(0.99).contains(point)\n );\n }\n containsIndex(index: number) {\n return this.#indexRange.contains(index, \"inclusive\");\n }\n recalculatePosition() {\n const editorRect = new Rect(this.#editor.getBoundingClientRect());", "score": 0.8155703544616699 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " : this.#element.value;\n }\n}\nexport class CodeMirrorRangeRectCalculator implements RangeRectCalculator {\n readonly #element: HTMLElement;\n readonly #range: Range;\n constructor(target: HTMLElement) {\n if (!target.classList.contains(\"CodeMirror-code\"))\n throw new Error(\n \"CodeMirrorRangeRectCalculator only works with CodeMirror code editors.\"", "score": 0.8153856992721558 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " readonly #editor: LintedMarkdownEditor;\n #elements: readonly HTMLElement[] = [];\n readonly #indexRange: NumberRange;\n constructor(\n readonly error: LintError,\n editor: LintedMarkdownEditor,\n portal: HTMLElement\n ) {\n super();\n this.#editor = editor;", "score": 0.81488436460495 } ]
typescript
#_annotations: readonly LintErrorAnnotation[] = [];
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip
(new Vector(event.clientX, event.clientY));
#onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " if (force || !this.#tooltip.matches(\":hover\"))\n this.#tooltip.setAttribute(\"hidden\", \"true\");\n }, 10);\n }\n #onGlobalKeydown(event: KeyboardEvent) {\n if (event.key === \"Escape\" && !event.defaultPrevented) this.hide(true);\n }\n static #createTooltipElement() {\n const element = document.createElement(\"div\");\n element.setAttribute(\"aria-live\", \"polite\");", "score": 0.8441537618637085 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " return this.#elements.some((el) =>\n // scale slightly so we don't show two tooltips at touching horizontal edges\n new Rect(el.getBoundingClientRect()).scaleY(0.99).contains(point)\n );\n }\n containsIndex(index: number) {\n return this.#indexRange.contains(index, \"inclusive\");\n }\n recalculatePosition() {\n const editorRect = new Rect(this.#editor.getBoundingClientRect());", "score": 0.838111400604248 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n getTooltipPosition() {\n const domRect = this.#elements.at(-1)?.getBoundingClientRect();\n if (domRect)\n return new Rect(domRect)\n .asVector(\"bottom-left\")\n .plus(new Vector(0, 2)) // add some breathing room\n .plus(getWindowScrollVector());\n }\n containsPoint(point: Vector) {", "score": 0.8194707036018372 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 0.8192710876464844 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const availableWidth = document.body.clientWidth - 2 * MARGIN;\n const rightOverflow = Math.max(x + WIDTH - (availableWidth + MARGIN), 0);\n this.#tooltip.style.left = `${Math.max(x - rightOverflow, MARGIN)}px`;\n this.#tooltip.style.maxWidth = `${availableWidth}px`;\n }\n this.#tooltip.removeAttribute(\"hidden\");\n }\n hide(force = false) {\n // Don't hide if the mouse enters the tooltip (allowing users to copy text)\n setTimeout(() => {", "score": 0.8174366354942322 } ]
typescript
(new Vector(event.clientX, event.clientY));
import { chunkAtEnd, isNumber, zeroPad } from "./utils"; import { numberUnits, tenUnits, thousandUnits } from "./constant"; export function formatNumber(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { const unit = thousandUnits[index] ?? ""; if (!Number(item)) { return acc; } return `${Number(item)}${unit} ${acc}`; }, "") .trim(); } export function formatNumberAll(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { if (!Number(item)) { return acc; } let numberUnit = ""; const zeroItem = zeroPad(item, 4); for (let i = 0; i < 4; i++) { const number = Number(zeroItem[i]); if (number) { const unit = tenUnits[3 - i]; numberUnit += `${ unit && number === 1 ? ""
: numberUnits[number] }${unit}`;
} } const thousandUnit = thousandUnits[index] ?? ""; return `${numberUnit}${numberUnit ? thousandUnit : ""} ${acc}`; }, "") .trim(); }
src/formatNumber.ts
hyukson-hangul-util-505feaa
[ { "filename": "src/utils.ts", "retrieved_chunk": " const _key = typeof key === \"string\" ? splitByKey(key) : key;\n if (!_key.length) return undefined;\n return _key?.reduce((acc, v) => acc?.[v], object);\n}\nexport function zeroPad(\n string: number | string = \"\",\n pow: number = 0,\n pad: string = \"0\"\n) {\n let result = String(string);", "score": 0.8200820684432983 }, { "filename": "src/formatDate.ts", "retrieved_chunk": " s: second,\n ss: zeroPad(second, 2, \"0\"),\n }[match] || match\n );\n }\n return (\n formatStyle\n .replace(DATE_REGEXER, matcher)\n // \"년년\" 방지 -> \"년\"\n .replace(/(년|월|일|시|분|초{1})(년|월|일|시|분|초{1})+/g, \"$1\")", "score": 0.7898228764533997 }, { "filename": "src/formatDate.ts", "retrieved_chunk": "import { zeroPad } from \"./utils\";\nimport { WEEK_DAY } from \"./constant\";\nconst DATE_REGEXER = /Y{2,4}|M{1,2}|D{1,2}|d{1,2}|H{1,2}|m{1,2}|s{1,2}/g;\n/**\n * @example\n * YY - 22, YYYY - 2022\n * M: 2, MM: 02,\n * D: 2, DD: 02,\n * d: 3, dd: '화',\n * H: 2, HH: 02,", "score": 0.788017749786377 }, { "filename": "src/combine.ts", "retrieved_chunk": " combineLoop(item.join(\"\").split(\"\"))\n )\n );\n }\n }\n result.push(combineLoop(_temp));\n return result.join(\"\");\n}\nconst REVERSE_JUNG_COMPLETE = reverseByObject(JUNG_COMPLETE_HANGUL);\nconst REVERSE_JONG_COMPLETE = reverseByObject(JONG_COMPLETE_HANGUL);", "score": 0.7855863571166992 }, { "filename": "src/constant.ts", "retrieved_chunk": "// use formatNumber function\nexport const numberUnits = [\"\", \"일\", \"이\", \"삼\", \"사\", \"오\", \"육\", \"칠\", \"팔\", \"구\"];\nexport const tenUnits = [\"\", \"십\", \"백\", \"천\"];\nexport const thousandUnits = [\"\", \"만\", \"억\", \"조\", \"경\", \"해\"];\n// use formatDate function\nexport const WEEK_DAY = [\"일\", \"월\", \"화\", \"수\", \"목\", \"금\", \"토\"];\n// use josa function\nexport const JOSA_LIST: Record<string, string> = {\n 이: \"이/가\",\n 가: \"이/가\",", "score": 0.7705221772193909 } ]
typescript
: numberUnits[number] }${unit}`;
import { chunkAtEnd, isNumber, zeroPad } from "./utils"; import { numberUnits, tenUnits, thousandUnits } from "./constant"; export function formatNumber(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { const unit = thousandUnits[index] ?? ""; if (!Number(item)) { return acc; } return `${Number(item)}${unit} ${acc}`; }, "") .trim(); } export function formatNumberAll(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { if (!Number(item)) { return acc; } let numberUnit = ""; const zeroItem = zeroPad(item, 4); for (let i = 0; i < 4; i++) { const number = Number(zeroItem[i]); if (number) { const unit = tenUnits[3 - i]; numberUnit += `${ unit && number === 1 ? "" : numberUnits[number] }${unit}`; } }
const thousandUnit = thousandUnits[index] ?? "";
return `${numberUnit}${numberUnit ? thousandUnit : ""} ${acc}`; }, "") .trim(); }
src/formatNumber.ts
hyukson-hangul-util-505feaa
[ { "filename": "src/getLocal.ts", "retrieved_chunk": " en: 0,\n number: 0,\n special: 0,\n etc: 0,\n };\n const result: string[] = [];\n for (let index = 0; index < word.length; index++) {\n const language = getLocal(word[index]);\n if (isPercent) {\n countObject[language]++;", "score": 0.7999599575996399 }, { "filename": "src/utils.ts", "retrieved_chunk": " const _key = typeof key === \"string\" ? splitByKey(key) : key;\n if (!_key.length) return undefined;\n return _key?.reduce((acc, v) => acc?.[v], object);\n}\nexport function zeroPad(\n string: number | string = \"\",\n pow: number = 0,\n pad: string = \"0\"\n) {\n let result = String(string);", "score": 0.7943897247314453 }, { "filename": "src/getLocal.ts", "retrieved_chunk": " return \"number\";\n }\n return \"etc\";\n}\nexport function getLocalByGroups(\n word: string = \"\",\n isPercent: boolean = false,\n) {\n const countObject = {\n ko: 0,", "score": 0.7828052043914795 }, { "filename": "src/formatDate.ts", "retrieved_chunk": " s: second,\n ss: zeroPad(second, 2, \"0\"),\n }[match] || match\n );\n }\n return (\n formatStyle\n .replace(DATE_REGEXER, matcher)\n // \"년년\" 방지 -> \"년\"\n .replace(/(년|월|일|시|분|초{1})(년|월|일|시|분|초{1})+/g, \"$1\")", "score": 0.7815496325492859 }, { "filename": "src/constant.ts", "retrieved_chunk": "// use formatNumber function\nexport const numberUnits = [\"\", \"일\", \"이\", \"삼\", \"사\", \"오\", \"육\", \"칠\", \"팔\", \"구\"];\nexport const tenUnits = [\"\", \"십\", \"백\", \"천\"];\nexport const thousandUnits = [\"\", \"만\", \"억\", \"조\", \"경\", \"해\"];\n// use formatDate function\nexport const WEEK_DAY = [\"일\", \"월\", \"화\", \"수\", \"목\", \"금\", \"토\"];\n// use josa function\nexport const JOSA_LIST: Record<string, string> = {\n 이: \"이/가\",\n 가: \"이/가\",", "score": 0.7793821096420288 } ]
typescript
const thousandUnit = thousandUnits[index] ?? "";
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea;
this.addEventListener(textarea, "input", this.onUpdate);
} get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " readonly #editor: LintedMarkdownEditor;\n #elements: readonly HTMLElement[] = [];\n readonly #indexRange: NumberRange;\n constructor(\n readonly error: LintError,\n editor: LintedMarkdownEditor,\n portal: HTMLElement\n ) {\n super();\n this.#editor = editor;", "score": 0.8828392028808594 }, { "filename": "src/content-script.ts", "retrieved_chunk": "import {\n LintedMarkdownCodeMirrorEditor,\n LintedMarkdownTextareaEditor,\n} from \"./components/linted-markdown-editor\";\nimport {observeSelector} from \"./utilities/dom/observe-selector\";\nconst rootPortal = document.createElement(\"div\");\nrootPortal.style.zIndex = \"999\";\nrootPortal.style.position = \"absolute\";\nrootPortal.style.top = \"0\";\nrootPortal.style.left = \"0\";", "score": 0.8786957263946533 }, { "filename": "src/content-script.ts", "retrieved_chunk": "document.body.appendChild(rootPortal);\nobserveSelector(\n \"textarea.js-paste-markdown, textarea.CommentBox-input, textarea[aria-label='Markdown value']\",\n (editor) => {\n if (!(editor instanceof HTMLTextAreaElement)) return () => {};\n const lintedEditor = new LintedMarkdownTextareaEditor(editor, rootPortal);\n return () => lintedEditor.disconnect();\n }\n);\nobserveSelector(", "score": 0.874015212059021 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " constructor(target: HTMLTextAreaElement) {\n this.#element = target;\n // The mirror div will replicate the textarea's style\n const div = document.createElement(\"div\");\n this.#div = div;\n document.body.appendChild(div);\n this.#refreshStyles();\n this.#mutationObserver = new MutationObserver(() => this.#refreshStyles());\n this.#mutationObserver.observe(this.#element, {\n attributeFilter: [\"style\"],", "score": 0.8646923303604126 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.8643410205841064 } ]
typescript
this.addEventListener(textarea, "input", this.onUpdate);
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */
getClientRects({start, end}: NumberRange): Rect[];
disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector(); const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset = new Vector( this.#element.scrollLeft, this.#element.scrollTop ); const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect).translate(netTranslate) ); } disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.#statusContainer.remove();\n }\n /**\n * Return a list of rects for the given range. If the range extends over multiple lines,\n * multiple rects will be returned.\n */\n getRangeRects(characterIndexes: NumberRange) {\n return this.#rangeRectCalculator.getClientRects(characterIndexes);\n }\n getBoundingClientRect() {", "score": 0.8486218452453613 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": "import {\n CodeMirrorRangeRectCalculator,\n RangeRectCalculator,\n TextareaRangeRectCalculator,\n} from \"../utilities/dom/range-rect-calculator\";\nimport {formatList} from \"../utilities/format\";\nimport {lintMarkdown} from \"../utilities/lint-markdown\";\nimport {LintErrorTooltip} from \"./lint-error-tooltip\";\nimport {LintErrorAnnotation} from \"./lint-error-annotation\";\nimport {Vector} from \"../utilities/geometry/vector\";", "score": 0.8202177286148071 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 0.7927151918411255 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " return this.#editor.getBoundingClientRect();\n }\n getLineHeight() {\n const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10);\n return Number.isNaN(parsed) ? undefined : parsed;\n }\n abstract get value(): string;\n abstract get caretPosition(): number;\n #_annotations: readonly LintErrorAnnotation[] = [];\n set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) {", "score": 0.7831231355667114 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": "import {NumberRange} from \"./number-range\";\nimport {Vector} from \"./vector\";\ntype RectParams = Pick<DOMRect, \"x\" | \"y\" | \"height\" | \"width\">;\n/** Represents a rectangle, typically the bounding box for an HTML element. */\nexport class Rect implements DOMRect {\n readonly height: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n constructor({x, y, height, width}: RectParams) {", "score": 0.7813938856124878 } ]
typescript
getClientRects({start, end}: NumberRange): Rect[];
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (
error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) );
} #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.8592674732208252 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 0.8534044027328491 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " readonly #editor: LintedMarkdownEditor;\n #elements: readonly HTMLElement[] = [];\n readonly #indexRange: NumberRange;\n constructor(\n readonly error: LintError,\n editor: LintedMarkdownEditor,\n portal: HTMLElement\n ) {\n super();\n this.#editor = editor;", "score": 0.8463828563690186 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": "//@ts-check\n\"use strict\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {LintError} from \"../utilities/lint-markdown\";\nimport {Component} from \"./component\";\nconst WIDTH = 350;\nconst MARGIN = 8;\nexport class LintErrorTooltip extends Component {\n #tooltip = LintErrorTooltip.#createTooltipElement();\n constructor(portal: HTMLElement) {", "score": 0.8417293429374695 }, { "filename": "src/content-script.ts", "retrieved_chunk": "document.body.appendChild(rootPortal);\nobserveSelector(\n \"textarea.js-paste-markdown, textarea.CommentBox-input, textarea[aria-label='Markdown value']\",\n (editor) => {\n if (!(editor instanceof HTMLTextAreaElement)) return () => {};\n const lintedEditor = new LintedMarkdownTextareaEditor(editor, rootPortal);\n return () => lintedEditor.disconnect();\n }\n);\nobserveSelector(", "score": 0.8329682946205139 } ]
typescript
error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) );
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return;
const errors = lintMarkdown(this.value);
this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 0.8343837857246399 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " (t, l) => t + l.length + 1 /* +1 for newline char */,\n startCol\n );\n const endIndex = startIndex + length;\n this.#indexRange = new NumberRange(startIndex, endIndex);\n this.recalculatePosition();\n }\n disconnect() {\n super.disconnect();\n this.#container.remove();", "score": 0.8190168142318726 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.814769983291626 }, { "filename": "src/content-script.ts", "retrieved_chunk": " \"file-attachment.js-upload-markdown-image .CodeMirror-code[contenteditable]\",\n (editor) => {\n const lintedEditor = new LintedMarkdownCodeMirrorEditor(editor, rootPortal);\n return () => lintedEditor.disconnect();\n }\n);", "score": 0.8127474188804626 }, { "filename": "src/components/component.ts", "retrieved_chunk": " for (const {target, name, capture, handler} of this.#eventListeners)\n target.removeEventListener(name, handler, capture);\n this.#eventListeners = [];\n }\n}", "score": 0.8098804950714111 } ]
typescript
const errors = lintMarkdown(this.value);
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */ getClientRects({start, end}: NumberRange): Rect[]; disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector(); const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset =
new Vector( this.#element.scrollLeft, this.#element.scrollTop );
const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect).translate(netTranslate) ); } disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " }\n get value() {\n return this.#textarea.value;\n }\n get caretPosition() {\n return this.#textarea.selectionEnd !== this.#textarea.selectionStart\n ? -1\n : this.#textarea.selectionStart;\n }\n}", "score": 0.8519198894500732 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n getTooltipPosition() {\n const domRect = this.#elements.at(-1)?.getBoundingClientRect();\n if (domRect)\n return new Rect(domRect)\n .asVector(\"bottom-left\")\n .plus(new Vector(0, 2)) // add some breathing room\n .plus(getWindowScrollVector());\n }\n containsPoint(point: Vector) {", "score": 0.8448655009269714 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 0.8398767709732056 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " return this.#elements.some((el) =>\n // scale slightly so we don't show two tooltips at touching horizontal edges\n new Rect(el.getBoundingClientRect()).scaleY(0.99).contains(point)\n );\n }\n containsIndex(index: number) {\n return this.#indexRange.contains(index, \"inclusive\");\n }\n recalculatePosition() {\n const editorRect = new Rect(this.#editor.getBoundingClientRect());", "score": 0.8367189764976501 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.addEventListener(element, \"mousemove\", this.#onMouseMove);\n this.addEventListener(element, \"mouseleave\", this.#onMouseLeave);\n // capture ancestor scroll events for nested scroll containers\n this.addEventListener(document, \"scroll\", this.#onReposition, true);\n // selectionchange can't be bound to the textarea so we have to use the document\n this.addEventListener(document, \"selectionchange\", this.#onSelectionChange);\n // annotations are document-relative so we need to observe document resize as well\n this.addEventListener(window, \"resize\", this.#onReposition);\n // this does mean it will run twice when the resize causes a resize of the textarea,\n // but we also need the resize observer for the textarea because it's user resizable", "score": 0.8259523510932922 } ]
typescript
new Vector( this.#element.scrollLeft, this.#element.scrollTop );
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList(
annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
} get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": " handleRuleFailures: true,\n customRules: markdownlintGitHub,\n })\n .content?.map((error) => ({\n ...error,\n justification: error.ruleNames\n .map((name) => ruleJustifications[name])\n .join(\" \"),\n })) ?? [];\nexport const ruleJustifications: Partial<Record<string, string>> = {", "score": 0.7745473384857178 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " this.lineNumber = error.lineNumber;\n portal.appendChild(this.#container);\n const markdown = editor.value;\n const [line = \"\", ...prevLines] = markdown\n .split(\"\\n\")\n .slice(0, this.lineNumber)\n .reverse();\n const startCol = (error.errorRange?.[0] ?? 1) - 1;\n const length = error.errorRange?.[1] ?? line.length - startCol;\n const startIndex = prevLines.reduce(", "score": 0.7730093002319336 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.7664475440979004 }, { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": " },\n config: markdownlintGitHub.init({\n default: false,\n \"no-reversed-links\": true,\n \"no-empty-links\": true,\n // While enforcing a certain unordered list style can be somewhat helpful for making the Markdown source\n // easier to read with a screen reader, this rule is ultimately too opinionated and noisy to be worth it,\n // especially because it conflicts with the editor's bulleted list toolbar button.\n \"ul-style\": false,\n }),", "score": 0.7639603018760681 }, { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": "import markdownlint from \"markdownlint\";\nimport markdownlintGitHub from \"@github/markdownlint-github\";\nexport interface LintError extends markdownlint.LintError {\n justification?: string;\n}\nexport const lintMarkdown = (markdown: string): LintError[] =>\n markdownlint\n .sync({\n strings: {\n content: markdown,", "score": 0.7623465061187744 } ]
typescript
annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${
formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
} get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " this.lineNumber = error.lineNumber;\n portal.appendChild(this.#container);\n const markdown = editor.value;\n const [line = \"\", ...prevLines] = markdown\n .split(\"\\n\")\n .slice(0, this.lineNumber)\n .reverse();\n const startCol = (error.errorRange?.[0] ?? 1) - 1;\n const length = error.errorRange?.[1] ?? line.length - startCol;\n const startIndex = prevLines.reduce(", "score": 0.784612774848938 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.7766332626342773 }, { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": " handleRuleFailures: true,\n customRules: markdownlintGitHub,\n })\n .content?.map((error) => ({\n ...error,\n justification: error.ruleNames\n .map((name) => ruleJustifications[name])\n .join(\" \"),\n })) ?? [];\nexport const ruleJustifications: Partial<Record<string, string>> = {", "score": 0.7749278545379639 }, { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": "import markdownlint from \"markdownlint\";\nimport markdownlintGitHub from \"@github/markdownlint-github\";\nexport interface LintError extends markdownlint.LintError {\n justification?: string;\n}\nexport const lintMarkdown = (markdown: string): LintError[] =>\n markdownlint\n .sync({\n strings: {\n content: markdown,", "score": 0.7660946249961853 }, { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": " \"ol-prefix\":\n \"When reading Markdown source code, out-of-order lists make it more difficult for non-sighted users to understand how long a list is.\",\n};", "score": 0.7642617225646973 } ]
typescript
formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position
= annotations[0]?.getTooltipPosition();
const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.829071044921875 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " : \"\",\n error.ruleNames?.length\n ? LintErrorTooltip.#createNameElement(\n error.ruleNames?.slice(0, 2).join(\": \")\n )\n : \"\",\n ]);\n this.#tooltip.replaceChildren(prefix, ...errorNodes.flat());\n this.#tooltip.style.top = `${y}px`;\n {", "score": 0.8152480125427246 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": "//@ts-check\n\"use strict\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {LintError} from \"../utilities/lint-markdown\";\nimport {Component} from \"./component\";\nconst WIDTH = 350;\nconst MARGIN = 8;\nexport class LintErrorTooltip extends Component {\n #tooltip = LintErrorTooltip.#createTooltipElement();\n constructor(portal: HTMLElement) {", "score": 0.8113844394683838 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 0.8034144639968872 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const prefix = LintErrorTooltip.#createPrefixElement(errors.length);\n // even though typed as required string, sometimes these properties are missing\n const errorNodes = errors.map((error, i) => [\n i !== 0 ? LintErrorTooltip.#createSeparatorElement() : \"\",\n LintErrorTooltip.#createDescriptionElement(error.ruleDescription),\n error.errorDetail\n ? LintErrorTooltip.#createDetailsElement(error.errorDetail)\n : \"\",\n error.justification\n ? LintErrorTooltip.#createJustificationElement(error.justification)", "score": 0.8016716241836548 } ]
typescript
= annotations[0]?.getTooltipPosition();
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error);
if (position) this.#tooltip.show(errors, position);
else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.837757408618927 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 0.8316846489906311 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " : \"\",\n error.ruleNames?.length\n ? LintErrorTooltip.#createNameElement(\n error.ruleNames?.slice(0, 2).join(\": \")\n )\n : \"\",\n ]);\n this.#tooltip.replaceChildren(prefix, ...errorNodes.flat());\n this.#tooltip.style.top = `${y}px`;\n {", "score": 0.8258370757102966 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": "//@ts-check\n\"use strict\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {LintError} from \"../utilities/lint-markdown\";\nimport {Component} from \"./component\";\nconst WIDTH = 350;\nconst MARGIN = 8;\nexport class LintErrorTooltip extends Component {\n #tooltip = LintErrorTooltip.#createTooltipElement();\n constructor(portal: HTMLElement) {", "score": 0.8215043544769287 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const prefix = LintErrorTooltip.#createPrefixElement(errors.length);\n // even though typed as required string, sometimes these properties are missing\n const errorNodes = errors.map((error, i) => [\n i !== 0 ? LintErrorTooltip.#createSeparatorElement() : \"\",\n LintErrorTooltip.#createDescriptionElement(error.ruleDescription),\n error.errorDetail\n ? LintErrorTooltip.#createDetailsElement(error.errorDetail)\n : \"\",\n error.justification\n ? LintErrorTooltip.#createJustificationElement(error.justification)", "score": 0.8140046000480652 } ]
typescript
if (position) this.#tooltip.show(errors, position);
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */ getClientRects(
{start, end}: NumberRange): Rect[];
disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector(); const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset = new Vector( this.#element.scrollLeft, this.#element.scrollTop ); const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect).translate(netTranslate) ); } disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.#statusContainer.remove();\n }\n /**\n * Return a list of rects for the given range. If the range extends over multiple lines,\n * multiple rects will be returned.\n */\n getRangeRects(characterIndexes: NumberRange) {\n return this.#rangeRectCalculator.getClientRects(characterIndexes);\n }\n getBoundingClientRect() {", "score": 0.8407335877418518 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": "import {\n CodeMirrorRangeRectCalculator,\n RangeRectCalculator,\n TextareaRangeRectCalculator,\n} from \"../utilities/dom/range-rect-calculator\";\nimport {formatList} from \"../utilities/format\";\nimport {lintMarkdown} from \"../utilities/lint-markdown\";\nimport {LintErrorTooltip} from \"./lint-error-tooltip\";\nimport {LintErrorAnnotation} from \"./lint-error-annotation\";\nimport {Vector} from \"../utilities/geometry/vector\";", "score": 0.817146897315979 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 0.7897863984107971 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": "export class NumberRange {\n readonly start: number;\n readonly end: number;\n constructor(start: number, end: number) {\n this.start = Math.min(start, end);\n this.end = Math.max(start, end);\n }\n contains(\n value: number,\n mode:", "score": 0.7840216159820557 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": "import {NumberRange} from \"./number-range\";\nimport {Vector} from \"./vector\";\ntype RectParams = Pick<DOMRect, \"x\" | \"y\" | \"height\" | \"width\">;\n/** Represents a rectangle, typically the bounding box for an HTML element. */\nexport class Rect implements DOMRect {\n readonly height: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n constructor({x, y, height, width}: RectParams) {", "score": 0.7831166982650757 } ]
typescript
{start, end}: NumberRange): Rect[];
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText =
await getOpenAiSuggestions( concatenatePatchesToString(files), );
const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 0.8135511875152588 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.8120384812355042 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": " messages: [\n { role: 'system', content: promptsConfig[Prompt.SYSTEM_PROMPT] },\n { role: 'user', content: patch },\n ],\n }),\n });\n if (!response.ok) throw new Error('Failed to post data.');\n const responseJson = (await response.json()) as any;\n const openAiSuggestion =\n responseJson.choices.shift()?.message?.content || '';", "score": 0.8030828833580017 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 0.79462069272995 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": "import { getInput } from '@actions/core';\nimport fetch from 'node-fetch';\nimport errorsConfig, { ErrorMessage } from '../../config/errorsConfig';\nimport promptsConfig, { Prompt } from '../../config/promptsConfig';\nconst OPENAI_MODEL = getInput('model') || 'gpt-3.5-turbo';\nconst getOpenAiSuggestions = async (patch: string): Promise<any> => {\n if (!patch) {\n throw new Error(\n errorsConfig[ErrorMessage.MISSING_PATCH_FOR_OPENAI_SUGGESTION],\n );", "score": 0.7879627346992493 } ]
typescript
await getOpenAiSuggestions( concatenatePatchesToString(files), );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) {
const firstChangedLine = extractFirstChangedLineFromPatch(file.patch);
const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.8320527076721191 }, { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 0.8148729205131531 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 0.8052980899810791 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": " messages: [\n { role: 'system', content: promptsConfig[Prompt.SYSTEM_PROMPT] },\n { role: 'user', content: patch },\n ],\n }),\n });\n if (!response.ok) throw new Error('Failed to post data.');\n const responseJson = (await response.json()) as any;\n const openAiSuggestion =\n responseJson.choices.shift()?.message?.content || '';", "score": 0.7989904284477234 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 0.7965775728225708 } ]
typescript
const firstChangedLine = extractFirstChangedLineFromPatch(file.patch);
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private
async createReviewComments(files: FilenameWithPatch[]) {
const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 0.8248425126075745 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.8067394495010376 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.799758791923523 }, { "filename": "src/index.ts", "retrieved_chunk": "import CommentOnPullRequestService from './services/commentOnPullRequestService';\nconst commentOnPrService = new CommentOnPullRequestService();\ncommentOnPrService.addCommentToPr();", "score": 0.7788645029067993 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 0.77490234375 } ]
typescript
async createReviewComments(files: FilenameWithPatch[]) {
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition();
const errors = annotations.map(({error}) => error);
if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.8347735404968262 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " : \"\",\n error.ruleNames?.length\n ? LintErrorTooltip.#createNameElement(\n error.ruleNames?.slice(0, 2).join(\": \")\n )\n : \"\",\n ]);\n this.#tooltip.replaceChildren(prefix, ...errorNodes.flat());\n this.#tooltip.style.top = `${y}px`;\n {", "score": 0.820481538772583 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const prefix = LintErrorTooltip.#createPrefixElement(errors.length);\n // even though typed as required string, sometimes these properties are missing\n const errorNodes = errors.map((error, i) => [\n i !== 0 ? LintErrorTooltip.#createSeparatorElement() : \"\",\n LintErrorTooltip.#createDescriptionElement(error.ruleDescription),\n error.errorDetail\n ? LintErrorTooltip.#createDetailsElement(error.errorDetail)\n : \"\",\n error.justification\n ? LintErrorTooltip.#createJustificationElement(error.justification)", "score": 0.8159043192863464 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": "//@ts-check\n\"use strict\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {LintError} from \"../utilities/lint-markdown\";\nimport {Component} from \"./component\";\nconst WIDTH = 350;\nconst MARGIN = 8;\nexport class LintErrorTooltip extends Component {\n #tooltip = LintErrorTooltip.#createTooltipElement();\n constructor(portal: HTMLElement) {", "score": 0.8144791722297668 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 0.8085378408432007 } ]
typescript
const errors = annotations.map(({error}) => error);
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), );
const suggestionsByFile = parseOpenAISuggestions(suggestionsListText);
const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 0.8173235058784485 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.8068739175796509 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": " messages: [\n { role: 'system', content: promptsConfig[Prompt.SYSTEM_PROMPT] },\n { role: 'user', content: patch },\n ],\n }),\n });\n if (!response.ok) throw new Error('Failed to post data.');\n const responseJson = (await response.json()) as any;\n const openAiSuggestion =\n responseJson.choices.shift()?.message?.content || '';", "score": 0.8002779483795166 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 0.7967511415481567 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.7928566932678223 } ]
typescript
const suggestionsByFile = parseOpenAISuggestions(suggestionsListText);
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (
suggestion) => suggestion.filename === file.filename, );
if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 0.8587181568145752 }, { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 0.8211950659751892 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "export default extractFirstChangedLineFromPatch;", "score": 0.8162847757339478 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 0.8156190514564514 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.8049819469451904 } ]
typescript
suggestion) => suggestion.filename === file.filename, );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error(
errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], );
} const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/index.ts", "retrieved_chunk": "import CommentOnPullRequestService from './services/commentOnPullRequestService';\nconst commentOnPrService = new CommentOnPullRequestService();\ncommentOnPrService.addCommentToPr();", "score": 0.8218222856521606 }, { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 0.7842315435409546 }, { "filename": "src/config/errorsConfig.ts", "retrieved_chunk": "enum ErrorMessage {\n MISSING_GITHUB_TOKEN,\n MISSING_OPENAI_TOKEN,\n NO_PULLREQUEST_IN_CONTEXT,\n MISSING_PATCH_FOR_OPENAI_SUGGESTION,\n NO_CHANGED_FILES_IN_PULL_REQUEST,\n}\nconst errorsConfig: { [key in ErrorMessage]: string } = {\n [ErrorMessage.MISSING_GITHUB_TOKEN]:\n 'A GitHub token must be provided to use the Octokit API.',", "score": 0.7813645601272583 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.7643356323242188 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": "import { getInput } from '@actions/core';\nimport fetch from 'node-fetch';\nimport errorsConfig, { ErrorMessage } from '../../config/errorsConfig';\nimport promptsConfig, { Prompt } from '../../config/promptsConfig';\nconst OPENAI_MODEL = getInput('model') || 'gpt-3.5-turbo';\nconst getOpenAiSuggestions = async (patch: string): Promise<any> => {\n if (!patch) {\n throw new Error(\n errorsConfig[ErrorMessage.MISSING_PATCH_FOR_OPENAI_SUGGESTION],\n );", "score": 0.7603211402893066 } ]
typescript
errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], );
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */ getClientRects({start, end}: NumberRange): Rect[]; disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition
= new Rect(this.#div.getBoundingClientRect()).asVector();
const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset = new Vector( this.#element.scrollLeft, this.#element.scrollTop ); const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect).translate(netTranslate) ); } disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.#statusContainer.remove();\n }\n /**\n * Return a list of rects for the given range. If the range extends over multiple lines,\n * multiple rects will be returned.\n */\n getRangeRects(characterIndexes: NumberRange) {\n return this.#rangeRectCalculator.getClientRects(characterIndexes);\n }\n getBoundingClientRect() {", "score": 0.8451471924781799 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": "import {\n CodeMirrorRangeRectCalculator,\n RangeRectCalculator,\n TextareaRangeRectCalculator,\n} from \"../utilities/dom/range-rect-calculator\";\nimport {formatList} from \"../utilities/format\";\nimport {lintMarkdown} from \"../utilities/lint-markdown\";\nimport {LintErrorTooltip} from \"./lint-error-tooltip\";\nimport {LintErrorAnnotation} from \"./lint-error-annotation\";\nimport {Vector} from \"../utilities/geometry/vector\";", "score": 0.8254699110984802 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 0.825179398059845 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " }\n get value() {\n return this.#textarea.value;\n }\n get caretPosition() {\n return this.#textarea.selectionEnd !== this.#textarea.selectionStart\n ? -1\n : this.#textarea.selectionStart;\n }\n}", "score": 0.8174469470977783 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " }\n get caretPosition() {\n const selection = document.getSelection();\n const range = selection?.getRangeAt(0);\n if (!range?.collapsed || selection?.rangeCount !== 1) return -1;\n const referenceRange = document.createRange();\n referenceRange.selectNodeContents(this.#element);\n referenceRange.setEnd(range.startContainer, range.startOffset);\n return referenceRange.toString().length;\n }", "score": 0.8072792291641235 } ]
typescript
= new Rect(this.#div.getBoundingClientRect()).asVector();
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange =
divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, );
await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 0.8583683371543884 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": " }\n return result;\n};\nexport default divideFilesByTokenRange;", "score": 0.8138675689697266 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.7989827394485474 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": " currentArray.push(file);\n currentTokensUsed += file.tokensUsed;\n } else {\n result.push(currentArray);\n currentArray = [file];\n currentTokensUsed = file.tokensUsed;\n }\n }\n if (currentArray.length > 0) {\n result.push(currentArray);", "score": 0.7812401056289673 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "export default extractFirstChangedLineFromPatch;", "score": 0.7634243965148926 } ]
typescript
divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) {
const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), );
const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 0.8202333450317383 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.8130099177360535 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": " messages: [\n { role: 'system', content: promptsConfig[Prompt.SYSTEM_PROMPT] },\n { role: 'user', content: patch },\n ],\n }),\n });\n if (!response.ok) throw new Error('Failed to post data.');\n const responseJson = (await response.json()) as any;\n const openAiSuggestion =\n responseJson.choices.shift()?.message?.content || '';", "score": 0.8004233241081238 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 0.7934730648994446 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.7906807065010071 } ]
typescript
const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) =>
suggestion.filename === file.filename, );
if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 0.858652651309967 }, { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 0.8207470178604126 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "export default extractFirstChangedLineFromPatch;", "score": 0.8167025446891785 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 0.8164568543434143 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.804633617401123 } ]
typescript
suggestion.filename === file.filename, );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find(
(suggestion) => suggestion.filename === file.filename, );
if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.861599326133728 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 0.8386870622634888 }, { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 0.8171141147613525 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 0.8119722604751587 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "export default extractFirstChangedLineFromPatch;", "score": 0.8089588284492493 } ]
typescript
(suggestion) => suggestion.filename === file.filename, );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); }
const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, );
await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 0.8666567802429199 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": " }\n return result;\n};\nexport default divideFilesByTokenRange;", "score": 0.8205910325050354 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 0.8038829565048218 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": " currentArray.push(file);\n currentTokensUsed += file.tokensUsed;\n } else {\n result.push(currentArray);\n currentArray = [file];\n currentTokensUsed = file.tokensUsed;\n }\n }\n if (currentArray.length > 0) {\n result.push(currentArray);", "score": 0.7964105010032654 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "export default extractFirstChangedLineFromPatch;", "score": 0.7702430486679077 } ]
typescript
const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, );
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv; const options: IOptions = { requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express;
if (options.mock) {
mockServer = initServer(options); } await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options))); } catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": " await fs.promises.unlink(pbjsFilePath);\n await saveTypeScriptDefineFile(pbtsFilePath, options);\n await saveApiFile(pbtsFilePath, options);\n const jsonSchemaFilePath = await saveJSONSchemaFile(pbtsFilePath);\n const mockFilePath = await saveMockJSONFile(jsonSchemaFilePath);\n console.log(`success generate ${filePath} to ${path.resolve(options.folder, filePath)}.d.ts and ${path.resolve(options.folder, filePath)}.ts`);\n if (options.mock && mockServer) {\n console.log('begin open mock server');\n await generateMockRoute(mockFilePath, mockServer, options);\n }", "score": 0.8585989475250244 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " * @param {Express} mockServer express server 对象\n * @param {IOptions} options 用户自定义配置\n */\nexport async function generateMockRoute(mockFilePath: string, mockServer: Express, options: IOptions) {\n const { baseUrl } = options;\n const mockFile = await fs.promises.readFile(mockFilePath, { encoding: 'utf-8' });\n const json = JSON.parse(mockFile);\n for (const apiName in json) {\n if (Object.hasOwnProperty.call(json, apiName)) {\n const requestMethod = getRequestMethod(apiName);", "score": 0.8373507857322693 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { Express } from 'express';\nimport fs from 'fs';\nimport path from 'path';\nimport { IOptions } from '../interfaces/IOptions';\nimport { getPbjsFile } from './getPbjsFile';\nimport { getPbtsFile } from './getPbtsFile';\nimport { generateMockRoute } from './mockServer';\nimport { saveApiFile } from './saveApiFile';\nimport { saveJSONSchemaFile } from './saveJSONSchemaFile';\nimport { saveMockJSONFile } from './saveMockJSONFile';", "score": 0.836936354637146 }, { "filename": "src/modules/getPbjsFile.ts", "retrieved_chunk": " const { folder = '' } = options;\n const fileName = filePath.replace('.proto', '.js');\n const pbjsFilePath = path.resolve(process.cwd(), folder, fileName);\n const p = path.dirname(pbjsFilePath);\n await mkdirp(p);\n return new Promise((resolve, reject) => {\n pbjs.main(['-p', options.root, '-t', 'static-module', '-w', 'commonjs', '-o', pbjsFilePath, path.resolve(process.cwd(), filePath)], err => {\n if (err) {\n reject(err);\n }", "score": 0.830924928188324 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { saveTypeScriptDefineFile } from './saveTypeScriptDefineFile';\n/**\n * 转换protobuf定义文件为ts定义文件和api请求文件\n * @param {String} filePath protobuf定义文件的路径\n * @param {Express} mockServer mockServer对象,是一个express实例化的对象\n * @param {Object} options 用户自定义配置\n */\nexport async function transferTSFile(filePath: string, mockServer: Express, options: IOptions) {\n const pbjsFilePath = await getPbjsFile(filePath, options);\n const pbtsFilePath = await getPbtsFile(pbjsFilePath, options);", "score": 0.8309170603752136 } ]
typescript
if (options.mock) {
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map(
(error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) );
} #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": "import {LintedMarkdownEditor} from \"./linted-markdown-editor\";\nimport {Rect} from \"../utilities/geometry/rect\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {getWindowScrollVector, isHighContrastMode} from \"../utilities/dom\";\nimport {NumberRange} from \"../utilities/geometry/number-range\";\nimport {Component} from \"./component\";\nimport {LintError} from \"../utilities/lint-markdown\";\nexport class LintErrorAnnotation extends Component {\n readonly lineNumber: number;\n readonly #container: HTMLElement = document.createElement(\"div\");", "score": 0.855983316898346 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 0.8500176072120667 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " readonly #editor: LintedMarkdownEditor;\n #elements: readonly HTMLElement[] = [];\n readonly #indexRange: NumberRange;\n constructor(\n readonly error: LintError,\n editor: LintedMarkdownEditor,\n portal: HTMLElement\n ) {\n super();\n this.#editor = editor;", "score": 0.8399660587310791 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": "//@ts-check\n\"use strict\";\nimport {Vector} from \"../utilities/geometry/vector\";\nimport {LintError} from \"../utilities/lint-markdown\";\nimport {Component} from \"./component\";\nconst WIDTH = 350;\nconst MARGIN = 8;\nexport class LintErrorTooltip extends Component {\n #tooltip = LintErrorTooltip.#createTooltipElement();\n constructor(portal: HTMLElement) {", "score": 0.837580680847168 }, { "filename": "src/content-script.ts", "retrieved_chunk": "document.body.appendChild(rootPortal);\nobserveSelector(\n \"textarea.js-paste-markdown, textarea.CommentBox-input, textarea[aria-label='Markdown value']\",\n (editor) => {\n if (!(editor instanceof HTMLTextAreaElement)) return () => {};\n const lintedEditor = new LintedMarkdownTextareaEditor(editor, rootPortal);\n return () => lintedEditor.disconnect();\n }\n);\nobserveSelector(", "score": 0.8337192535400391 } ]
typescript
(error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) );
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv; const options: IOptions = { requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express; if (options.mock) { mockServer = initServer(options); } await Promise.all(protoFiles.map
(filePath => transferTSFile(filePath, mockServer, options)));
} catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { saveTypeScriptDefineFile } from './saveTypeScriptDefineFile';\n/**\n * 转换protobuf定义文件为ts定义文件和api请求文件\n * @param {String} filePath protobuf定义文件的路径\n * @param {Express} mockServer mockServer对象,是一个express实例化的对象\n * @param {Object} options 用户自定义配置\n */\nexport async function transferTSFile(filePath: string, mockServer: Express, options: IOptions) {\n const pbjsFilePath = await getPbjsFile(filePath, options);\n const pbtsFilePath = await getPbtsFile(pbjsFilePath, options);", "score": 0.8785567283630371 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": " await fs.promises.unlink(pbjsFilePath);\n await saveTypeScriptDefineFile(pbtsFilePath, options);\n await saveApiFile(pbtsFilePath, options);\n const jsonSchemaFilePath = await saveJSONSchemaFile(pbtsFilePath);\n const mockFilePath = await saveMockJSONFile(jsonSchemaFilePath);\n console.log(`success generate ${filePath} to ${path.resolve(options.folder, filePath)}.d.ts and ${path.resolve(options.folder, filePath)}.ts`);\n if (options.mock && mockServer) {\n console.log('begin open mock server');\n await generateMockRoute(mockFilePath, mockServer, options);\n }", "score": 0.873015820980072 }, { "filename": "src/modules/getPbjsFile.ts", "retrieved_chunk": " const { folder = '' } = options;\n const fileName = filePath.replace('.proto', '.js');\n const pbjsFilePath = path.resolve(process.cwd(), folder, fileName);\n const p = path.dirname(pbjsFilePath);\n await mkdirp(p);\n return new Promise((resolve, reject) => {\n pbjs.main(['-p', options.root, '-t', 'static-module', '-w', 'commonjs', '-o', pbjsFilePath, path.resolve(process.cwd(), filePath)], err => {\n if (err) {\n reject(err);\n }", "score": 0.8466433882713318 }, { "filename": "src/modules/getPbtsFile.ts", "retrieved_chunk": " const pbtsFilePath = path.resolve(process.cwd(), folder, pbjsFilePath.replace('.js', '.d.ts'));\n return new Promise((resolve, reject) => {\n pbts.main(['-p', options.root, '-o', pbtsFilePath, pbjsFilePath], err => {\n if (err) {\n reject(err);\n }\n resolve(pbtsFilePath);\n });\n });\n}", "score": 0.8273037075996399 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " * @param {Express} mockServer express server 对象\n * @param {IOptions} options 用户自定义配置\n */\nexport async function generateMockRoute(mockFilePath: string, mockServer: Express, options: IOptions) {\n const { baseUrl } = options;\n const mockFile = await fs.promises.readFile(mockFilePath, { encoding: 'utf-8' });\n const json = JSON.parse(mockFile);\n for (const apiName in json) {\n if (Object.hasOwnProperty.call(json, apiName)) {\n const requestMethod = getRequestMethod(apiName);", "score": 0.8271855115890503 } ]
typescript
(filePath => transferTSFile(filePath, mockServer, options)));
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv; const options: IOptions = { requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express; if (options.mock) { mockServer = initServer(options); }
await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options)));
} catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { saveTypeScriptDefineFile } from './saveTypeScriptDefineFile';\n/**\n * 转换protobuf定义文件为ts定义文件和api请求文件\n * @param {String} filePath protobuf定义文件的路径\n * @param {Express} mockServer mockServer对象,是一个express实例化的对象\n * @param {Object} options 用户自定义配置\n */\nexport async function transferTSFile(filePath: string, mockServer: Express, options: IOptions) {\n const pbjsFilePath = await getPbjsFile(filePath, options);\n const pbtsFilePath = await getPbtsFile(pbjsFilePath, options);", "score": 0.8749561309814453 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": " await fs.promises.unlink(pbjsFilePath);\n await saveTypeScriptDefineFile(pbtsFilePath, options);\n await saveApiFile(pbtsFilePath, options);\n const jsonSchemaFilePath = await saveJSONSchemaFile(pbtsFilePath);\n const mockFilePath = await saveMockJSONFile(jsonSchemaFilePath);\n console.log(`success generate ${filePath} to ${path.resolve(options.folder, filePath)}.d.ts and ${path.resolve(options.folder, filePath)}.ts`);\n if (options.mock && mockServer) {\n console.log('begin open mock server');\n await generateMockRoute(mockFilePath, mockServer, options);\n }", "score": 0.8687795400619507 }, { "filename": "src/modules/getPbjsFile.ts", "retrieved_chunk": " const { folder = '' } = options;\n const fileName = filePath.replace('.proto', '.js');\n const pbjsFilePath = path.resolve(process.cwd(), folder, fileName);\n const p = path.dirname(pbjsFilePath);\n await mkdirp(p);\n return new Promise((resolve, reject) => {\n pbjs.main(['-p', options.root, '-t', 'static-module', '-w', 'commonjs', '-o', pbjsFilePath, path.resolve(process.cwd(), filePath)], err => {\n if (err) {\n reject(err);\n }", "score": 0.8493680953979492 }, { "filename": "src/modules/getPbtsFile.ts", "retrieved_chunk": " const pbtsFilePath = path.resolve(process.cwd(), folder, pbjsFilePath.replace('.js', '.d.ts'));\n return new Promise((resolve, reject) => {\n pbts.main(['-p', options.root, '-o', pbtsFilePath, pbjsFilePath], err => {\n if (err) {\n reject(err);\n }\n resolve(pbtsFilePath);\n });\n });\n}", "score": 0.8280082941055298 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " * @param {Express} mockServer express server 对象\n * @param {IOptions} options 用户自定义配置\n */\nexport async function generateMockRoute(mockFilePath: string, mockServer: Express, options: IOptions) {\n const { baseUrl } = options;\n const mockFile = await fs.promises.readFile(mockFilePath, { encoding: 'utf-8' });\n const json = JSON.parse(mockFile);\n for (const apiName in json) {\n if (Object.hasOwnProperty.call(json, apiName)) {\n const requestMethod = getRequestMethod(apiName);", "score": 0.826672375202179 } ]
typescript
await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options)));
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv;
const options: IOptions = {
requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express; if (options.mock) { mockServer = initServer(options); } await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options))); } catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/interfaces/IOptions.ts", "retrieved_chunk": "export interface IOptions {\n requestModule: string;\n baseUrl: string;\n folder: string;\n root: string;\n optional: boolean;\n mock: boolean;\n port: string;\n help: string;\n}", "score": 0.8536484241485596 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { Express } from 'express';\nimport fs from 'fs';\nimport path from 'path';\nimport { IOptions } from '../interfaces/IOptions';\nimport { getPbjsFile } from './getPbjsFile';\nimport { getPbtsFile } from './getPbtsFile';\nimport { generateMockRoute } from './mockServer';\nimport { saveApiFile } from './saveApiFile';\nimport { saveJSONSchemaFile } from './saveJSONSchemaFile';\nimport { saveMockJSONFile } from './saveMockJSONFile';", "score": 0.8222603797912598 }, { "filename": "src/modules/saveJSONSchemaFile.ts", "retrieved_chunk": " required: true,\n };\n const compilerOptions = {\n strictNullChecks: true,\n };\n const program = getProgramFromFiles([path.resolve(pbtsFilePath)], compilerOptions, process.cwd());\n const generator = buildGenerator(program, settings);\n const symbols = (generator?.getUserSymbols() || []).filter(symbol => /I(\\S*)Rsp$/.test(symbol));\n const schema = generator?.getSchemaForSymbols(symbols);\n const jsonSchemaFilePath = pbtsFilePath.replace('.d.ts', '.json');", "score": 0.8078566789627075 }, { "filename": "src/modules/getPbjsFile.ts", "retrieved_chunk": " const { folder = '' } = options;\n const fileName = filePath.replace('.proto', '.js');\n const pbjsFilePath = path.resolve(process.cwd(), folder, fileName);\n const p = path.dirname(pbjsFilePath);\n await mkdirp(p);\n return new Promise((resolve, reject) => {\n pbjs.main(['-p', options.root, '-t', 'static-module', '-w', 'commonjs', '-o', pbjsFilePath, path.resolve(process.cwd(), filePath)], err => {\n if (err) {\n reject(err);\n }", "score": 0.8073334097862244 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": " await fs.promises.unlink(pbjsFilePath);\n await saveTypeScriptDefineFile(pbtsFilePath, options);\n await saveApiFile(pbtsFilePath, options);\n const jsonSchemaFilePath = await saveJSONSchemaFile(pbtsFilePath);\n const mockFilePath = await saveMockJSONFile(jsonSchemaFilePath);\n console.log(`success generate ${filePath} to ${path.resolve(options.folder, filePath)}.d.ts and ${path.resolve(options.folder, filePath)}.ts`);\n if (options.mock && mockServer) {\n console.log('begin open mock server');\n await generateMockRoute(mockFilePath, mockServer, options);\n }", "score": 0.8037792444229126 } ]
typescript
const options: IOptions = {
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv; const options: IOptions = { requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express; if (options.mock) { mockServer =
initServer(options);
} await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options))); } catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": " await fs.promises.unlink(pbjsFilePath);\n await saveTypeScriptDefineFile(pbtsFilePath, options);\n await saveApiFile(pbtsFilePath, options);\n const jsonSchemaFilePath = await saveJSONSchemaFile(pbtsFilePath);\n const mockFilePath = await saveMockJSONFile(jsonSchemaFilePath);\n console.log(`success generate ${filePath} to ${path.resolve(options.folder, filePath)}.d.ts and ${path.resolve(options.folder, filePath)}.ts`);\n if (options.mock && mockServer) {\n console.log('begin open mock server');\n await generateMockRoute(mockFilePath, mockServer, options);\n }", "score": 0.8656513094902039 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " * @param {Express} mockServer express server 对象\n * @param {IOptions} options 用户自定义配置\n */\nexport async function generateMockRoute(mockFilePath: string, mockServer: Express, options: IOptions) {\n const { baseUrl } = options;\n const mockFile = await fs.promises.readFile(mockFilePath, { encoding: 'utf-8' });\n const json = JSON.parse(mockFile);\n for (const apiName in json) {\n if (Object.hasOwnProperty.call(json, apiName)) {\n const requestMethod = getRequestMethod(apiName);", "score": 0.8473992347717285 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { Express } from 'express';\nimport fs from 'fs';\nimport path from 'path';\nimport { IOptions } from '../interfaces/IOptions';\nimport { getPbjsFile } from './getPbjsFile';\nimport { getPbtsFile } from './getPbtsFile';\nimport { generateMockRoute } from './mockServer';\nimport { saveApiFile } from './saveApiFile';\nimport { saveJSONSchemaFile } from './saveJSONSchemaFile';\nimport { saveMockJSONFile } from './saveMockJSONFile';", "score": 0.8451276421546936 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { saveTypeScriptDefineFile } from './saveTypeScriptDefineFile';\n/**\n * 转换protobuf定义文件为ts定义文件和api请求文件\n * @param {String} filePath protobuf定义文件的路径\n * @param {Express} mockServer mockServer对象,是一个express实例化的对象\n * @param {Object} options 用户自定义配置\n */\nexport async function transferTSFile(filePath: string, mockServer: Express, options: IOptions) {\n const pbjsFilePath = await getPbjsFile(filePath, options);\n const pbtsFilePath = await getPbtsFile(pbjsFilePath, options);", "score": 0.8400380611419678 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " const mockServer = express();\n const { port = '3000' } = options;\n mockServer.listen(+port, () => {\n console.log(`mock server listening on port ${port}`);\n });\n return mockServer;\n}\n/**\n * 拿到mock文件,生成mock server\n * @param {String} mockFilePath mock文件的路径", "score": 0.8389818072319031 } ]
typescript
initServer(options);
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */ getClientRects({start, end}: NumberRange): Rect[]; disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector(); const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset = new Vector( this.#element.scrollLeft, this.#element.scrollTop ); const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect
).translate(netTranslate) );
} disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 0.8448877334594727 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.#statusContainer.remove();\n }\n /**\n * Return a list of rects for the given range. If the range extends over multiple lines,\n * multiple rects will be returned.\n */\n getRangeRects(characterIndexes: NumberRange) {\n return this.#rangeRectCalculator.getClientRects(characterIndexes);\n }\n getBoundingClientRect() {", "score": 0.8282284736633301 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " }\n get value() {\n return this.#textarea.value;\n }\n get caretPosition() {\n return this.#textarea.selectionEnd !== this.#textarea.selectionStart\n ? -1\n : this.#textarea.selectionStart;\n }\n}", "score": 0.8274732828140259 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " return this.#elements.some((el) =>\n // scale slightly so we don't show two tooltips at touching horizontal edges\n new Rect(el.getBoundingClientRect()).scaleY(0.99).contains(point)\n );\n }\n containsIndex(index: number) {\n return this.#indexRange.contains(index, \"inclusive\");\n }\n recalculatePosition() {\n const editorRect = new Rect(this.#editor.getBoundingClientRect());", "score": 0.8204439878463745 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n getTooltipPosition() {\n const domRect = this.#elements.at(-1)?.getBoundingClientRect();\n if (domRect)\n return new Rect(domRect)\n .asVector(\"bottom-left\")\n .plus(new Vector(0, 2)) // add some breathing room\n .plus(getWindowScrollVector());\n }\n containsPoint(point: Vector) {", "score": 0.8196238279342651 } ]
typescript
).translate(netTranslate) );
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) =>
a.containsIndex(this.caretPosition) );
} static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " return this.#elements.some((el) =>\n // scale slightly so we don't show two tooltips at touching horizontal edges\n new Rect(el.getBoundingClientRect()).scaleY(0.99).contains(point)\n );\n }\n containsIndex(index: number) {\n return this.#indexRange.contains(index, \"inclusive\");\n }\n recalculatePosition() {\n const editorRect = new Rect(this.#editor.getBoundingClientRect());", "score": 0.8338098526000977 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n getTooltipPosition() {\n const domRect = this.#elements.at(-1)?.getBoundingClientRect();\n if (domRect)\n return new Rect(domRect)\n .asVector(\"bottom-left\")\n .plus(new Vector(0, 2)) // add some breathing room\n .plus(getWindowScrollVector());\n }\n containsPoint(point: Vector) {", "score": 0.8294830918312073 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " if (force || !this.#tooltip.matches(\":hover\"))\n this.#tooltip.setAttribute(\"hidden\", \"true\");\n }, 10);\n }\n #onGlobalKeydown(event: KeyboardEvent) {\n if (event.key === \"Escape\" && !event.defaultPrevented) this.hide(true);\n }\n static #createTooltipElement() {\n const element = document.createElement(\"div\");\n element.setAttribute(\"aria-live\", \"polite\");", "score": 0.8235453367233276 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n annotation.style.pointerEvents = \"none\";\n annotation.style.top = `${rect.top}px`;\n annotation.style.left = `${rect.left}px`;\n annotation.style.width = `${rect.width}px`;\n annotation.style.height = `${rect.height}px`;\n return annotation;\n }\n}", "score": 0.8234459161758423 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const availableWidth = document.body.clientWidth - 2 * MARGIN;\n const rightOverflow = Math.max(x + WIDTH - (availableWidth + MARGIN), 0);\n this.#tooltip.style.left = `${Math.max(x - rightOverflow, MARGIN)}px`;\n this.#tooltip.style.maxWidth = `${availableWidth}px`;\n }\n this.#tooltip.removeAttribute(\"hidden\");\n }\n hide(force = false) {\n // Don't hide if the mouse enters the tooltip (allowing users to copy text)\n setTimeout(() => {", "score": 0.8070880174636841 } ]
typescript
a.containsIndex(this.caretPosition) );
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) =>
a.containsPoint(pointerLocation) );
} #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " return this.#elements.some((el) =>\n // scale slightly so we don't show two tooltips at touching horizontal edges\n new Rect(el.getBoundingClientRect()).scaleY(0.99).contains(point)\n );\n }\n containsIndex(index: number) {\n return this.#indexRange.contains(index, \"inclusive\");\n }\n recalculatePosition() {\n const editorRect = new Rect(this.#editor.getBoundingClientRect());", "score": 0.8497025966644287 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n annotation.style.pointerEvents = \"none\";\n annotation.style.top = `${rect.top}px`;\n annotation.style.left = `${rect.left}px`;\n annotation.style.width = `${rect.width}px`;\n annotation.style.height = `${rect.height}px`;\n return annotation;\n }\n}", "score": 0.8378154635429382 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n getTooltipPosition() {\n const domRect = this.#elements.at(-1)?.getBoundingClientRect();\n if (domRect)\n return new Rect(domRect)\n .asVector(\"bottom-left\")\n .plus(new Vector(0, 2)) // add some breathing room\n .plus(getWindowScrollVector());\n }\n containsPoint(point: Vector) {", "score": 0.8309960961341858 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 0.817852258682251 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " if (force || !this.#tooltip.matches(\":hover\"))\n this.#tooltip.setAttribute(\"hidden\", \"true\");\n }, 10);\n }\n #onGlobalKeydown(event: KeyboardEvent) {\n if (event.key === \"Escape\" && !event.defaultPrevented) this.hide(true);\n }\n static #createTooltipElement() {\n const element = document.createElement(\"div\");\n element.setAttribute(\"aria-live\", \"polite\");", "score": 0.8041566014289856 } ]
typescript
a.containsPoint(pointerLocation) );
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions =
calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";", "score": 0.8618499040603638 }, { "filename": "src/types/alert.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number", "score": 0.8516191244125366 }, { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))", "score": 0.8459193706512451 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 0.8453402519226074 }, { "filename": "src/types/query.ts", "retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];", "score": 0.838650107383728 } ]
typescript
calcs?.map(cal => getCalculationAlias(cal));
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) }
const Parameters: DeploymentQueryParameters = {
...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t});\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}", "score": 0.8483240604400635 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 0.8468566536903381 }, { "filename": "src/types/query.ts", "retrieved_chunk": "};\nexport type DeploymentQueryParameters = {\n\tdatasets: string[];\n\tcalculations?: string[];\n\tfilterCombination: \"AND\" | \"OR\";\n\tfilters?: string[];\n\tgroupBys?: QueryGroupBy[];\n\torderBy?: {\n\t\tvalue: string;\n\t\torder?: \"ASC\" | \"DESC\";", "score": 0.8328088521957397 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,", "score": 0.8316842913627625 }, { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,", "score": 0.8312100172042847 } ]
typescript
const Parameters: DeploymentQueryParameters = {