@studious-lms/server 1.4.3 → 1.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.vscode/settings.json +3 -0
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/models/worksheet.d.ts +1 -0
- package/dist/models/worksheet.d.ts.map +1 -1
- package/dist/models/worksheet.js +2 -2
- package/dist/models/worksheet.js.map +1 -1
- package/dist/pipelines/pdfToWorksheet.d.ts +12 -0
- package/dist/pipelines/pdfToWorksheet.d.ts.map +1 -0
- package/dist/pipelines/pdfToWorksheet.js +155 -0
- package/dist/pipelines/pdfToWorksheet.js.map +1 -0
- package/dist/routers/_app.d.ts +142 -0
- package/dist/routers/_app.d.ts.map +1 -1
- package/dist/routers/worksheet.d.ts +71 -0
- package/dist/routers/worksheet.d.ts.map +1 -1
- package/dist/routers/worksheet.js +110 -3
- package/dist/routers/worksheet.js.map +1 -1
- package/dist/services/worksheet.d.ts +21 -0
- package/dist/services/worksheet.d.ts.map +1 -1
- package/dist/services/worksheet.js +50 -2
- package/dist/services/worksheet.js.map +1 -1
- package/dist/utils/inference.d.ts +2 -1
- package/dist/utils/inference.d.ts.map +1 -1
- package/dist/utils/inference.js +53 -5
- package/dist/utils/inference.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +3 -2
- package/src/models/worksheet.ts +1 -0
- package/src/pipelines/pdfToWorksheet.ts +177 -0
- package/src/routers/worksheet.ts +143 -0
- package/src/services/worksheet.ts +61 -0
- package/src/utils/inference.ts +77 -7
- package/tests/pipelines/pdfToWorksheet.test.ts +176 -0
- package/tests/utils/inference.test.ts +37 -0
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b668f2a6-403a-56fd-86cc-2e9de852cf65")}catch(e){}}();
|
|
3
3
|
import express from 'express';
|
|
4
4
|
import { createServer } from 'http';
|
|
5
5
|
import { Server } from 'socket.io';
|
|
@@ -429,7 +429,7 @@ function getUploadSessionId(req) {
|
|
|
429
429
|
return typeof headerValue === 'string' ? headerValue : headerValue?.[0];
|
|
430
430
|
}
|
|
431
431
|
// File upload endpoint for secure file uploads (supports both POST and PUT)
|
|
432
|
-
app.post('/api/upload/:filePath',
|
|
432
|
+
app.post('/api/upload/:filePath', async (req, res) => {
|
|
433
433
|
await handleFileUpload(req, res);
|
|
434
434
|
});
|
|
435
435
|
app.put('/api/upload/:filePath', uploadLimiter, async (req, res) => {
|
|
@@ -570,4 +570,4 @@ const gracefulShutdown = (signal) => {
|
|
|
570
570
|
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
|
|
571
571
|
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
|
|
572
572
|
//# sourceMappingURL=index.js.map
|
|
573
|
-
//# debugId=
|
|
573
|
+
//# debugId=b668f2a6-403a-56fd-86cc-2e9de852cf65
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["index.ts"],"sourceRoot":"/","sourcesContent":["import express from 'express';\nimport type { Request, Response } from 'express';\nimport { createServer } from 'http';\nimport { Server } from 'socket.io';\nimport cors from 'cors';\nimport dotenv from 'dotenv';\nimport { createExpressMiddleware } from '@trpc/server/adapters/express';\nimport { appRouter } from './routers/_app.js';\nimport { createTRPCContext, createCallerFactory } from './trpc.js';\nimport { findUserBySessionToken } from './models/auth.js';\nimport { logger } from './utils/logger.js';\nimport { setupSocketHandlers } from './socket/handlers.js';\nimport { bucket } from './lib/googleCloudStorage.js';\nimport { validateDirectUploadIntent } from './lib/fileUpload.js';\nimport { prisma } from './lib/prisma.js';\nimport { pusher } from './lib/pusher.js';\nimport { connectRedis, disconnectRedis } from './lib/redis.js';\nimport { createCorsOriginMatcher } from './lib/config/cors.js';\n\nimport { authLimiter, generalLimiter, helmetConfig, uploadLimiter } from './middleware/security.js';\n\nimport * as Sentry from \"@sentry/node\";\nimport { env } from './lib/config/env.js';\nimport compression from 'compression';\nimport { v4 as uuidv4 } from 'uuid';\n\n\nimport \"./instrument.js\";\nimport { openAIClient } from './utils/inference.js';\n\nconst app = express();\n\napp.set('trust proxy', 1);\n\napp.use(helmetConfig);\napp.use(compression());\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n\napp.use((req, res, next) => {\n const requestId = uuidv4();\n res.setHeader('X-Request-ID', requestId);\n next();\n});\n\nconst { allowedOrigins, allowedOriginPatterns, isAllowedOrigin } = createCorsOriginMatcher(env);\n\n// CORS middleware\napp.use(cors({\n origin: (origin, callback) => {\n if (!origin || isAllowedOrigin(origin)) {\n callback(null, true);\n return;\n }\n\n logger.warn('CORS origin rejected', { origin, allowedOrigins });\n callback(null, false);\n },\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'x-user'],\n preflightContinue: false,\n optionsSuccessStatus: 204,\n}));\n\napp.use(generalLimiter);\n\n// CORS debugging middleware\napp.use((req, res, next) => {\n if (req.method === 'OPTIONS' || req.path.includes('trpc')) {\n logger.info('CORS Request', {\n method: req.method,\n path: req.path,\n origin: req.headers.origin,\n userAgent: req.headers['user-agent']\n });\n }\n next();\n});\n\n// Response time logging middleware\napp.use((req, res, next) => {\n const start = Date.now();\n res.on('finish', () => {\n const duration = Date.now() - start;\n logger.info('Request completed', {\n method: req.method,\n path: req.path,\n statusCode: res.statusCode,\n duration: `${duration}ms`\n });\n });\n next();\n});\n\n// app.use(\"/panel\", async (_, res) => {\n// if (env.NODE_ENV !== \"development\") {\n// return res.status(404).send(\"Not Found\");\n// }\n\n// // Dynamically import renderTrpcPanel only in development\n// const { renderTrpcPanel } = await import(\"trpc-ui\");\n\n// return res.send(\n// renderTrpcPanel(appRouter, {\n// url: \"/trpc\", // Base url of your trpc server\n// meta: {\n// title: \"Studious Backend\",\n// description:\n// \"This is the backend for the Studious application.\",\n// },\n// })\n// );\n// });\n\n\n// Create HTTP server\nconst httpServer = createServer(app);\n\napp.get('/', async (req, res) => {\n res.status(200).json({ \n status: 'OK',\n timestamp: new Date().toISOString(),\n uptime: process.uptime(),\n version: process.env.npm_package_version,\n environment: process.env.NODE_ENV,\n appUrl: process.env.NEXT_PUBLIC_APP_URL,\n });\n});\n\napp.get('/health', async (req, res) => {\n\n try {\n // Check database connectivity\n await prisma.$queryRaw`SELECT 1`;\n \n res.status(200).json({ \n status: 'OK',\n timestamp: new Date().toISOString(),\n uptime: process.uptime(),\n database: 'connected'\n });\n } catch (error) {\n res.status(503).json({ \n status: 'ERROR',\n database: 'disconnected',\n error: error instanceof Error ? error.message : 'Unknown error'\n });\n }\n});\n\n// Pusher channel auth (for private-* and presence-* channels)\n// Token from: x-user header, or cookie (same-origin requests send cookies automatically)\napp.post('/api/pusher/auth', async (req, res) => {\n try {\n let token = req.headers['x-user'] as string | undefined;\n if (!token && req.headers.cookie) {\n const cookieName = env.PUSHER_AUTH_COOKIE_NAME || 'token';\n const match = req.headers.cookie.match(new RegExp(`${cookieName}=([^;]+)`));\n token = match?.[1]?.trim();\n }\n const { socket_id, channel_name } = req.body as { socket_id?: string; channel_name?: string };\n\n if (!socket_id || !channel_name) {\n return res.status(400).json({ error: 'socket_id and channel_name required' });\n }\n\n if (!token) {\n return res.status(401).json({ error: 'Authentication required' });\n }\n\n const user = await findUserBySessionToken(token);\n\n if (!user) {\n return res.status(401).json({ error: 'Invalid or expired session' });\n }\n\n // Verify channel access for private-conversation-* channels\n if (channel_name.startsWith('private-conversation-')) {\n const conversationId = channel_name.replace('private-conversation-', '');\n const member = await prisma.conversationMember.findFirst({\n where: { conversationId, userId: user.id },\n });\n \n if (!member) {\n return res.status(403).json({ error: 'Not a member of this conversation' });\n }\n }\n\n if (channel_name.startsWith('private-worksheet-')) {\n const worksheetId = channel_name.replace('private-worksheet-', '');\n const worksheet = await prisma.studentWorksheetResponse.findFirst({\n where: { id: worksheetId, OR: [\n { studentId: user.id },\n { submission: { assignment: { class: { teachers: { some: { id: user.id } } } } } },\n ] },\n });\n if (!worksheet) {\n return res.status(403).json({ error: 'No access to this worksheet' });\n }\n }\n\n if (channel_name.startsWith('private-teacher-')) {\n const classId = channel_name.replace('private-teacher-', '');\n const isTeacher = await prisma.class.findFirst({\n where: { id: classId, teachers: { some: { id: user.id } } },\n });\n if (!isTeacher) {\n return res.status(403).json({ error: 'Not a teacher of this class' });\n }\n }\n\n // Verify channel access for private-class-* channels\n // if (channel_name.startsWith('private-class-')) {\n // const classId = channel_name.replace('private-class-', '');\n // const isMember = await prisma.class.findFirst({\n // where: {\n // id: classId,\n // OR: [\n // { students: { some: { id: user.id } } },\n // { teachers: { some: { id: user.id } } },\n // ],\n // },\n // });\n // if (!isMember) {\n // return res.status(403).json({ error: 'Not a member of this class' });\n // }\n // }\n\n if (channel_name.startsWith('presence-')) {\n const authResponse = pusher.authorizeChannel(socket_id, channel_name, {\n user_id: user.id,\n user_info: { username: user.username },\n });\n return res.json(authResponse);\n }\n\n const authResponse = pusher.authorizeChannel(socket_id, channel_name);\n return res.json(authResponse);\n } catch (error) {\n logger.error('Pusher auth error', { error });\n return res.status(500).json({ error: 'Authentication failed' });\n }\n});\n\n// Setup Socket.IO\nconst io = new Server(httpServer, {\n cors: {\n origin: (origin, callback) => {\n callback(null, !origin || isAllowedOrigin(origin));\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n credentials: true,\n allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Access-Control-Allow-Origin', 'x-user']\n },\n transports: ['websocket', 'polling'],\n pingTimeout: 60000,\n pingInterval: 25000,\n connectTimeout: 45000,\n path: '/socket.io/',\n allowEIO3: true\n});\n\n// Add server-level logging\nio.engine.on('connection_error', (err: Error) => {\n logger.error('Socket connection error', { error: err.message });\n});\n\n// Setup socket handlers\nsetupSocketHandlers(io);\n\n// File serving endpoint for secure file access\napp.get('/api/files/:fileId', async (req, res) => {\n try {\n const fileId = decodeURIComponent(req.params.fileId);\n // console.log('File request:', { fileId, originalPath: req.params.fileId });\n \n // Get user from request headers\n const userHeader = req.headers['x-user'];\n if (!userHeader) {\n return res.status(401).json({ error: 'Authentication required' });\n }\n\n const token = typeof userHeader === 'string' ? userHeader : userHeader[0];\n\n // Find user by session token\n const user = await findUserBySessionToken(token);\n\n if (!user) {\n return res.status(401).json({ error: 'Invalid or expired session' });\n }\n\n // Find file in database by path\n const fileRecord = await prisma.file.findFirst({\n where: { id: fileId },\n include: {\n user: true,\n assignment: {\n include: {\n class: {\n include: {\n students: true,\n teachers: true\n }\n }\n }\n },\n submission: {\n include: {\n student: true,\n assignment: {\n include: {\n class: {\n include: {\n teachers: true\n }\n }\n }\n }\n }\n },\n annotations: {\n include: {\n student: true,\n assignment: {\n include: {\n class: {\n include: {\n teachers: true\n }\n }\n }\n }\n }\n },\n folder: {\n include: {\n class: {\n include: {\n students: true,\n teachers: true\n }\n }\n }\n },\n classDraft: {\n include: {\n students: true,\n teachers: true\n }\n }\n }\n });\n\n if (!fileRecord) {\n return res.status(404).json({ error: 'File not found in database' });\n }\n\n // Check if user has permission to access this file\n let hasPermission = false;\n\n // Check if user created the file\n if (fileRecord.userId === user.id) {\n hasPermission = true;\n }\n\n // Check if file is related to a class where user is a member\n if (!hasPermission) {\n // Check assignment files\n if (fileRecord.assignment?.class) {\n const classData = fileRecord.assignment.class;\n const isStudent = classData.students.some(student => student.id === user.id);\n const isTeacher = classData.teachers.some(teacher => teacher.id === user.id);\n if (isStudent || isTeacher) {\n hasPermission = true;\n }\n }\n\n if (!hasPermission && fileRecord.annotations) {\n const annotation = fileRecord.annotations;\n if (annotation.studentId === user.id) {\n hasPermission = true;\n } else if (annotation.assignment?.class?.teachers.some(teacher => teacher.id === user.id)) {\n hasPermission = true;\n }\n }\n\n // Check submission files (student can access their own submissions, teachers can access all submissions in their class)\n if (!hasPermission && fileRecord.submission) {\n const submission = fileRecord.submission;\n if (submission.studentId === user.id) {\n hasPermission = true; // Student accessing their own submission\n } else if (submission.assignment?.class?.teachers.some(teacher => teacher.id === user.id)) {\n hasPermission = true; // Teacher accessing submission in their class\n }\n }\n\n // Check folder files\n if (!hasPermission && fileRecord.folder?.class) {\n const classData = fileRecord.folder.class;\n const isStudent = classData.students.some(student => student.id === user.id);\n const isTeacher = classData.teachers.some(teacher => teacher.id === user.id);\n if (isStudent || isTeacher) {\n hasPermission = true;\n }\n }\n\n // Check class draft files\n if (!hasPermission && fileRecord.classDraft) {\n const classData = fileRecord.classDraft;\n const isStudent = classData.students.some(student => student.id === user.id);\n const isTeacher = classData.teachers.some(teacher => teacher.id === user.id);\n if (isStudent || isTeacher) {\n hasPermission = true;\n }\n }\n }\n\n if (!hasPermission) {\n return res.status(403).json({ error: 'Access denied - insufficient permissions' });\n }\n \n const filePath = fileRecord.path;\n \n // Get file from Google Cloud Storage\n const file = bucket.file(filePath);\n const [exists] = await file.exists();\n \n if (!exists) {\n return res.status(404).json({ error: 'File not found in storage', filePath });\n }\n \n // Get file metadata\n const [metadata] = await file.getMetadata();\n \n // Set appropriate headers\n res.set({\n 'Content-Type': metadata.contentType || 'application/octet-stream',\n 'Content-Length': metadata.size,\n 'Cache-Control': 'public, max-age=31536000', // 1 year cache\n 'ETag': metadata.etag,\n });\n \n // Stream file to response\n const stream = file.createReadStream();\n stream.pipe(res);\n \n stream.on('error', (error) => {\n logger.error('Error streaming file:', {error});\n if (!res.headersSent) {\n res.status(500).json({ error: 'Error streaming file' });\n }\n });\n \n } catch (error) {\n logger.error('Error serving file:', {error});\n res.status(500).json({ error: 'Internal server error' });\n }\n});\n\napp.use('/trpc/auth.login', authLimiter);\napp.use('/trpc/auth.register', authLimiter);\n\nasync function getAuthenticatedRequestUser(req: Request) {\n const userHeader = req.headers['x-user'];\n const tokenFromUserHeader = typeof userHeader === 'string' ? userHeader : userHeader?.[0];\n const authorizationHeader = req.headers.authorization;\n const tokenFromAuthorization =\n typeof authorizationHeader === 'string' && authorizationHeader.startsWith('Bearer ')\n ? authorizationHeader.slice(7)\n : null;\n\n let token = tokenFromUserHeader ?? tokenFromAuthorization;\n\n if (!token && req.headers.cookie) {\n const cookieName = env.PUSHER_AUTH_COOKIE_NAME || 'token';\n const match = req.headers.cookie.match(new RegExp(cookieName + '=([^;]+)'));\n token = match?.[1]?.trim() ?? null;\n }\n\n if (!token) {\n return null;\n }\n\n return findUserBySessionToken(token);\n}\n\nfunction getUploadSessionId(req: Request) {\n const queryValue = req.query.uploadSessionId;\n if (typeof queryValue === 'string' && queryValue.trim()) {\n return queryValue;\n }\n\n const headerValue = req.headers['x-upload-session-id'];\n return typeof headerValue === 'string' ? headerValue : headerValue?.[0];\n}\n\n// File upload endpoint for secure file uploads (supports both POST and PUT)\napp.post('/api/upload/:filePath', uploadLimiter, async (req, res) => {\n await handleFileUpload(req, res);\n});\n\napp.put('/api/upload/:filePath', uploadLimiter, async (req, res) => {\n await handleFileUpload(req, res);\n});\n\nasync function handleFileUpload(req: Request, res: Response) {\n try {\n const filePath = decodeURIComponent(req.params.filePath);\n \n // Set CORS headers for upload endpoint\n const origin = req.headers.origin;\n \n if (origin && !isAllowedOrigin(origin)) {\n return res.status(403).json({ error: 'Origin not allowed' });\n }\n\n if (origin) {\n res.header('Access-Control-Allow-Origin', origin);\n }\n \n res.header('Access-Control-Allow-Credentials', 'true');\n\n const user = await getAuthenticatedRequestUser(req);\n if (!user) {\n return res.status(401).json({ error: 'Authentication required' });\n }\n\n const uploadSessionId = getUploadSessionId(req);\n if (!uploadSessionId) {\n return res.status(401).json({ error: 'Upload session is required' });\n }\n\n await validateDirectUploadIntent({\n filePath,\n uploadSessionId,\n userId: user.id,\n });\n \n const contentType = req.headers['content-type'] || 'application/octet-stream';\n const file = bucket.file(filePath);\n const writeStream = file.createWriteStream({\n metadata: {\n contentType,\n },\n });\n \n writeStream.on('error', (error) => {\n logger.error('Error uploading file:', {error, filePath, userId: user.id});\n if (!res.headersSent) {\n res.status(500).json({ error: 'Error uploading file' });\n }\n });\n \n writeStream.on('finish', () => {\n res.status(200).json({ \n success: true, \n filePath,\n message: 'File uploaded successfully' \n });\n });\n \n req.pipe(writeStream);\n \n } catch (error) {\n logger.error('Error handling file upload:', {error});\n const code = typeof error === 'object' && error && 'code' in error ? error.code : null;\n const message = error instanceof Error ? error.message : 'Internal server error';\n\n if (code === 'FORBIDDEN') {\n return res.status(403).json({ error: message });\n }\n\n if (code === 'BAD_REQUEST') {\n return res.status(400).json({ error: message });\n }\n\n res.status(500).json({ error: 'Internal server error' });\n }\n}\n\n// Create caller\nconst createCaller = createCallerFactory(appRouter);\n\n// Fallback OPTIONS handler — prevents tRPC from rejecting preflight requests\n// when the cors middleware passes through without ending the response.\napp.options('/trpc/*', (req, res) => {\n const origin = req.headers.origin;\n if (origin && isAllowedOrigin(origin)) {\n res.setHeader('Access-Control-Allow-Origin', origin);\n res.setHeader('Access-Control-Allow-Credentials', 'true');\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, x-user');\n }\n res.sendStatus(204);\n});\n\n// Setup tRPC middleware\napp.use(\n '/trpc',\n createExpressMiddleware({\n router: appRouter,\n createContext: async ({ req, res }: { req: Request; res: Response }) => {\n return createTRPCContext({ req, res });\n },\n })\n);\n\n// IMPORTANT: Sentry error handler must be added AFTER all other middleware and routes\n// but BEFORE any other error handlers\nSentry.setupExpressErrorHandler(app);\n\n// app.use(function onError(err, req, res, next) {\n// // The error id is attached to `res.sentry` to be returned\n// // and optionally displayed to the user for support.\n// res.statusCode = 500;\n// res.end(res.sentry + \"\\n\");\n// });\n\n\nconst PORT = env.PORT || 3001;\n\nconnectRedis().then(() => {\n httpServer.listen(PORT, () => {\n logger.info(`Server running on port ${PORT}`, {\n port: PORT,\n services: ['tRPC', 'Socket.IO', env.REDIS_URL ? 'Redis' : null].filter(Boolean),\n });\n });\n}); \n\n// log all env variables\nlogger.info('Configurations', {\n NODE_ENV: env.NODE_ENV,\n PORT: env.PORT,\n NEXT_PUBLIC_APP_URL: env.NEXT_PUBLIC_APP_URL,\n LOG_MODE: env.LOG_MODE,\n});\n\n// Log CORS configuration\nlogger.info('CORS Configuration', {\n allowedOrigins,\n allowedOriginPatterns: allowedOriginPatterns.map((pattern) => pattern.source),\n});\n\nconst gracefulShutdown = (signal: string) => {\n logger.info(`Received ${signal}, shutting down gracefully`);\n \n httpServer.close(() => {\n logger.info('HTTP server closed');\n \n io.close(() => {\n logger.info('Socket.IO server closed');\n\n disconnectRedis().then(() =>\n prisma.$disconnect().then(() => {\n logger.info('Database connections closed');\n process.exit(0);\n }).catch((err) => {\n logger.error('Error disconnecting from database', { error: err });\n process.exit(1);\n })\n );\n });\n });\n \n // Force shutdown after 10 seconds\n setTimeout(() => {\n logger.error('Forced shutdown after timeout');\n process.exit(1);\n }, 10000);\n};\n\nprocess.on('SIGTERM', () => gracefulShutdown('SIGTERM'));\nprocess.on('SIGINT', () => gracefulShutdown('SIGINT'));\n"],"names":[],"mappings":";;AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,YAAY,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,iBAAiB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EF,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC;AACzD,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC","debug_id":"3cfa0c9c-5588-5fbd-a283-4495b71df718"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["index.ts"],"sourceRoot":"/","sourcesContent":["import express from 'express';\nimport type { Request, Response } from 'express';\nimport { createServer } from 'http';\nimport { Server } from 'socket.io';\nimport cors from 'cors';\nimport dotenv from 'dotenv';\nimport { createExpressMiddleware } from '@trpc/server/adapters/express';\nimport { appRouter } from './routers/_app.js';\nimport { createTRPCContext, createCallerFactory } from './trpc.js';\nimport { findUserBySessionToken } from './models/auth.js';\nimport { logger } from './utils/logger.js';\nimport { setupSocketHandlers } from './socket/handlers.js';\nimport { bucket } from './lib/googleCloudStorage.js';\nimport { validateDirectUploadIntent } from './lib/fileUpload.js';\nimport { prisma } from './lib/prisma.js';\nimport { pusher } from './lib/pusher.js';\nimport { connectRedis, disconnectRedis } from './lib/redis.js';\nimport { createCorsOriginMatcher } from './lib/config/cors.js';\n\nimport { authLimiter, generalLimiter, helmetConfig, uploadLimiter } from './middleware/security.js';\n\nimport * as Sentry from \"@sentry/node\";\nimport { env } from './lib/config/env.js';\nimport compression from 'compression';\nimport { v4 as uuidv4 } from 'uuid';\n\n\nimport \"./instrument.js\";\nimport { openAIClient } from './utils/inference.js';\n\nconst app = express();\n\napp.set('trust proxy', 1);\n\napp.use(helmetConfig);\napp.use(compression());\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n\napp.use((req, res, next) => {\n const requestId = uuidv4();\n res.setHeader('X-Request-ID', requestId);\n next();\n});\n\nconst { allowedOrigins, allowedOriginPatterns, isAllowedOrigin } = createCorsOriginMatcher(env);\n\n// CORS middleware\napp.use(cors({\n origin: (origin, callback) => {\n if (!origin || isAllowedOrigin(origin)) {\n callback(null, true);\n return;\n }\n\n logger.warn('CORS origin rejected', { origin, allowedOrigins });\n callback(null, false);\n },\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'x-user'],\n preflightContinue: false,\n optionsSuccessStatus: 204,\n}));\n\napp.use(generalLimiter);\n\n// CORS debugging middleware\napp.use((req, res, next) => {\n if (req.method === 'OPTIONS' || req.path.includes('trpc')) {\n logger.info('CORS Request', {\n method: req.method,\n path: req.path,\n origin: req.headers.origin,\n userAgent: req.headers['user-agent']\n });\n }\n next();\n});\n\n// Response time logging middleware\napp.use((req, res, next) => {\n const start = Date.now();\n res.on('finish', () => {\n const duration = Date.now() - start;\n logger.info('Request completed', {\n method: req.method,\n path: req.path,\n statusCode: res.statusCode,\n duration: `${duration}ms`\n });\n });\n next();\n});\n\n// app.use(\"/panel\", async (_, res) => {\n// if (env.NODE_ENV !== \"development\") {\n// return res.status(404).send(\"Not Found\");\n// }\n\n// // Dynamically import renderTrpcPanel only in development\n// const { renderTrpcPanel } = await import(\"trpc-ui\");\n\n// return res.send(\n// renderTrpcPanel(appRouter, {\n// url: \"/trpc\", // Base url of your trpc server\n// meta: {\n// title: \"Studious Backend\",\n// description:\n// \"This is the backend for the Studious application.\",\n// },\n// })\n// );\n// });\n\n\n// Create HTTP server\nconst httpServer = createServer(app);\n\napp.get('/', async (req, res) => {\n res.status(200).json({ \n status: 'OK',\n timestamp: new Date().toISOString(),\n uptime: process.uptime(),\n version: process.env.npm_package_version,\n environment: process.env.NODE_ENV,\n appUrl: process.env.NEXT_PUBLIC_APP_URL,\n });\n});\n\napp.get('/health', async (req, res) => {\n\n try {\n // Check database connectivity\n await prisma.$queryRaw`SELECT 1`;\n \n res.status(200).json({ \n status: 'OK',\n timestamp: new Date().toISOString(),\n uptime: process.uptime(),\n database: 'connected'\n });\n } catch (error) {\n res.status(503).json({ \n status: 'ERROR',\n database: 'disconnected',\n error: error instanceof Error ? error.message : 'Unknown error'\n });\n }\n});\n\n// Pusher channel auth (for private-* and presence-* channels)\n// Token from: x-user header, or cookie (same-origin requests send cookies automatically)\napp.post('/api/pusher/auth', async (req, res) => {\n try {\n let token = req.headers['x-user'] as string | undefined;\n if (!token && req.headers.cookie) {\n const cookieName = env.PUSHER_AUTH_COOKIE_NAME || 'token';\n const match = req.headers.cookie.match(new RegExp(`${cookieName}=([^;]+)`));\n token = match?.[1]?.trim();\n }\n const { socket_id, channel_name } = req.body as { socket_id?: string; channel_name?: string };\n\n if (!socket_id || !channel_name) {\n return res.status(400).json({ error: 'socket_id and channel_name required' });\n }\n\n if (!token) {\n return res.status(401).json({ error: 'Authentication required' });\n }\n\n const user = await findUserBySessionToken(token);\n\n if (!user) {\n return res.status(401).json({ error: 'Invalid or expired session' });\n }\n\n // Verify channel access for private-conversation-* channels\n if (channel_name.startsWith('private-conversation-')) {\n const conversationId = channel_name.replace('private-conversation-', '');\n const member = await prisma.conversationMember.findFirst({\n where: { conversationId, userId: user.id },\n });\n \n if (!member) {\n return res.status(403).json({ error: 'Not a member of this conversation' });\n }\n }\n\n if (channel_name.startsWith('private-worksheet-')) {\n const worksheetId = channel_name.replace('private-worksheet-', '');\n const worksheet = await prisma.studentWorksheetResponse.findFirst({\n where: { id: worksheetId, OR: [\n { studentId: user.id },\n { submission: { assignment: { class: { teachers: { some: { id: user.id } } } } } },\n ] },\n });\n if (!worksheet) {\n return res.status(403).json({ error: 'No access to this worksheet' });\n }\n }\n\n if (channel_name.startsWith('private-teacher-')) {\n const classId = channel_name.replace('private-teacher-', '');\n const isTeacher = await prisma.class.findFirst({\n where: { id: classId, teachers: { some: { id: user.id } } },\n });\n if (!isTeacher) {\n return res.status(403).json({ error: 'Not a teacher of this class' });\n }\n }\n\n // Verify channel access for private-class-* channels\n // if (channel_name.startsWith('private-class-')) {\n // const classId = channel_name.replace('private-class-', '');\n // const isMember = await prisma.class.findFirst({\n // where: {\n // id: classId,\n // OR: [\n // { students: { some: { id: user.id } } },\n // { teachers: { some: { id: user.id } } },\n // ],\n // },\n // });\n // if (!isMember) {\n // return res.status(403).json({ error: 'Not a member of this class' });\n // }\n // }\n\n if (channel_name.startsWith('presence-')) {\n const authResponse = pusher.authorizeChannel(socket_id, channel_name, {\n user_id: user.id,\n user_info: { username: user.username },\n });\n return res.json(authResponse);\n }\n\n const authResponse = pusher.authorizeChannel(socket_id, channel_name);\n return res.json(authResponse);\n } catch (error) {\n logger.error('Pusher auth error', { error });\n return res.status(500).json({ error: 'Authentication failed' });\n }\n});\n\n// Setup Socket.IO\nconst io = new Server(httpServer, {\n cors: {\n origin: (origin, callback) => {\n callback(null, !origin || isAllowedOrigin(origin));\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n credentials: true,\n allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Access-Control-Allow-Origin', 'x-user']\n },\n transports: ['websocket', 'polling'],\n pingTimeout: 60000,\n pingInterval: 25000,\n connectTimeout: 45000,\n path: '/socket.io/',\n allowEIO3: true\n});\n\n// Add server-level logging\nio.engine.on('connection_error', (err: Error) => {\n logger.error('Socket connection error', { error: err.message });\n});\n\n// Setup socket handlers\nsetupSocketHandlers(io);\n\n// File serving endpoint for secure file access\napp.get('/api/files/:fileId', async (req, res) => {\n try {\n const fileId = decodeURIComponent(req.params.fileId);\n // console.log('File request:', { fileId, originalPath: req.params.fileId });\n \n // Get user from request headers\n const userHeader = req.headers['x-user'];\n if (!userHeader) {\n return res.status(401).json({ error: 'Authentication required' });\n }\n\n const token = typeof userHeader === 'string' ? userHeader : userHeader[0];\n\n // Find user by session token\n const user = await findUserBySessionToken(token);\n\n if (!user) {\n return res.status(401).json({ error: 'Invalid or expired session' });\n }\n\n // Find file in database by path\n const fileRecord = await prisma.file.findFirst({\n where: { id: fileId },\n include: {\n user: true,\n assignment: {\n include: {\n class: {\n include: {\n students: true,\n teachers: true\n }\n }\n }\n },\n submission: {\n include: {\n student: true,\n assignment: {\n include: {\n class: {\n include: {\n teachers: true\n }\n }\n }\n }\n }\n },\n annotations: {\n include: {\n student: true,\n assignment: {\n include: {\n class: {\n include: {\n teachers: true\n }\n }\n }\n }\n }\n },\n folder: {\n include: {\n class: {\n include: {\n students: true,\n teachers: true\n }\n }\n }\n },\n classDraft: {\n include: {\n students: true,\n teachers: true\n }\n }\n }\n });\n\n if (!fileRecord) {\n return res.status(404).json({ error: 'File not found in database' });\n }\n\n // Check if user has permission to access this file\n let hasPermission = false;\n\n // Check if user created the file\n if (fileRecord.userId === user.id) {\n hasPermission = true;\n }\n\n // Check if file is related to a class where user is a member\n if (!hasPermission) {\n // Check assignment files\n if (fileRecord.assignment?.class) {\n const classData = fileRecord.assignment.class;\n const isStudent = classData.students.some(student => student.id === user.id);\n const isTeacher = classData.teachers.some(teacher => teacher.id === user.id);\n if (isStudent || isTeacher) {\n hasPermission = true;\n }\n }\n\n if (!hasPermission && fileRecord.annotations) {\n const annotation = fileRecord.annotations;\n if (annotation.studentId === user.id) {\n hasPermission = true;\n } else if (annotation.assignment?.class?.teachers.some(teacher => teacher.id === user.id)) {\n hasPermission = true;\n }\n }\n\n // Check submission files (student can access their own submissions, teachers can access all submissions in their class)\n if (!hasPermission && fileRecord.submission) {\n const submission = fileRecord.submission;\n if (submission.studentId === user.id) {\n hasPermission = true; // Student accessing their own submission\n } else if (submission.assignment?.class?.teachers.some(teacher => teacher.id === user.id)) {\n hasPermission = true; // Teacher accessing submission in their class\n }\n }\n\n // Check folder files\n if (!hasPermission && fileRecord.folder?.class) {\n const classData = fileRecord.folder.class;\n const isStudent = classData.students.some(student => student.id === user.id);\n const isTeacher = classData.teachers.some(teacher => teacher.id === user.id);\n if (isStudent || isTeacher) {\n hasPermission = true;\n }\n }\n\n // Check class draft files\n if (!hasPermission && fileRecord.classDraft) {\n const classData = fileRecord.classDraft;\n const isStudent = classData.students.some(student => student.id === user.id);\n const isTeacher = classData.teachers.some(teacher => teacher.id === user.id);\n if (isStudent || isTeacher) {\n hasPermission = true;\n }\n }\n }\n\n if (!hasPermission) {\n return res.status(403).json({ error: 'Access denied - insufficient permissions' });\n }\n \n const filePath = fileRecord.path;\n \n // Get file from Google Cloud Storage\n const file = bucket.file(filePath);\n const [exists] = await file.exists();\n \n if (!exists) {\n return res.status(404).json({ error: 'File not found in storage', filePath });\n }\n \n // Get file metadata\n const [metadata] = await file.getMetadata();\n \n // Set appropriate headers\n res.set({\n 'Content-Type': metadata.contentType || 'application/octet-stream',\n 'Content-Length': metadata.size,\n 'Cache-Control': 'public, max-age=31536000', // 1 year cache\n 'ETag': metadata.etag,\n });\n \n // Stream file to response\n const stream = file.createReadStream();\n stream.pipe(res);\n \n stream.on('error', (error) => {\n logger.error('Error streaming file:', {error});\n if (!res.headersSent) {\n res.status(500).json({ error: 'Error streaming file' });\n }\n });\n \n } catch (error) {\n logger.error('Error serving file:', {error});\n res.status(500).json({ error: 'Internal server error' });\n }\n});\n\napp.use('/trpc/auth.login', authLimiter);\napp.use('/trpc/auth.register', authLimiter);\n\nasync function getAuthenticatedRequestUser(req: Request) {\n const userHeader = req.headers['x-user'];\n const tokenFromUserHeader = typeof userHeader === 'string' ? userHeader : userHeader?.[0];\n const authorizationHeader = req.headers.authorization;\n const tokenFromAuthorization =\n typeof authorizationHeader === 'string' && authorizationHeader.startsWith('Bearer ')\n ? authorizationHeader.slice(7)\n : null;\n\n let token = tokenFromUserHeader ?? tokenFromAuthorization;\n\n if (!token && req.headers.cookie) {\n const cookieName = env.PUSHER_AUTH_COOKIE_NAME || 'token';\n const match = req.headers.cookie.match(new RegExp(cookieName + '=([^;]+)'));\n token = match?.[1]?.trim() ?? null;\n }\n\n if (!token) {\n return null;\n }\n\n return findUserBySessionToken(token);\n}\n\nfunction getUploadSessionId(req: Request) {\n const queryValue = req.query.uploadSessionId;\n if (typeof queryValue === 'string' && queryValue.trim()) {\n return queryValue;\n }\n\n const headerValue = req.headers['x-upload-session-id'];\n return typeof headerValue === 'string' ? headerValue : headerValue?.[0];\n}\n\n// File upload endpoint for secure file uploads (supports both POST and PUT)\napp.post('/api/upload/:filePath', async (req, res) => {\n await handleFileUpload(req, res);\n});\n\napp.put('/api/upload/:filePath', uploadLimiter, async (req, res) => {\n await handleFileUpload(req, res);\n});\n\nasync function handleFileUpload(req: Request, res: Response) {\n try {\n const filePath = decodeURIComponent(req.params.filePath);\n\n // Set CORS headers for upload endpoint\n const origin = req.headers.origin;\n \n if (origin && !isAllowedOrigin(origin)) {\n return res.status(403).json({ error: 'Origin not allowed' });\n }\n\n if (origin) {\n res.header('Access-Control-Allow-Origin', origin);\n }\n \n res.header('Access-Control-Allow-Credentials', 'true');\n\n const user = await getAuthenticatedRequestUser(req);\n if (!user) {\n return res.status(401).json({ error: 'Authentication required' });\n }\n\n const uploadSessionId = getUploadSessionId(req);\n if (!uploadSessionId) {\n return res.status(401).json({ error: 'Upload session is required' });\n }\n\n await validateDirectUploadIntent({\n filePath,\n uploadSessionId,\n userId: user.id,\n });\n \n const contentType = req.headers['content-type'] || 'application/octet-stream';\n const file = bucket.file(filePath);\n\n const writeStream = file.createWriteStream({\n metadata: {\n contentType,\n },\n });\n \n writeStream.on('error', (error) => {\n logger.error('Error uploading file:', {error, filePath, userId: user.id});\n if (!res.headersSent) {\n res.status(500).json({ error: 'Error uploading file' });\n }\n });\n \n writeStream.on('finish', () => {\n res.status(200).json({ \n success: true, \n filePath,\n message: 'File uploaded successfully' \n });\n });\n \n req.pipe(writeStream);\n \n } catch (error) {\n logger.error('Error handling file upload:', {error});\n const code = typeof error === 'object' && error && 'code' in error ? error.code : null;\n const message = error instanceof Error ? error.message : 'Internal server error';\n\n if (code === 'FORBIDDEN') {\n return res.status(403).json({ error: message });\n }\n\n if (code === 'BAD_REQUEST') {\n return res.status(400).json({ error: message });\n }\n\n res.status(500).json({ error: 'Internal server error' });\n }\n}\n\n// Create caller\nconst createCaller = createCallerFactory(appRouter);\n\n// Fallback OPTIONS handler — prevents tRPC from rejecting preflight requests\n// when the cors middleware passes through without ending the response.\napp.options('/trpc/*', (req, res) => {\n const origin = req.headers.origin;\n if (origin && isAllowedOrigin(origin)) {\n res.setHeader('Access-Control-Allow-Origin', origin);\n res.setHeader('Access-Control-Allow-Credentials', 'true');\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, x-user');\n }\n res.sendStatus(204);\n});\n\n// Setup tRPC middleware\napp.use(\n '/trpc',\n createExpressMiddleware({\n router: appRouter,\n createContext: async ({ req, res }: { req: Request; res: Response }) => {\n return createTRPCContext({ req, res });\n },\n })\n);\n\n// IMPORTANT: Sentry error handler must be added AFTER all other middleware and routes\n// but BEFORE any other error handlers\nSentry.setupExpressErrorHandler(app);\n\n// app.use(function onError(err, req, res, next) {\n// // The error id is attached to `res.sentry` to be returned\n// // and optionally displayed to the user for support.\n// res.statusCode = 500;\n// res.end(res.sentry + \"\\n\");\n// });\n\n\nconst PORT = env.PORT || 3001;\n\nconnectRedis().then(() => {\n httpServer.listen(PORT, () => {\n logger.info(`Server running on port ${PORT}`, {\n port: PORT,\n services: ['tRPC', 'Socket.IO', env.REDIS_URL ? 'Redis' : null].filter(Boolean),\n });\n });\n}); \n\n// log all env variables\nlogger.info('Configurations', {\n NODE_ENV: env.NODE_ENV,\n PORT: env.PORT,\n NEXT_PUBLIC_APP_URL: env.NEXT_PUBLIC_APP_URL,\n LOG_MODE: env.LOG_MODE,\n});\n\n// Log CORS configuration\nlogger.info('CORS Configuration', {\n allowedOrigins,\n allowedOriginPatterns: allowedOriginPatterns.map((pattern) => pattern.source),\n});\n\nconst gracefulShutdown = (signal: string) => {\n logger.info(`Received ${signal}, shutting down gracefully`);\n \n httpServer.close(() => {\n logger.info('HTTP server closed');\n \n io.close(() => {\n logger.info('Socket.IO server closed');\n\n disconnectRedis().then(() =>\n prisma.$disconnect().then(() => {\n logger.info('Database connections closed');\n process.exit(0);\n }).catch((err) => {\n logger.error('Error disconnecting from database', { error: err });\n process.exit(1);\n })\n );\n });\n });\n \n // Force shutdown after 10 seconds\n setTimeout(() => {\n logger.error('Forced shutdown after timeout');\n process.exit(1);\n }, 10000);\n};\n\nprocess.on('SIGTERM', () => gracefulShutdown('SIGTERM'));\nprocess.on('SIGINT', () => gracefulShutdown('SIGINT'));\n"],"names":[],"mappings":";;AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,YAAY,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,6BAA6B,CAAC;AACrD,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAE/D,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEpG,OAAO,KAAK,MAAM,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,GAAG,EA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6BAA6B,CAAC,CAAC;gBAC3C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACf,MAAM,CAAC,KAAK,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;gBAClE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC,CAAC,CACH,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,kCAAkC;IAClC,UAAU,CAAC,GAAG,EAAE;QACd,MAAM,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC;QAC9C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,EAAE,KAAK,CAAC,CAAC;AACZ,CAAC,CAAC;AAEF,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC;AACzD,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC","debug_id":"b668f2a6-403a-56fd-86cc-2e9de852cf65"}
|
|
@@ -246,6 +246,7 @@ export declare function createWorksheetQuestion(data: {
|
|
|
246
246
|
points?: number;
|
|
247
247
|
options?: object;
|
|
248
248
|
markScheme?: object;
|
|
249
|
+
order?: number;
|
|
249
250
|
}): import(".prisma/client").Prisma.Prisma__WorksheetQuestionClient<{
|
|
250
251
|
type: import(".prisma/client").$Enums.WorksheetQuestionType;
|
|
251
252
|
options: import("@prisma/client/runtime/library.js").JsonValue | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worksheet.d.ts","sourceRoot":"/","sources":["models/worksheet.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;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,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;;;;;;;;;;;;;;;;;;;GAIA;AAED,kDAAkD;AAClD,wBAAgB,2BAA2B,CACzC,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,0BAA0B,EAAE,MAAM;;;;;;;;;;;;;;;;;;;GASnC;AAED,wDAAwD;AACxD,wBAAgB,uCAAuC,CACrD,EAAE,EAAE,MAAM,EACV,IAAI,EAAE;IACJ,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;;;;;;;;;;;;;;;;;;;GAMF;AAED,mDAAmD;AACnD,wBAAgB,uCAAuC,CAAC,IAAI,EAAE;IAC5D,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,0BAA0B,EAAE,MAAM,CAAC;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;;;;;;;;;;;;;;;;;;;GAIA;AAED,gDAAgD;AAChD,wBAAgB,aAAa,CAAC,IAAI,EAAE;IAClC,yBAAyB,EAAE,MAAM,CAAC;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;CAClB;;;;;;;;;;;;;;;;GAIA"}
|
package/dist/models/worksheet.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Worksheet model – worksheets, questions, submissions, student progress, grading.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
5
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ac1564ba-a589-57e4-8f58-f282c5648ea5")}catch(e){}}();
|
|
6
6
|
import { prisma } from "../lib/prisma.js";
|
|
7
7
|
const worksheetClassMemberWhere = (userId) => ({
|
|
8
8
|
class: {
|
|
@@ -363,4 +363,4 @@ export function createComment(data) {
|
|
|
363
363
|
});
|
|
364
364
|
}
|
|
365
365
|
//# sourceMappingURL=worksheet.js.map
|
|
366
|
-
//# debugId=
|
|
366
|
+
//# debugId=ac1564ba-a589-57e4-8f58-f282c5648ea5
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worksheet.js","sources":["models/worksheet.ts"],"sourceRoot":"/","sourcesContent":["/**\n * Worksheet model – worksheets, questions, submissions, student progress, grading.\n */\nimport { prisma } from \"../lib/prisma.js\";\nimport type { WorksheetQuestionType, GenerationStatus } from \"@prisma/client\";\n\nconst worksheetClassMemberWhere = (userId: string) => ({\n class: {\n OR: [\n { teachers: { some: { id: userId } } },\n { students: { some: { id: userId } } },\n ],\n },\n});\n\nconst worksheetTeacherWhere = (userId: string) => ({\n class: {\n teachers: { some: { id: userId } },\n },\n});\n\n/** @returns Worksheet with questions and class. */\nexport function findWorksheetById(id: string) {\n return prisma.worksheet.findUnique({\n where: { id },\n include: {\n questions: { orderBy: { createdAt: \"asc\" as const } },\n class: true,\n },\n });\n}\n\n/** @returns Worksheet by ID (minimal). */\nexport function findWorksheetByIdMinimal(id: string) {\n return prisma.worksheet.findUnique({\n where: { id },\n });\n}\n\n/** @returns Worksheet by ID for an authorized class member. */\nexport function findWorksheetByIdForClassMember(id: string, userId: string) {\n return prisma.worksheet.findFirst({\n where: {\n id,\n ...worksheetClassMemberWhere(userId),\n },\n include: {\n questions: { orderBy: { createdAt: \"asc\" as const } },\n class: true,\n },\n });\n}\n\n/** @returns Worksheet by ID for an authorized teacher. */\nexport function findWorksheetByIdForTeacher(id: string, userId: string) {\n return prisma.worksheet.findFirst({\n where: {\n id,\n ...worksheetTeacherWhere(userId),\n },\n include: {\n questions: { orderBy: { createdAt: \"asc\" as const } },\n class: true,\n },\n });\n}\n\n/** @returns Worksheets for a class. */\nexport function findWorksheetsByClassId(classId: string) {\n return prisma.worksheet.findMany({\n where: { classId },\n include: {\n questions: { select: { id: true } },\n },\n orderBy: { createdAt: \"desc\" },\n });\n}\n\n/** @returns Worksheet question by ID for an authorized teacher. */\nexport function findWorksheetQuestionByIdForTeacher(id: string, userId: string) {\n return prisma.worksheetQuestion.findFirst({\n where: {\n id,\n worksheet: worksheetTeacherWhere(userId),\n },\n });\n}\n\n/** @returns Worksheet question scoped to a worksheet. */\nexport function findWorksheetQuestionByIdInWorksheet(\n id: string,\n worksheetId: string\n) {\n return prisma.worksheetQuestion.findFirst({\n where: { id, worksheetId },\n });\n}\n\n/** Create a worksheet. */\nexport function createWorksheet(data: { classId: string; name: string }) {\n return prisma.worksheet.create({\n data,\n });\n}\n\n/** Update worksheet name. */\nexport function updateWorksheet(id: string, data: { name?: string }) {\n return prisma.worksheet.update({\n where: { id },\n data,\n });\n}\n\n/** Delete a worksheet. */\nexport function deleteWorksheet(id: string) {\n return prisma.worksheet.delete({\n where: { id },\n });\n}\n\n/** @returns Questions for a worksheet. */\nexport function findQuestionsByWorksheetId(worksheetId: string) {\n return prisma.worksheetQuestion.findMany({\n where: { worksheetId },\n orderBy: { order: \"asc\" },\n });\n}\n\n/** Create a worksheet question. */\nexport function createWorksheetQuestion(data: {\n worksheetId: string;\n type: WorksheetQuestionType;\n question: string;\n answer: string;\n points?: number;\n options?: object;\n markScheme?: object;\n}) {\n return prisma.worksheetQuestion.create({\n data,\n });\n}\n\n/** Update question order. */\nexport function updateWorksheetQuestionOrder(id: string, order: number) {\n return prisma.worksheetQuestion.update({\n where: { id },\n data: { order },\n });\n}\n\n/** Update a worksheet question. */\nexport function updateWorksheetQuestion(\n id: string,\n data: {\n question?: string;\n answer?: string;\n points?: number;\n options?: object;\n markScheme?: object;\n type?: WorksheetQuestionType;\n }\n) {\n return prisma.worksheetQuestion.update({\n where: { id },\n data,\n });\n}\n\n/** Delete a worksheet question. */\nexport function deleteWorksheetQuestion(id: string) {\n return prisma.worksheetQuestion.delete({\n where: { id },\n });\n}\n\n/** @returns Submission by ID. */\nexport function findSubmissionById(id: string) {\n return prisma.submission.findUnique({\n where: { id },\n });\n}\n\n/** @returns Submission if requester is the owning student or a class teacher for the worksheet. */\nexport function findSubmissionByIdForWorksheetAccess(\n id: string,\n worksheetId: string,\n worksheetClassId: string,\n userId: string\n) {\n return prisma.submission.findFirst({\n where: {\n id,\n assignment: {\n classId: worksheetClassId,\n worksheets: { some: { id: worksheetId } },\n },\n OR: [\n {\n studentId: userId,\n assignment: {\n class: {\n students: { some: { id: userId } },\n },\n },\n },\n {\n assignment: {\n class: {\n teachers: { some: { id: userId } },\n },\n },\n },\n ],\n },\n select: {\n id: true,\n studentId: true,\n },\n });\n}\n\nconst worksheetResponseInclude = {\n responses: {\n include: {\n comments: { select: { id: true } },\n },\n },\n};\n\n/** @returns Worksheet response for submission and worksheet. */\nexport function findWorksheetResponseBySubmissionAndWorksheet(\n submissionId: string,\n worksheetId: string\n) {\n return prisma.studentWorksheetResponse.findFirst({\n where: { submissionId, worksheetId },\n include: worksheetResponseInclude,\n });\n}\n\n/** Get or create worksheet response for student. */\nexport async function findOrCreateWorksheetResponse(\n submissionId: string,\n worksheetId: string,\n studentId: string\n) {\n return prisma.$transaction(async (tx) => {\n const existing = await tx.studentWorksheetResponse.findFirst({\n where: { submissionId, worksheetId },\n include: worksheetResponseInclude,\n });\n if (existing) return existing;\n return tx.studentWorksheetResponse.create({\n data: { worksheetId, submissionId, studentId },\n include: worksheetResponseInclude,\n });\n });\n}\n\n/** Create a worksheet response. */\nexport function createWorksheetResponse(data: {\n worksheetId: string;\n submissionId: string;\n studentId: string;\n}) {\n return prisma.studentWorksheetResponse.create({\n data,\n include: {\n responses: {\n include: {\n comments: { select: { id: true } },\n },\n },\n },\n });\n}\n\n/** @returns Worksheet response by ID. */\nexport function findWorksheetResponseById(id: string) {\n return prisma.studentWorksheetResponse.findUnique({\n where: { id },\n include: { responses: true },\n });\n}\n\n/** @returns Worksheet response if requester is the owning student. */\nexport function findWorksheetResponseByIdForStudent(id: string, userId: string) {\n return prisma.studentWorksheetResponse.findFirst({\n where: {\n id,\n studentId: userId,\n worksheet: worksheetClassMemberWhere(userId),\n },\n include: { responses: true, worksheet: true },\n });\n}\n\n/** @returns Worksheet response if requester is a class teacher. */\nexport function findWorksheetResponseByIdForTeacher(id: string, userId: string) {\n return prisma.studentWorksheetResponse.findFirst({\n where: {\n id,\n worksheet: worksheetTeacherWhere(userId),\n },\n include: { responses: true, worksheet: true },\n });\n}\n\n/** @returns Worksheet response with question responses. */\nexport function findWorksheetResponseWithResponses(\n id: string,\n questionId?: string\n) {\n return prisma.studentWorksheetResponse.findUnique({\n where: { id },\n include: {\n responses: questionId\n ? { where: { questionId } }\n : true,\n },\n });\n}\n\n/** @returns Worksheet response with scoped responses if requester is the owning student. */\nexport function findWorksheetResponseWithResponsesForStudent(\n id: string,\n userId: string,\n questionId?: string\n) {\n return prisma.studentWorksheetResponse.findFirst({\n where: {\n id,\n studentId: userId,\n worksheet: worksheetClassMemberWhere(userId),\n },\n include: {\n worksheet: true,\n responses: questionId ? { where: { questionId } } : true,\n },\n });\n}\n\n/** @returns Worksheet response with scoped responses if requester is a class teacher. */\nexport function findWorksheetResponseWithResponsesForTeacher(\n id: string,\n userId: string,\n questionId?: string\n) {\n return prisma.studentWorksheetResponse.findFirst({\n where: {\n id,\n worksheet: worksheetTeacherWhere(userId),\n },\n include: {\n worksheet: true,\n responses: questionId ? { where: { questionId } } : true,\n },\n });\n}\n\n/** @returns Worksheet question by ID. */\nexport function findWorksheetQuestionById(id: string) {\n return prisma.worksheetQuestion.findUnique({\n where: { id },\n });\n}\n\n/** @returns Student question progress if requester is a class teacher. */\nexport function findStudentQuestionProgressByIdForTeacher(\n id: string,\n userId: string\n) {\n return prisma.studentQuestionProgress.findFirst({\n where: {\n id,\n question: {\n worksheet: worksheetTeacherWhere(userId),\n },\n },\n include: {\n question: true,\n studentWorksheetResponse: true,\n },\n });\n}\n\n/** @returns Student question progress by id and worksheet response if requester is a class teacher. */\nexport function findStudentQuestionProgressByIdForTeacherAndResponse(\n id: string,\n studentWorksheetResponseId: string,\n userId: string\n) {\n return prisma.studentQuestionProgress.findFirst({\n where: {\n id,\n studentWorksheetResponseId,\n question: {\n worksheet: worksheetTeacherWhere(userId),\n },\n },\n include: {\n question: true,\n studentWorksheetResponse: true,\n },\n });\n}\n\n/** Update student's question progress. */\nexport function updateStudentQuestionProgress(\n id: string,\n data: {\n response?: string;\n isCorrect?: boolean;\n points?: number;\n status?: GenerationStatus;\n }\n) {\n return prisma.studentQuestionProgress.update({\n where: { id },\n data,\n });\n}\n\n/** Create student question progress. */\nexport function createStudentQuestionProgress(data: {\n studentId: string;\n questionId: string;\n studentWorksheetResponseId: string;\n response: string;\n isCorrect?: boolean;\n points?: number;\n}) {\n return prisma.studentQuestionProgress.create({\n data,\n });\n}\n\n/** @returns Student's progress for a question. */\nexport function findStudentQuestionProgress(\n studentId: string,\n questionId: string,\n studentWorksheetResponseId: string\n) {\n return prisma.studentQuestionProgress.findFirst({\n where: {\n studentId,\n questionId,\n studentWorksheetResponseId,\n },\n });\n}\n\n/** Update progress for grading (AI feedback, marks). */\nexport function updateStudentQuestionProgressForGrading(\n id: string,\n data: {\n isCorrect?: boolean;\n feedback?: string;\n markschemeState?: object;\n points?: number;\n response?: string;\n }\n) {\n return prisma.studentQuestionProgress.update({\n where: { id },\n data,\n });\n}\n\n/** Create progress record for grading pipeline. */\nexport function createStudentQuestionProgressForGrading(data: {\n studentId: string;\n questionId: string;\n studentWorksheetResponseId: string;\n response: string;\n isCorrect: boolean;\n feedback?: string;\n markschemeState?: object;\n points?: number;\n}) {\n return prisma.studentQuestionProgress.create({\n data,\n });\n}\n\n/** Create a comment on a worksheet response. */\nexport function createComment(data: {\n studentQuestionProgressId: string;\n content: string;\n authorId: string;\n}) {\n return prisma.comment.create({\n data,\n });\n}\n"],"names":[],"mappings":"AAAA;;GAEG;;;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAG1C,MAAM,yBAAyB,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,CAAC;IACrD,KAAK,EAAE;QACL,EAAE,EAAE;YACF,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE;YACtC,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE;SACvC;KACF;CACF,CAAC,CAAC;AAEH,MAAM,qBAAqB,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,CAAC;IACjD,KAAK,EAAE;QACL,QAAQ,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE;KACnC;CACF,CAAC,CAAC;AAEH,mDAAmD;AACnD,MAAM,UAAU,iBAAiB,CAAC,EAAU;IAC1C,OAAO,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC;QACjC,KAAK,EAAE,EAAE,EAAE,EAAE;QACb,OAAO,EAAE;YACP,SAAS,EAAE,EAAE,OAAO,EAAE,EAAE,SAAS,EAAE,KAAc,EAAE,EAAE;YACrD,KAAK,EAAE,IAAI;SACZ;KACF,CAAC,CAAC;AACL,CAAC;AAED,0CAA0C;AAC1C,MAAM,UAAU,wBAAwB,CAAC,EAAU;IACjD,OAAO,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC;QACjC,KAAK,EAAE,EAAE,EAA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,MAAM,UAAU,aAAa,CAAC,IAI7B;IACC,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;QAC3B,IAAI;KACL,CAAC,CAAC;AACL,CAAC","debug_id":"5edbab9e-02d0-5d22-a1f0-c2cfdcd85f9a"}
|
|
1
|
+
{"version":3,"file":"worksheet.js","sources":["models/worksheet.ts"],"sourceRoot":"/","sourcesContent":["/**\n * Worksheet model – worksheets, questions, submissions, student progress, grading.\n */\nimport { prisma } from \"../lib/prisma.js\";\nimport type { WorksheetQuestionType, GenerationStatus } from \"@prisma/client\";\n\nconst worksheetClassMemberWhere = (userId: string) => ({\n class: {\n OR: [\n { teachers: { some: { id: userId } } },\n { students: { some: { id: userId } } },\n ],\n },\n});\n\nconst worksheetTeacherWhere = (userId: string) => ({\n class: {\n teachers: { some: { id: userId } },\n },\n});\n\n/** @returns Worksheet with questions and class. */\nexport function findWorksheetById(id: string) {\n return prisma.worksheet.findUnique({\n where: { id },\n include: {\n questions: { orderBy: { createdAt: \"asc\" as const } },\n class: true,\n },\n });\n}\n\n/** @returns Worksheet by ID (minimal). */\nexport function findWorksheetByIdMinimal(id: string) {\n return prisma.worksheet.findUnique({\n where: { id },\n });\n}\n\n/** @returns Worksheet by ID for an authorized class member. */\nexport function findWorksheetByIdForClassMember(id: string, userId: string) {\n return prisma.worksheet.findFirst({\n where: {\n id,\n ...worksheetClassMemberWhere(userId),\n },\n include: {\n questions: { orderBy: { createdAt: \"asc\" as const } },\n class: true,\n },\n });\n}\n\n/** @returns Worksheet by ID for an authorized teacher. */\nexport function findWorksheetByIdForTeacher(id: string, userId: string) {\n return prisma.worksheet.findFirst({\n where: {\n id,\n ...worksheetTeacherWhere(userId),\n },\n include: {\n questions: { orderBy: { createdAt: \"asc\" as const } },\n class: true,\n },\n });\n}\n\n/** @returns Worksheets for a class. */\nexport function findWorksheetsByClassId(classId: string) {\n return prisma.worksheet.findMany({\n where: { classId },\n include: {\n questions: { select: { id: true } },\n },\n orderBy: { createdAt: \"desc\" },\n });\n}\n\n/** @returns Worksheet question by ID for an authorized teacher. */\nexport function findWorksheetQuestionByIdForTeacher(id: string, userId: string) {\n return prisma.worksheetQuestion.findFirst({\n where: {\n id,\n worksheet: worksheetTeacherWhere(userId),\n },\n });\n}\n\n/** @returns Worksheet question scoped to a worksheet. */\nexport function findWorksheetQuestionByIdInWorksheet(\n id: string,\n worksheetId: string\n) {\n return prisma.worksheetQuestion.findFirst({\n where: { id, worksheetId },\n });\n}\n\n/** Create a worksheet. */\nexport function createWorksheet(data: { classId: string; name: string }) {\n return prisma.worksheet.create({\n data,\n });\n}\n\n/** Update worksheet name. */\nexport function updateWorksheet(id: string, data: { name?: string }) {\n return prisma.worksheet.update({\n where: { id },\n data,\n });\n}\n\n/** Delete a worksheet. */\nexport function deleteWorksheet(id: string) {\n return prisma.worksheet.delete({\n where: { id },\n });\n}\n\n/** @returns Questions for a worksheet. */\nexport function findQuestionsByWorksheetId(worksheetId: string) {\n return prisma.worksheetQuestion.findMany({\n where: { worksheetId },\n orderBy: { order: \"asc\" },\n });\n}\n\n/** Create a worksheet question. */\nexport function createWorksheetQuestion(data: {\n worksheetId: string;\n type: WorksheetQuestionType;\n question: string;\n answer: string;\n points?: number;\n options?: object;\n markScheme?: object;\n order?: number;\n}) {\n return prisma.worksheetQuestion.create({\n data,\n });\n}\n\n/** Update question order. */\nexport function updateWorksheetQuestionOrder(id: string, order: number) {\n return prisma.worksheetQuestion.update({\n where: { id },\n data: { order },\n });\n}\n\n/** Update a worksheet question. */\nexport function updateWorksheetQuestion(\n id: string,\n data: {\n question?: string;\n answer?: string;\n points?: number;\n options?: object;\n markScheme?: object;\n type?: WorksheetQuestionType;\n }\n) {\n return prisma.worksheetQuestion.update({\n where: { id },\n data,\n });\n}\n\n/** Delete a worksheet question. */\nexport function deleteWorksheetQuestion(id: string) {\n return prisma.worksheetQuestion.delete({\n where: { id },\n });\n}\n\n/** @returns Submission by ID. */\nexport function findSubmissionById(id: string) {\n return prisma.submission.findUnique({\n where: { id },\n });\n}\n\n/** @returns Submission if requester is the owning student or a class teacher for the worksheet. */\nexport function findSubmissionByIdForWorksheetAccess(\n id: string,\n worksheetId: string,\n worksheetClassId: string,\n userId: string\n) {\n return prisma.submission.findFirst({\n where: {\n id,\n assignment: {\n classId: worksheetClassId,\n worksheets: { some: { id: worksheetId } },\n },\n OR: [\n {\n studentId: userId,\n assignment: {\n class: {\n students: { some: { id: userId } },\n },\n },\n },\n {\n assignment: {\n class: {\n teachers: { some: { id: userId } },\n },\n },\n },\n ],\n },\n select: {\n id: true,\n studentId: true,\n },\n });\n}\n\nconst worksheetResponseInclude = {\n responses: {\n include: {\n comments: { select: { id: true } },\n },\n },\n};\n\n/** @returns Worksheet response for submission and worksheet. */\nexport function findWorksheetResponseBySubmissionAndWorksheet(\n submissionId: string,\n worksheetId: string\n) {\n return prisma.studentWorksheetResponse.findFirst({\n where: { submissionId, worksheetId },\n include: worksheetResponseInclude,\n });\n}\n\n/** Get or create worksheet response for student. */\nexport async function findOrCreateWorksheetResponse(\n submissionId: string,\n worksheetId: string,\n studentId: string\n) {\n return prisma.$transaction(async (tx) => {\n const existing = await tx.studentWorksheetResponse.findFirst({\n where: { submissionId, worksheetId },\n include: worksheetResponseInclude,\n });\n if (existing) return existing;\n return tx.studentWorksheetResponse.create({\n data: { worksheetId, submissionId, studentId },\n include: worksheetResponseInclude,\n });\n });\n}\n\n/** Create a worksheet response. */\nexport function createWorksheetResponse(data: {\n worksheetId: string;\n submissionId: string;\n studentId: string;\n}) {\n return prisma.studentWorksheetResponse.create({\n data,\n include: {\n responses: {\n include: {\n comments: { select: { id: true } },\n },\n },\n },\n });\n}\n\n/** @returns Worksheet response by ID. */\nexport function findWorksheetResponseById(id: string) {\n return prisma.studentWorksheetResponse.findUnique({\n where: { id },\n include: { responses: true },\n });\n}\n\n/** @returns Worksheet response if requester is the owning student. */\nexport function findWorksheetResponseByIdForStudent(id: string, userId: string) {\n return prisma.studentWorksheetResponse.findFirst({\n where: {\n id,\n studentId: userId,\n worksheet: worksheetClassMemberWhere(userId),\n },\n include: { responses: true, worksheet: true },\n });\n}\n\n/** @returns Worksheet response if requester is a class teacher. */\nexport function findWorksheetResponseByIdForTeacher(id: string, userId: string) {\n return prisma.studentWorksheetResponse.findFirst({\n where: {\n id,\n worksheet: worksheetTeacherWhere(userId),\n },\n include: { responses: true, worksheet: true },\n });\n}\n\n/** @returns Worksheet response with question responses. */\nexport function findWorksheetResponseWithResponses(\n id: string,\n questionId?: string\n) {\n return prisma.studentWorksheetResponse.findUnique({\n where: { id },\n include: {\n responses: questionId\n ? { where: { questionId } }\n : true,\n },\n });\n}\n\n/** @returns Worksheet response with scoped responses if requester is the owning student. */\nexport function findWorksheetResponseWithResponsesForStudent(\n id: string,\n userId: string,\n questionId?: string\n) {\n return prisma.studentWorksheetResponse.findFirst({\n where: {\n id,\n studentId: userId,\n worksheet: worksheetClassMemberWhere(userId),\n },\n include: {\n worksheet: true,\n responses: questionId ? { where: { questionId } } : true,\n },\n });\n}\n\n/** @returns Worksheet response with scoped responses if requester is a class teacher. */\nexport function findWorksheetResponseWithResponsesForTeacher(\n id: string,\n userId: string,\n questionId?: string\n) {\n return prisma.studentWorksheetResponse.findFirst({\n where: {\n id,\n worksheet: worksheetTeacherWhere(userId),\n },\n include: {\n worksheet: true,\n responses: questionId ? { where: { questionId } } : true,\n },\n });\n}\n\n/** @returns Worksheet question by ID. */\nexport function findWorksheetQuestionById(id: string) {\n return prisma.worksheetQuestion.findUnique({\n where: { id },\n });\n}\n\n/** @returns Student question progress if requester is a class teacher. */\nexport function findStudentQuestionProgressByIdForTeacher(\n id: string,\n userId: string\n) {\n return prisma.studentQuestionProgress.findFirst({\n where: {\n id,\n question: {\n worksheet: worksheetTeacherWhere(userId),\n },\n },\n include: {\n question: true,\n studentWorksheetResponse: true,\n },\n });\n}\n\n/** @returns Student question progress by id and worksheet response if requester is a class teacher. */\nexport function findStudentQuestionProgressByIdForTeacherAndResponse(\n id: string,\n studentWorksheetResponseId: string,\n userId: string\n) {\n return prisma.studentQuestionProgress.findFirst({\n where: {\n id,\n studentWorksheetResponseId,\n question: {\n worksheet: worksheetTeacherWhere(userId),\n },\n },\n include: {\n question: true,\n studentWorksheetResponse: true,\n },\n });\n}\n\n/** Update student's question progress. */\nexport function updateStudentQuestionProgress(\n id: string,\n data: {\n response?: string;\n isCorrect?: boolean;\n points?: number;\n status?: GenerationStatus;\n }\n) {\n return prisma.studentQuestionProgress.update({\n where: { id },\n data,\n });\n}\n\n/** Create student question progress. */\nexport function createStudentQuestionProgress(data: {\n studentId: string;\n questionId: string;\n studentWorksheetResponseId: string;\n response: string;\n isCorrect?: boolean;\n points?: number;\n}) {\n return prisma.studentQuestionProgress.create({\n data,\n });\n}\n\n/** @returns Student's progress for a question. */\nexport function findStudentQuestionProgress(\n studentId: string,\n questionId: string,\n studentWorksheetResponseId: string\n) {\n return prisma.studentQuestionProgress.findFirst({\n where: {\n studentId,\n questionId,\n studentWorksheetResponseId,\n },\n });\n}\n\n/** Update progress for grading (AI feedback, marks). */\nexport function updateStudentQuestionProgressForGrading(\n id: string,\n data: {\n isCorrect?: boolean;\n feedback?: string;\n markschemeState?: object;\n points?: number;\n response?: string;\n }\n) {\n return prisma.studentQuestionProgress.update({\n where: { id },\n data,\n });\n}\n\n/** Create progress record for grading pipeline. */\nexport function createStudentQuestionProgressForGrading(data: {\n studentId: string;\n questionId: string;\n studentWorksheetResponseId: string;\n response: string;\n isCorrect: boolean;\n feedback?: string;\n markschemeState?: object;\n points?: number;\n}) {\n return prisma.studentQuestionProgress.create({\n data,\n });\n}\n\n/** Create a comment on a worksheet response. */\nexport function createComment(data: {\n studentQuestionProgressId: string;\n content: string;\n authorId: string;\n}) {\n return prisma.comment.create({\n data,\n });\n}\n"],"names":[],"mappings":"AAAA;;GAEG;;;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAG1C,MAAM,yBAAyB,GAAG,CAAC,MAAc,EAAE,EAAE,CAA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O,MAAM,CAAC,uBAAuB,CAAC,MAAM,CAAC;QAC3C,KAAK,EAAE,EAAE,EAAE,EAAE;QACb,IAAI;KACL,CAAC,CAAC;AACL,CAAC;AAED,wCAAwC;AACxC,MAAM,UAAU,6BAA6B,CAAC,IAO7C;IACC,OAAO,MAAM,CAAC,uBAAuB,CAAC,MAAM,CAAC;QAC3C,IAAI;KACL,CAAC,CAAC;AACL,CAAC;AAED,kDAAkD;AAClD,MAAM,UAAU,2BAA2B,CACzC,SAAiB,EACjB,UAAkB,EAClB,0BAAkC;IAElC,OAAO,MAAM,CAAC,uBAAuB,CAAC,SAAS,CAAC;QAC9C,KAAK,EAAE;YACL,SAAS;YACT,UAAU;YACV,0BAA0B;SAC3B;KACF,CAAC,CAAC;AACL,CAAC;AAED,wDAAwD;AACxD,MAAM,UAAU,uCAAuC,CACrD,EAAU,EACV,IAMC;IAED,OAAO,MAAM,CAAC,uBAAuB,CAAC,MAAM,CAAC;QAC3C,KAAK,EAAE,EAAE,EAAE,EAAE;QACb,IAAI;KACL,CAAC,CAAC;AACL,CAAC;AAED,mDAAmD;AACnD,MAAM,UAAU,uCAAuC,CAAC,IASvD;IACC,OAAO,MAAM,CAAC,uBAAuB,CAAC,MAAM,CAAC;QAC3C,IAAI;KACL,CAAC,CAAC;AACL,CAAC;AAED,gDAAgD;AAChD,MAAM,UAAU,aAAa,CAAC,IAI7B;IACC,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;QAC3B,IAAI;KACL,CAAC,CAAC;AACL,CAAC","debug_id":"ac1564ba-a589-57e4-8f58-f282c5648ea5"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sends a PDF URL to the model for remote retrieval, extracts a worksheet via
|
|
3
|
+
* structured inference, and inserts worksheet + questions in one DB transaction.
|
|
4
|
+
*/
|
|
5
|
+
export declare function pdfToWorksheet(gcsUrl: string, classId: string): Promise<{
|
|
6
|
+
name: string;
|
|
7
|
+
id: string;
|
|
8
|
+
createdAt: Date;
|
|
9
|
+
classId: string;
|
|
10
|
+
updatedAt: Date;
|
|
11
|
+
} | null>;
|
|
12
|
+
//# sourceMappingURL=pdfToWorksheet.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pdfToWorksheet.d.ts","sourceRoot":"/","sources":["pipelines/pdfToWorksheet.ts"],"names":[],"mappings":"AA0GA;;;GAGG;AACH,wBAAsB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;;;;;;UAkEnE"}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PDF URL → worksheet: send a remote PDF URL to structured inference,
|
|
3
|
+
* then persist a Worksheet and WorksheetQuestion rows.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ea4c1689-45bc-59df-b76c-6c749341cffe")}catch(e){}}();
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { prisma } from "../lib/prisma.js";
|
|
9
|
+
import { inference } from "../utils/inference.js";
|
|
10
|
+
import { logger } from "../utils/logger.js";
|
|
11
|
+
/** Restrict remote fetches to Google-hosted object URLs. */
|
|
12
|
+
function isProbablyGoogleCloudUrl(url) {
|
|
13
|
+
try {
|
|
14
|
+
const host = new URL(url).hostname;
|
|
15
|
+
return (host.endsWith("storage.googleapis.com") ||
|
|
16
|
+
host.endsWith("googleusercontent.com") ||
|
|
17
|
+
host.includes("storage.cloud.google.com"));
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function getFilenameFromUrl(url) {
|
|
24
|
+
try {
|
|
25
|
+
const parsed = new URL(url);
|
|
26
|
+
const lastSegment = parsed.pathname.split("/").filter(Boolean).pop();
|
|
27
|
+
return lastSegment && lastSegment.includes(".") ? lastSegment : "document.pdf";
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return "document.pdf";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function sanitizeUrlForLogs(url) {
|
|
34
|
+
try {
|
|
35
|
+
const parsed = new URL(url);
|
|
36
|
+
return `${parsed.origin}${parsed.pathname}`;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return 'invalid-url';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** LLM output shape (validated by inference). */
|
|
43
|
+
const worksheetDraftSchema = z.object({
|
|
44
|
+
title: z.string(),
|
|
45
|
+
questions: z
|
|
46
|
+
.array(z.object({
|
|
47
|
+
type: z.enum([
|
|
48
|
+
"MULTIPLE_CHOICE",
|
|
49
|
+
"TRUE_FALSE",
|
|
50
|
+
"SHORT_ANSWER",
|
|
51
|
+
"LONG_ANSWER",
|
|
52
|
+
"MATH_EXPRESSION",
|
|
53
|
+
"ESSAY",
|
|
54
|
+
]),
|
|
55
|
+
question: z.string(),
|
|
56
|
+
answer: z.string(),
|
|
57
|
+
options: z
|
|
58
|
+
.array(z.object({
|
|
59
|
+
id: z.string(),
|
|
60
|
+
text: z.string(),
|
|
61
|
+
isCorrect: z.boolean(),
|
|
62
|
+
}))
|
|
63
|
+
.optional()
|
|
64
|
+
.default([]),
|
|
65
|
+
markScheme: z
|
|
66
|
+
.array(z.object({
|
|
67
|
+
id: z.string(),
|
|
68
|
+
points: z.number().transform((value) => Math.round(value)),
|
|
69
|
+
description: z.string(),
|
|
70
|
+
}))
|
|
71
|
+
.optional()
|
|
72
|
+
.default([]),
|
|
73
|
+
points: z.number().optional().default(0),
|
|
74
|
+
order: z.number().transform((value) => Math.round(value)),
|
|
75
|
+
}))
|
|
76
|
+
.default([]),
|
|
77
|
+
});
|
|
78
|
+
const schemaInstructions = `Return ONLY valid JSON matching this schema:
|
|
79
|
+
{
|
|
80
|
+
"title": string,
|
|
81
|
+
"questions": [
|
|
82
|
+
{
|
|
83
|
+
"type": "MULTIPLE_CHOICE" | "TRUE_FALSE" | "SHORT_ANSWER" | "LONG_ANSWER" | "MATH_EXPRESSION" | "ESSAY",
|
|
84
|
+
"question": string,
|
|
85
|
+
"answer": string,
|
|
86
|
+
"options": [ { "id": string, "text": string, "isCorrect": boolean } ],
|
|
87
|
+
"markScheme": [ { "id": string, "points": number, "description": string } ],
|
|
88
|
+
"points": number,
|
|
89
|
+
"order": number
|
|
90
|
+
}
|
|
91
|
+
]
|
|
92
|
+
}
|
|
93
|
+
Rules: "questions" is an array ([] if none). Non-MCQ "options" can be []. Use "order" 1,2,3,… in reading order. No markdown or extra keys.
|
|
94
|
+
If no answer is provided for a multiple-choice or true/false question, determine the answer from the options.`;
|
|
95
|
+
/**
|
|
96
|
+
* Sends a PDF URL to the model for remote retrieval, extracts a worksheet via
|
|
97
|
+
* structured inference, and inserts worksheet + questions in one DB transaction.
|
|
98
|
+
*/
|
|
99
|
+
export async function pdfToWorksheet(gcsUrl, classId) {
|
|
100
|
+
const sanitizedUrl = sanitizeUrlForLogs(gcsUrl);
|
|
101
|
+
if (!isProbablyGoogleCloudUrl(gcsUrl)) {
|
|
102
|
+
logger.warn("pdfToWorksheet: rejected unsupported PDF URL", {
|
|
103
|
+
sanitizedUrl,
|
|
104
|
+
});
|
|
105
|
+
throw new Error("Only Google Cloud Storage URLs are supported");
|
|
106
|
+
}
|
|
107
|
+
const filename = getFilenameFromUrl(gcsUrl);
|
|
108
|
+
const prompt = `Read the attached PDF and convert it into a single worksheet JSON object.\n\n${schemaInstructions}`;
|
|
109
|
+
// Force Responses API input types so we can pass a remote PDF via `file_url`.
|
|
110
|
+
const input = [
|
|
111
|
+
{
|
|
112
|
+
role: "user",
|
|
113
|
+
content: [
|
|
114
|
+
{ type: "input_text", text: prompt },
|
|
115
|
+
{ type: "input_file", file_url: gcsUrl },
|
|
116
|
+
],
|
|
117
|
+
},
|
|
118
|
+
];
|
|
119
|
+
const draft = await inference(input, worksheetDraftSchema, {
|
|
120
|
+
reason: 'pdf_to_worksheet_draft',
|
|
121
|
+
metadata: {
|
|
122
|
+
classId,
|
|
123
|
+
filename,
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
if (!draft) {
|
|
127
|
+
logger.warn("pdfToWorksheet: no model output", { filename });
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
return prisma.$transaction(async (tx) => {
|
|
131
|
+
const worksheet = await tx.worksheet.create({
|
|
132
|
+
data: { classId, name: draft.title },
|
|
133
|
+
});
|
|
134
|
+
if (draft.questions.length > 0) {
|
|
135
|
+
await tx.worksheetQuestion.createMany({
|
|
136
|
+
data: draft.questions.map((question) => ({
|
|
137
|
+
worksheetId: worksheet.id,
|
|
138
|
+
type: question.type,
|
|
139
|
+
question: question.question,
|
|
140
|
+
answer: question.answer,
|
|
141
|
+
points: Math.round(question.points ?? 0),
|
|
142
|
+
options: question.options ?? [],
|
|
143
|
+
markScheme: (question.markScheme ?? []).map((item) => ({
|
|
144
|
+
...item,
|
|
145
|
+
points: Math.round(item.points),
|
|
146
|
+
})),
|
|
147
|
+
order: Math.round(question.order),
|
|
148
|
+
})),
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
return worksheet;
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
//# sourceMappingURL=pdfToWorksheet.js.map
|
|
155
|
+
//# debugId=ea4c1689-45bc-59df-b76c-6c749341cffe
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pdfToWorksheet.js","sources":["pipelines/pdfToWorksheet.ts"],"sourceRoot":"/","sourcesContent":["/**\n * PDF URL → worksheet: send a remote PDF URL to structured inference,\n * then persist a Worksheet and WorksheetQuestion rows.\n */\nimport { z } from \"zod\";\nimport type { ResponseInput } from \"openai/resources/responses/responses.js\";\nimport { prisma } from \"../lib/prisma.js\";\nimport { inference } from \"../utils/inference.js\";\nimport { logger } from \"../utils/logger.js\";\n\n/** Restrict remote fetches to Google-hosted object URLs. */\nfunction isProbablyGoogleCloudUrl(url: string): boolean {\n try {\n const host = new URL(url).hostname;\n return (\n host.endsWith(\"storage.googleapis.com\") ||\n host.endsWith(\"googleusercontent.com\") ||\n host.includes(\"storage.cloud.google.com\")\n );\n } catch {\n return false;\n }\n}\n\nfunction getFilenameFromUrl(url: string): string {\n try {\n const parsed = new URL(url);\n const lastSegment = parsed.pathname.split(\"/\").filter(Boolean).pop();\n return lastSegment && lastSegment.includes(\".\") ? lastSegment : \"document.pdf\";\n } catch {\n return \"document.pdf\";\n }\n}\n\nfunction sanitizeUrlForLogs(url: string): string {\n try {\n const parsed = new URL(url);\n return `${parsed.origin}${parsed.pathname}`;\n } catch {\n return 'invalid-url';\n }\n}\n\n/** LLM output shape (validated by inference). */\nconst worksheetDraftSchema = z.object({\n title: z.string(),\n questions: z\n .array(\n z.object({\n type: z.enum([\n \"MULTIPLE_CHOICE\",\n \"TRUE_FALSE\",\n \"SHORT_ANSWER\",\n \"LONG_ANSWER\",\n \"MATH_EXPRESSION\",\n \"ESSAY\",\n ]),\n question: z.string(),\n answer: z.string(),\n options: z\n .array(\n z.object({\n id: z.string(),\n text: z.string(),\n isCorrect: z.boolean(),\n })\n )\n .optional()\n .default([]),\n markScheme: z\n .array(\n z.object({\n id: z.string(),\n points: z.number().transform((value) => Math.round(value)),\n description: z.string(),\n })\n )\n .optional()\n .default([]),\n points: z.number().optional().default(0),\n order: z.number().transform((value) => Math.round(value)),\n })\n )\n .default([]),\n});\n\ntype WorksheetDraft = z.infer<typeof worksheetDraftSchema>;\n\nconst schemaInstructions = `Return ONLY valid JSON matching this schema:\n{\n \"title\": string,\n \"questions\": [\n {\n \"type\": \"MULTIPLE_CHOICE\" | \"TRUE_FALSE\" | \"SHORT_ANSWER\" | \"LONG_ANSWER\" | \"MATH_EXPRESSION\" | \"ESSAY\",\n \"question\": string,\n \"answer\": string,\n \"options\": [ { \"id\": string, \"text\": string, \"isCorrect\": boolean } ],\n \"markScheme\": [ { \"id\": string, \"points\": number, \"description\": string } ],\n \"points\": number,\n \"order\": number\n }\n ]\n}\nRules: \"questions\" is an array ([] if none). Non-MCQ \"options\" can be []. Use \"order\" 1,2,3,… in reading order. No markdown or extra keys.\nIf no answer is provided for a multiple-choice or true/false question, determine the answer from the options.`;\n\n/**\n * Sends a PDF URL to the model for remote retrieval, extracts a worksheet via\n * structured inference, and inserts worksheet + questions in one DB transaction.\n */\nexport async function pdfToWorksheet(gcsUrl: string, classId: string) {\n const sanitizedUrl = sanitizeUrlForLogs(gcsUrl);\n\n if (!isProbablyGoogleCloudUrl(gcsUrl)) {\n logger.warn(\"pdfToWorksheet: rejected unsupported PDF URL\", {\n sanitizedUrl,\n });\n throw new Error(\"Only Google Cloud Storage URLs are supported\");\n }\n\n const filename = getFilenameFromUrl(gcsUrl);\n const prompt = `Read the attached PDF and convert it into a single worksheet JSON object.\\n\\n${schemaInstructions}`;\n\n // Force Responses API input types so we can pass a remote PDF via `file_url`.\n const input: ResponseInput = [\n {\n role: \"user\",\n content: [\n { type: \"input_text\", text: prompt },\n { type: \"input_file\", file_url: gcsUrl },\n ],\n },\n ];\n\n const draft = await inference<WorksheetDraft>(\n input,\n worksheetDraftSchema,\n {\n reason: 'pdf_to_worksheet_draft',\n metadata: {\n classId,\n filename,\n },\n }\n );\n\n if (!draft) {\n logger.warn(\"pdfToWorksheet: no model output\", { filename });\n return null;\n }\n\n return prisma.$transaction(async (tx) => {\n const worksheet = await tx.worksheet.create({\n data: { classId, name: draft.title },\n });\n\n if (draft.questions.length > 0) {\n await tx.worksheetQuestion.createMany({\n data: draft.questions.map((question) => ({\n worksheetId: worksheet.id,\n type: question.type,\n question: question.question,\n answer: question.answer,\n points: Math.round(question.points ?? 0),\n options: question.options ?? [],\n markScheme: (question.markScheme ?? []).map((item) => ({\n ...item,\n points: Math.round(item.points),\n })),\n order: Math.round(question.order),\n })),\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