@studious-lms/server 1.16.0 → 1.16.1

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.
Files changed (151) hide show
  1. package/.github/workflows/deploy.yml +1 -1
  2. package/dist/instrument.js +3 -3
  3. package/dist/instrument.js.map +1 -1
  4. package/dist/lib/chatAttachmentPrompt.d.ts +47 -0
  5. package/dist/lib/chatAttachmentPrompt.d.ts.map +1 -0
  6. package/dist/lib/chatAttachmentPrompt.js +190 -0
  7. package/dist/lib/chatAttachmentPrompt.js.map +1 -0
  8. package/dist/lib/inferDocumentFormat.js +3 -3
  9. package/dist/lib/inferDocumentFormat.js.map +1 -1
  10. package/dist/lib/legal.d.ts +3 -0
  11. package/dist/lib/legal.d.ts.map +1 -0
  12. package/dist/lib/legal.js +6 -0
  13. package/dist/lib/legal.js.map +1 -0
  14. package/dist/models/announcement.d.ts +2 -0
  15. package/dist/models/announcement.d.ts.map +1 -1
  16. package/dist/models/auth.d.ts +8 -0
  17. package/dist/models/auth.d.ts.map +1 -1
  18. package/dist/models/auth.js +4 -2
  19. package/dist/models/auth.js.map +1 -1
  20. package/dist/models/event.d.ts +2 -0
  21. package/dist/models/event.d.ts.map +1 -1
  22. package/dist/models/file.d.ts +24 -0
  23. package/dist/models/file.d.ts.map +1 -1
  24. package/dist/models/marketing.d.ts +2 -15
  25. package/dist/models/marketing.d.ts.map +1 -1
  26. package/dist/models/marketing.js +12 -4
  27. package/dist/models/marketing.js.map +1 -1
  28. package/dist/pipelines/aiLabChat.d.ts.map +1 -1
  29. package/dist/pipelines/aiLabChat.js +39 -59
  30. package/dist/pipelines/aiLabChat.js.map +1 -1
  31. package/dist/pipelines/aiLabChatContract.d.ts +2 -2
  32. package/dist/pipelines/aiNewtonChat.d.ts +1 -1
  33. package/dist/pipelines/aiNewtonChat.d.ts.map +1 -1
  34. package/dist/pipelines/aiNewtonChat.js +20 -19
  35. package/dist/pipelines/aiNewtonChat.js.map +1 -1
  36. package/dist/pipelines/gradeWorksheet.d.ts +1 -0
  37. package/dist/pipelines/gradeWorksheet.d.ts.map +1 -1
  38. package/dist/pipelines/gradeWorksheet.js +84 -13
  39. package/dist/pipelines/gradeWorksheet.js.map +1 -1
  40. package/dist/pipelines/labChatPrompt.d.ts +4 -20
  41. package/dist/pipelines/labChatPrompt.d.ts.map +1 -1
  42. package/dist/pipelines/labChatPrompt.js +24 -64
  43. package/dist/pipelines/labChatPrompt.js.map +1 -1
  44. package/dist/routers/_app.d.ts +236 -26
  45. package/dist/routers/_app.d.ts.map +1 -1
  46. package/dist/routers/assignment.d.ts +10 -0
  47. package/dist/routers/assignment.d.ts.map +1 -1
  48. package/dist/routers/auth.d.ts +2 -0
  49. package/dist/routers/auth.d.ts.map +1 -1
  50. package/dist/routers/auth.js +15 -2
  51. package/dist/routers/auth.js.map +1 -1
  52. package/dist/routers/class.d.ts +4 -0
  53. package/dist/routers/class.d.ts.map +1 -1
  54. package/dist/routers/event.d.ts +2 -0
  55. package/dist/routers/event.d.ts.map +1 -1
  56. package/dist/routers/marketing.d.ts +0 -13
  57. package/dist/routers/marketing.d.ts.map +1 -1
  58. package/dist/routers/school.d.ts +4 -0
  59. package/dist/routers/school.d.ts.map +1 -1
  60. package/dist/routers/user.d.ts +89 -0
  61. package/dist/routers/user.d.ts.map +1 -1
  62. package/dist/routers/user.js +19 -2
  63. package/dist/routers/user.js.map +1 -1
  64. package/dist/routers/worksheet.d.ts +7 -0
  65. package/dist/routers/worksheet.d.ts.map +1 -1
  66. package/dist/routers/worksheet.js +8 -3
  67. package/dist/routers/worksheet.js.map +1 -1
  68. package/dist/seedDatabase.d.ts +2 -0
  69. package/dist/seedDatabase.d.ts.map +1 -1
  70. package/dist/services/aiChatStream.d.ts +2 -0
  71. package/dist/services/aiChatStream.d.ts.map +1 -1
  72. package/dist/services/aiChatStream.js +31 -4
  73. package/dist/services/aiChatStream.js.map +1 -1
  74. package/dist/services/aiProposalTools.d.ts.map +1 -1
  75. package/dist/services/aiProposalTools.js +9 -9
  76. package/dist/services/aiProposalTools.js.map +1 -1
  77. package/dist/services/aiTools.js +3 -3
  78. package/dist/services/aiTools.js.map +1 -1
  79. package/dist/services/assignment.d.ts +10 -0
  80. package/dist/services/assignment.d.ts.map +1 -1
  81. package/dist/services/auth.d.ts +2 -0
  82. package/dist/services/auth.d.ts.map +1 -1
  83. package/dist/services/auth.js +13 -4
  84. package/dist/services/auth.js.map +1 -1
  85. package/dist/services/class.d.ts +4 -0
  86. package/dist/services/class.d.ts.map +1 -1
  87. package/dist/services/event.d.ts +2 -0
  88. package/dist/services/event.d.ts.map +1 -1
  89. package/dist/services/marketing.d.ts +1 -14
  90. package/dist/services/marketing.d.ts.map +1 -1
  91. package/dist/services/marketing.js +5 -5
  92. package/dist/services/marketing.js.map +1 -1
  93. package/dist/services/newtonChat.d.ts.map +1 -1
  94. package/dist/services/newtonChat.js +2 -8
  95. package/dist/services/newtonChat.js.map +1 -1
  96. package/dist/services/openaiDocumentGen.d.ts +12 -0
  97. package/dist/services/openaiDocumentGen.d.ts.map +1 -1
  98. package/dist/services/openaiDocumentGen.js +173 -65
  99. package/dist/services/openaiDocumentGen.js.map +1 -1
  100. package/dist/services/school.d.ts +4 -0
  101. package/dist/services/school.d.ts.map +1 -1
  102. package/dist/services/userPrivacy.d.ts +86 -0
  103. package/dist/services/userPrivacy.d.ts.map +1 -0
  104. package/dist/services/userPrivacy.js +184 -0
  105. package/dist/services/userPrivacy.js.map +1 -0
  106. package/dist/services/worksheet.d.ts +1 -0
  107. package/dist/services/worksheet.d.ts.map +1 -1
  108. package/dist/services/worksheet.js +13 -3
  109. package/dist/services/worksheet.js.map +1 -1
  110. package/dist/utils/email.d.ts.map +1 -1
  111. package/dist/utils/email.js +7 -3
  112. package/dist/utils/email.js.map +1 -1
  113. package/dist/workers/processors/aiNewtonChat.d.ts.map +1 -1
  114. package/dist/workers/processors/aiNewtonChat.js +3 -3
  115. package/dist/workers/processors/aiNewtonChat.js.map +1 -1
  116. package/package.json +2 -1
  117. package/prisma/migrations/20260611120000_add_user_terms_acceptance/migration.sql +3 -0
  118. package/prisma/schema.prisma +3 -0
  119. package/src/instrument.ts +1 -1
  120. package/src/lib/chatAttachmentPrompt.ts +270 -0
  121. package/src/lib/inferDocumentFormat.ts +1 -1
  122. package/src/lib/legal.ts +2 -0
  123. package/src/models/auth.ts +4 -0
  124. package/src/models/marketing.ts +10 -2
  125. package/src/pipelines/aiLabChat.ts +46 -71
  126. package/src/pipelines/aiNewtonChat.ts +20 -23
  127. package/src/pipelines/gradeWorksheet.ts +87 -11
  128. package/src/pipelines/labChatPrompt.ts +29 -98
  129. package/src/routers/auth.ts +13 -0
  130. package/src/routers/user.ts +26 -0
  131. package/src/routers/worksheet.ts +11 -0
  132. package/src/services/aiChatStream.ts +30 -3
  133. package/src/services/aiProposalTools.ts +8 -7
  134. package/src/services/aiTools.ts +1 -1
  135. package/src/services/auth.ts +14 -2
  136. package/src/services/marketing.ts +3 -3
  137. package/src/services/newtonChat.ts +0 -7
  138. package/src/services/openaiDocumentGen.ts +190 -66
  139. package/src/services/userPrivacy.ts +196 -0
  140. package/src/services/worksheet.ts +20 -1
  141. package/src/utils/email.ts +5 -1
  142. package/src/workers/processors/aiNewtonChat.ts +0 -1
  143. package/tests/helpers/registerInput.ts +20 -0
  144. package/tests/integration/globalSetup.ts +10 -18
  145. package/tests/integration/routers/auth.test.ts +13 -18
  146. package/tests/integration/routers/newtonChat.test.ts +9 -8
  147. package/tests/unit/lib/chatAttachmentPrompt.test.ts +135 -0
  148. package/tests/unit/lib/inferDocumentFormat.test.ts +10 -0
  149. package/tests/unit/pipelines/labChatPrompt.test.ts +6 -6
  150. package/tests/unit/services/aiChatStream.test.ts +92 -0
  151. package/tests/unit/services/openaiDocumentGen.test.ts +65 -0
@@ -3,14 +3,38 @@
3
3
  * Supports every format the sandbox can produce (pdf, docx, xlsx, pptx, …).
4
4
  */
5
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]="cd65973d-ca13-5498-8d6b-ff056b093631")}catch(e){}}();
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]="d086b281-e191-5157-a799-843675a76a37")}catch(e){}}();
7
7
  import OpenAI from 'openai';
8
8
  import { logger } from '../utils/logger.js';
9
- const DOCUMENT_GEN_MODEL = 'gpt-4o-mini';
9
+ const DOCUMENT_GEN_MODEL = 'gpt-5.5';
10
+ /**
11
+ * Extensions OpenAI Code Interpreter can read/write in its sandbox.
12
+ * @see https://developers.openai.com/api/docs/guides/tools-code-interpreter
13
+ */
10
14
  export const SUPPORTED_DOCUMENT_FORMATS = [
11
- 'pdf', 'docx', 'doc', 'xlsx', 'pptx', 'csv', 'md', 'html', 'txt', 'json',
12
- 'xml', 'tex', 'png', 'jpeg', 'jpg', 'gif', 'zip', 'tar', 'py', 'js', 'ts',
13
- 'css', 'sh',
15
+ 'pdf',
16
+ 'docx',
17
+ 'doc',
18
+ 'xlsx',
19
+ 'pptx',
20
+ 'csv',
21
+ 'md',
22
+ 'html',
23
+ 'txt',
24
+ 'json',
25
+ 'xml',
26
+ 'tex',
27
+ 'png',
28
+ 'jpeg',
29
+ 'jpg',
30
+ 'gif',
31
+ 'zip',
32
+ 'tar',
33
+ 'py',
34
+ 'js',
35
+ 'ts',
36
+ 'css',
37
+ 'sh',
14
38
  ];
15
39
  const FORMAT_MIME = {
16
40
  pdf: 'application/pdf',
@@ -38,29 +62,67 @@ const FORMAT_MIME = {
38
62
  sh: 'application/x-sh',
39
63
  };
40
64
  const FORMAT_HINTS = {
41
- pdf: 'fpdf2 or reportlab',
42
- docx: 'python-docx',
43
- doc: 'python-docx',
44
- xlsx: 'openpyxl or pandas',
45
- pptx: 'python-pptx',
46
- csv: 'pandas or csv module',
47
- md: 'write markdown directly',
48
- html: 'write a complete HTML page',
49
- txt: 'write plain text',
50
- json: 'json.dumps with indentation',
51
- xml: 'well-formed XML',
52
- tex: 'LaTeX source',
53
- png: 'matplotlib or Pillow',
54
- jpeg: 'matplotlib or Pillow',
55
- jpg: 'matplotlib or Pillow',
56
- gif: 'matplotlib or Pillow',
57
- zip: 'zipfile',
58
- tar: 'tarfile',
59
- py: 'Python source',
60
- js: 'JavaScript source',
61
- ts: 'TypeScript source',
62
- css: 'CSS stylesheet',
63
- sh: 'shell script',
65
+ pdf: 'fpdf2 or reportlab — polished document with headings, body text, and tables',
66
+ docx: 'python-docx — Word document with heading styles, paragraphs, and lists',
67
+ doc: 'python-docx saving as .doc if supported, otherwise .docx',
68
+ xlsx: 'openpyxl or pandas — spreadsheet with labelled columns, formulas where useful',
69
+ pptx: 'python-pptx — full slide deck: title slide, section slides, bullets, diagrams on slides',
70
+ csv: 'pandas or csv module — tabular data with headers',
71
+ md: 'write the markdown file directly',
72
+ html: 'write a complete, styled HTML page',
73
+ txt: 'write plain text with clear section breaks',
74
+ json: 'json.dumps with readable indentation',
75
+ xml: 'well-formed XML document',
76
+ tex: 'LaTeX source that compiles to the requested content',
77
+ png: 'matplotlib, networkx, or Pillow — render the described chart/diagram as a finished image',
78
+ jpeg: 'matplotlib or Pillow — high-quality visual saved as JPEG',
79
+ jpg: 'matplotlib or Pillow — high-quality visual saved as JPEG',
80
+ gif: 'matplotlib or Pillow — save as GIF',
81
+ zip: 'zipfile — bundle multiple related files if needed',
82
+ tar: 'tarfile — archive if multiple files are required',
83
+ py: 'valid, runnable Python source with comments',
84
+ js: 'valid JavaScript source with comments',
85
+ ts: 'valid TypeScript source with comments',
86
+ css: 'stylesheet file',
87
+ sh: 'shell script file',
88
+ };
89
+ /** Extra quality rules appended for formats that need more than a one-line library hint. */
90
+ const FORMAT_QUALITY_RULES = {
91
+ png: [
92
+ 'Interpret the source content as a visual spec — draw it, do not dump text into the image.',
93
+ 'Charts: labelled axes, legend, title, readable font sizes, 150+ DPI.',
94
+ 'Diagrams/flowcharts: use matplotlib patches, networkx, or Pillow drawing — boxes, arrows, labels.',
95
+ 'Geometry/maps: accurate relative positions; label every important part.',
96
+ 'Use color meaningfully; avoid blank or placeholder images.',
97
+ ],
98
+ jpeg: [
99
+ 'Same visual quality rules as PNG — polished chart or diagram, not a screenshot of text.',
100
+ ],
101
+ jpg: [
102
+ 'Same visual quality rules as PNG — polished chart or diagram, not a screenshot of text.',
103
+ ],
104
+ gif: [
105
+ 'Render a clear educational visual; static GIF is fine unless animation is described.',
106
+ ],
107
+ pptx: [
108
+ 'Split slides on "---" lines or "Slide N:" / "# " headings in the source content.',
109
+ 'Title slide first, then content slides with concise bullets (not walls of text).',
110
+ 'If the content describes a diagram, draw it on a slide (shapes/arrows) or embed a generated chart.',
111
+ 'Use distinct slide layouts where appropriate (title, title+content).',
112
+ ],
113
+ xlsx: [
114
+ 'Parse markdown tables or tabular lists in the source into real rows/columns.',
115
+ 'Bold header row; auto-fit column widths where possible.',
116
+ ],
117
+ pdf: [
118
+ 'If the source describes a figure/chart, generate and embed it — do not leave a "[diagram]" placeholder.',
119
+ ],
120
+ docx: [
121
+ 'Use Heading 1/2 styles for section titles; bullets and numbered lists for enumerations.',
122
+ ],
123
+ html: [
124
+ 'Include embedded CSS for readable typography; use tables or simple layout for structured content.',
125
+ ],
64
126
  };
65
127
  export function normalizeDocumentFormat(format) {
66
128
  const raw = (format ?? 'pdf').toLowerCase().replace(/^\./, '');
@@ -72,10 +134,21 @@ export function normalizeDocumentFormat(format) {
72
134
  export function mimeTypeForFormat(format) {
73
135
  return FORMAT_MIME[format];
74
136
  }
137
+ export function extensionForFormat(format) {
138
+ return format === 'jpg' ? 'jpg' : format;
139
+ }
140
+ /** Pull generated-file citations for a given extension out of a Responses output. */
75
141
  export function extractContainerGeneratedFiles(response, extension) {
76
- const suffix = `.${extension}`;
77
142
  const seen = new Set();
78
143
  const files = [];
144
+ const suffix = `.${extension}`;
145
+ const add = (containerId, fileId, filename) => {
146
+ const key = `${containerId}:${fileId}`;
147
+ if (seen.has(key))
148
+ return;
149
+ seen.add(key);
150
+ files.push({ containerId, fileId, filename });
151
+ };
79
152
  for (const item of response.output ?? []) {
80
153
  if (item.type !== 'message')
81
154
  continue;
@@ -86,17 +159,9 @@ export function extractContainerGeneratedFiles(response, extension) {
86
159
  if (ann.type !== 'container_file_citation')
87
160
  continue;
88
161
  const name = ann.filename?.toLowerCase() ?? '';
89
- if (!name.endsWith(suffix))
90
- continue;
91
- const key = `${ann.container_id}:${ann.file_id}`;
92
- if (seen.has(key))
93
- continue;
94
- seen.add(key);
95
- files.push({
96
- containerId: ann.container_id,
97
- fileId: ann.file_id,
98
- filename: ann.filename,
99
- });
162
+ if (name.endsWith(suffix)) {
163
+ add(ann.container_id, ann.file_id, ann.filename);
164
+ }
100
165
  }
101
166
  }
102
167
  }
@@ -125,38 +190,70 @@ async function listContainerGeneratedFiles(client, containerId, extension) {
125
190
  }
126
191
  return files;
127
192
  }
193
+ async function downloadContainerFile(client, file) {
194
+ try {
195
+ const res = await client.containers.files.content.retrieve(file.fileId, {
196
+ container_id: file.containerId,
197
+ });
198
+ const bytes = await res.arrayBuffer();
199
+ return Buffer.from(bytes);
200
+ }
201
+ catch (error) {
202
+ logger.error('Failed to download container file', { error, file });
203
+ return null;
204
+ }
205
+ }
128
206
  function safeBasename(title) {
129
- return (title
207
+ const base = title
130
208
  .replace(/[^a-zA-Z0-9\s\-_]/g, '')
131
209
  .replace(/\s+/g, '_')
132
- .substring(0, 60) || 'document');
210
+ .substring(0, 60);
211
+ return base || 'document';
212
+ }
213
+ function buildDocumentGenInstructions(format) {
214
+ const qualityRules = FORMAT_QUALITY_RULES[format] ?? [];
215
+ return [
216
+ 'You are a document generator for K-12 and university teachers.',
217
+ 'When given a title, output format, and source content:',
218
+ '1. Use the python tool to create exactly ONE output file of the requested type.',
219
+ `2. For this format use: ${FORMAT_HINTS[format]}.`,
220
+ `3. You MUST output a ${format.toUpperCase()} file — not any other format.`,
221
+ `4. The saved filename MUST end with .${extensionForFormat(format)}.`,
222
+ '5. Faithfully adapt ALL source content to the output medium — do not summarize away detail.',
223
+ '6. Include the document title prominently where the format allows.',
224
+ '7. Put ONLY the educational content in the file — no meta commentary.',
225
+ '8. You MUST save the file to disk in the working directory before you finish.',
226
+ ...(format !== 'pdf'
227
+ ? [`9. Do NOT create a PDF when ${format.toUpperCase()} was requested.`]
228
+ : []),
229
+ ...(qualityRules.length > 0
230
+ ? ['', 'Format-specific quality:', ...qualityRules.map((r, i) => `${i + 1}. ${r}`)]
231
+ : []),
232
+ ].join('\n');
133
233
  }
134
234
  /** Generate a file via OpenAI Code Interpreter. */
135
235
  export async function generateDocumentWithOpenAI(input) {
136
236
  const client = new OpenAI();
137
237
  const format = normalizeDocumentFormat(input.format);
138
- const ext = format === 'jpg' ? 'jpg' : format;
238
+ const ext = extensionForFormat(format);
139
239
  const filename = `${safeBasename(input.title)}.${ext}`;
140
240
  try {
141
241
  const response = await client.responses.create({
142
242
  model: DOCUMENT_GEN_MODEL,
143
- instructions: [
144
- 'You generate classroom-ready files for teachers using the python tool.',
145
- `You MUST output a ${ext.toUpperCase()} file — not any other format.`,
146
- `Use: ${FORMAT_HINTS[format]}.`,
147
- `The saved filename MUST end with .${ext}.`,
148
- 'Save exactly one output file with the requested filename.',
149
- 'Include only educational content — no chat commentary.',
150
- ...(format !== 'pdf' ? [`Do NOT create a PDF when ${ext.toUpperCase()} was requested.`] : []),
151
- ].join(' '),
152
- tools: [{ type: 'code_interpreter', container: { type: 'auto' } }],
243
+ instructions: buildDocumentGenInstructions(format),
244
+ tools: [
245
+ {
246
+ type: 'code_interpreter',
247
+ container: { type: 'auto' },
248
+ },
249
+ ],
153
250
  tool_choice: 'required',
154
251
  input: [
155
- `Create a ${ext.toUpperCase()} file.`,
156
- `Filename (exact): ${filename}`,
157
- `Title: ${input.title}`,
158
- 'Content:',
159
- input.content,
252
+ `Create a ${ext.toUpperCase()} file using the python tool.`,
253
+ `Output filename (exact): ${filename}`,
254
+ `Output format: ${ext}`,
255
+ `Document title: ${input.title}`,
256
+ ['Source content — adapt fully to the output medium (do not paste raw markdown into slides/images):', input.content].join('\n'),
160
257
  ].join('\n\n'),
161
258
  });
162
259
  let matches = extractContainerGeneratedFiles(response, format);
@@ -167,18 +264,18 @@ export async function generateDocumentWithOpenAI(input) {
167
264
  }
168
265
  }
169
266
  if (matches.length === 0) {
170
- logger.error('OpenAI document gen: no output file', {
267
+ logger.error('OpenAI document gen produced no matching files', {
171
268
  title: input.title,
172
269
  format,
270
+ outputTypes: (response.output ?? []).map((o) => o.type),
173
271
  });
174
272
  return null;
175
273
  }
176
274
  const preferred = matches.find((f) => f.filename.toLowerCase() === filename.toLowerCase()) ??
177
275
  matches[0];
178
- const res = await client.containers.files.content.retrieve(preferred.fileId, {
179
- container_id: preferred.containerId,
180
- });
181
- const bytes = Buffer.from(await res.arrayBuffer());
276
+ const bytes = await downloadContainerFile(client, preferred);
277
+ if (!bytes)
278
+ return null;
182
279
  return {
183
280
  bytes,
184
281
  filename: preferred.filename,
@@ -187,9 +284,20 @@ export async function generateDocumentWithOpenAI(input) {
187
284
  };
188
285
  }
189
286
  catch (error) {
190
- logger.error('OpenAI document generation failed', { error, title: input.title, format });
287
+ logger.error('OpenAI document generation failed', {
288
+ error,
289
+ title: input.title,
290
+ format,
291
+ });
191
292
  return null;
192
293
  }
193
294
  }
295
+ /** @deprecated Use {@link generateDocumentWithOpenAI} */
296
+ export async function generatePdfWithOpenAI(input) {
297
+ const result = await generateDocumentWithOpenAI({ ...input, format: 'pdf' });
298
+ return result?.bytes ?? null;
299
+ }
300
+ /** @deprecated Use {@link extractContainerGeneratedFiles} */
301
+ export const extractContainerPdfFiles = (response) => extractContainerGeneratedFiles(response, 'pdf');
194
302
  //# sourceMappingURL=openaiDocumentGen.js.map
195
- //# debugId=cd65973d-ca13-5498-8d6b-ff056b093631
303
+ //# debugId=d086b281-e191-5157-a799-843675a76a37
@@ -1 +1 @@
1
- {"version":3,"file":"openaiDocumentGen.js","sources":["services/openaiDocumentGen.ts"],"sourceRoot":"/","sourcesContent":["/**\n * Generate files via OpenAI Code Interpreter (Responses API).\n * Supports every format the sandbox can produce (pdf, docx, xlsx, pptx, …).\n */\nimport OpenAI from 'openai';\nimport type { Response } from 'openai/resources/responses/responses.js';\nimport { logger } from '../utils/logger.js';\n\nconst DOCUMENT_GEN_MODEL = 'gpt-4o-mini';\n\nexport const SUPPORTED_DOCUMENT_FORMATS = [\n 'pdf', 'docx', 'doc', 'xlsx', 'pptx', 'csv', 'md', 'html', 'txt', 'json',\n 'xml', 'tex', 'png', 'jpeg', 'jpg', 'gif', 'zip', 'tar', 'py', 'js', 'ts',\n 'css', 'sh',\n] as const;\n\nexport type DocumentFormat = (typeof SUPPORTED_DOCUMENT_FORMATS)[number];\n\nconst FORMAT_MIME: Record<DocumentFormat, string> = {\n pdf: 'application/pdf',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n doc: 'application/msword',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n csv: 'text/csv',\n md: 'text/markdown',\n html: 'text/html',\n txt: 'text/plain',\n json: 'application/json',\n xml: 'application/xml',\n tex: 'text/x-tex',\n png: 'image/png',\n jpeg: 'image/jpeg',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n zip: 'application/zip',\n tar: 'application/x-tar',\n py: 'text/x-python',\n js: 'text/javascript',\n ts: 'application/typescript',\n css: 'text/css',\n sh: 'application/x-sh',\n};\n\nconst FORMAT_HINTS: Record<DocumentFormat, string> = {\n pdf: 'fpdf2 or reportlab',\n docx: 'python-docx',\n doc: 'python-docx',\n xlsx: 'openpyxl or pandas',\n pptx: 'python-pptx',\n csv: 'pandas or csv module',\n md: 'write markdown directly',\n html: 'write a complete HTML page',\n txt: 'write plain text',\n json: 'json.dumps with indentation',\n xml: 'well-formed XML',\n tex: 'LaTeX source',\n png: 'matplotlib or Pillow',\n jpeg: 'matplotlib or Pillow',\n jpg: 'matplotlib or Pillow',\n gif: 'matplotlib or Pillow',\n zip: 'zipfile',\n tar: 'tarfile',\n py: 'Python source',\n js: 'JavaScript source',\n ts: 'TypeScript source',\n css: 'CSS stylesheet',\n sh: 'shell script',\n};\n\nexport interface GenerateDocumentInput {\n title: string;\n content: string;\n format?: DocumentFormat | string;\n}\n\nexport interface GeneratedDocumentResult {\n bytes: Buffer;\n filename: string;\n mimeType: string;\n format: DocumentFormat;\n}\n\nexport interface ContainerGeneratedFile {\n containerId: string;\n fileId: string;\n filename: string;\n}\n\nexport function normalizeDocumentFormat(format?: string | null): DocumentFormat {\n const raw = (format ?? 'pdf').toLowerCase().replace(/^\\./, '');\n if ((SUPPORTED_DOCUMENT_FORMATS as readonly string[]).includes(raw)) {\n return raw as DocumentFormat;\n }\n return 'pdf';\n}\n\nexport function mimeTypeForFormat(format: DocumentFormat): string {\n return FORMAT_MIME[format];\n}\n\nexport function extractContainerGeneratedFiles(\n response: Response,\n extension: DocumentFormat,\n): ContainerGeneratedFile[] {\n const suffix = `.${extension}`;\n const seen = new Set<string>();\n const files: ContainerGeneratedFile[] = [];\n\n for (const item of response.output ?? []) {\n if (item.type !== 'message') continue;\n for (const block of item.content ?? []) {\n if (block.type !== 'output_text') continue;\n for (const ann of block.annotations ?? []) {\n if (ann.type !== 'container_file_citation') continue;\n const name = ann.filename?.toLowerCase() ?? '';\n if (!name.endsWith(suffix)) continue;\n const key = `${ann.container_id}:${ann.file_id}`;\n if (seen.has(key)) continue;\n seen.add(key);\n files.push({\n containerId: ann.container_id,\n fileId: ann.file_id,\n filename: ann.filename,\n });\n }\n }\n }\n return files;\n}\n\nfunction containerIdFromResponse(response: Response): string | undefined {\n for (const item of response.output ?? []) {\n if (item.type === 'code_interpreter_call' && item.container_id) {\n return item.container_id;\n }\n }\n return undefined;\n}\n\nasync function listContainerGeneratedFiles(\n client: OpenAI,\n containerId: string,\n extension: DocumentFormat,\n): Promise<ContainerGeneratedFile[]> {\n const suffix = `.${extension}`;\n const files: ContainerGeneratedFile[] = [];\n for await (const file of client.containers.files.list(containerId)) {\n const path = file.path?.toLowerCase() ?? '';\n if (path.endsWith(suffix) && file.source === 'assistant') {\n files.push({\n containerId,\n fileId: file.id,\n filename: file.path.split('/').pop() ?? file.path,\n });\n }\n }\n return files;\n}\n\nfunction safeBasename(title: string): string {\n return (\n title\n .replace(/[^a-zA-Z0-9\\s\\-_]/g, '')\n .replace(/\\s+/g, '_')\n .substring(0, 60) || 'document'\n );\n}\n\n/** Generate a file via OpenAI Code Interpreter. */\nexport async function generateDocumentWithOpenAI(\n input: GenerateDocumentInput,\n): Promise<GeneratedDocumentResult | null> {\n const client = new OpenAI();\n const format = normalizeDocumentFormat(input.format);\n const ext = format === 'jpg' ? 'jpg' : format;\n const filename = `${safeBasename(input.title)}.${ext}`;\n\n try {\n const response = await client.responses.create({\n model: DOCUMENT_GEN_MODEL,\n instructions: [\n 'You generate classroom-ready files for teachers using the python tool.',\n `You MUST output a ${ext.toUpperCase()} file — not any other format.`,\n `Use: ${FORMAT_HINTS[format]}.`,\n `The saved filename MUST end with .${ext}.`,\n 'Save exactly one output file with the requested filename.',\n 'Include only educational content — no chat commentary.',\n ...(format !== 'pdf' ? [`Do NOT create a PDF when ${ext.toUpperCase()} was requested.`] : []),\n ].join(' '),\n tools: [{ type: 'code_interpreter', container: { type: 'auto' } }],\n tool_choice: 'required',\n input: [\n `Create a ${ext.toUpperCase()} file.`,\n `Filename (exact): ${filename}`,\n `Title: ${input.title}`,\n 'Content:',\n input.content,\n ].join('\\n\\n'),\n });\n\n let matches = extractContainerGeneratedFiles(response, format);\n if (matches.length === 0) {\n const containerId = containerIdFromResponse(response);\n if (containerId) {\n matches = await listContainerGeneratedFiles(client, containerId, format);\n }\n }\n\n if (matches.length === 0) {\n logger.error('OpenAI document gen: no output file', {\n title: input.title,\n format,\n });\n return null;\n }\n\n const preferred =\n matches.find((f) => f.filename.toLowerCase() === filename.toLowerCase()) ??\n matches[0];\n\n const res = await client.containers.files.content.retrieve(preferred.fileId, {\n container_id: preferred.containerId,\n });\n const bytes = Buffer.from(await res.arrayBuffer());\n\n return {\n bytes,\n filename: preferred.filename,\n mimeType: mimeTypeForFormat(format),\n format,\n };\n } catch (error) {\n logger.error('OpenAI document generation failed', { error, title: input.title, format });\n return null;\n }\n}\n"],"names":[],"mappings":"AAAA;;;GAGG;;;AACH,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,MAAM,kBAAkB,GAAG,aAAa,CAAC;AAEzC,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;IACxE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;IACzE,KAAK,EAAE,IAAI;CACH,CAAC;AAIX,MAAM,WAAW,GAAmC;IAClD,GAAG,EAAE,iBAAiB;IACtB,IAAI,EAAE,yEAAyE;IAC/E,GAAG,EAAE,oBAAoB;IACzB,IAAI,EAAE,mEAAmE;IACzE,IAAI,EAAE,2EAA2E;IACjF,GAAG,EAAE,UAAU;IACf,EAAE,EAAE,eAAe;IACnB,IAAI,EAAE,WAAW;IACjB,GAAG,EAAE,YAAY;IACjB,IAAI,EAAE,kBAAkB;IACxB,GAAG,EAAE,iBAAiB;IACtB,GAAG,EAAE,YAAY;IACjB,GAAG,EAAE,WAAW;IAChB,IAAI,EAAE,YAAY;IAClB,GAAG,EAAE,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+ {"version":3,"file":"openaiDocumentGen.js","sources":["services/openaiDocumentGen.ts"],"sourceRoot":"/","sourcesContent":["/**\n * Generate files via OpenAI Code Interpreter (Responses API).\n * Supports every format the sandbox can produce (pdf, docx, xlsx, pptx, …).\n */\nimport OpenAI from 'openai';\nimport type { Response } from 'openai/resources/responses/responses.js';\nimport { logger } from '../utils/logger.js';\n\nconst DOCUMENT_GEN_MODEL = 'gpt-5.5';\n\n/**\n * Extensions OpenAI Code Interpreter can read/write in its sandbox.\n * @see https://developers.openai.com/api/docs/guides/tools-code-interpreter\n */\nexport const SUPPORTED_DOCUMENT_FORMATS = [\n 'pdf',\n 'docx',\n 'doc',\n 'xlsx',\n 'pptx',\n 'csv',\n 'md',\n 'html',\n 'txt',\n 'json',\n 'xml',\n 'tex',\n 'png',\n 'jpeg',\n 'jpg',\n 'gif',\n 'zip',\n 'tar',\n 'py',\n 'js',\n 'ts',\n 'css',\n 'sh',\n] as const;\n\nexport type DocumentFormat = (typeof SUPPORTED_DOCUMENT_FORMATS)[number];\n\nconst FORMAT_MIME: Record<DocumentFormat, string> = {\n pdf: 'application/pdf',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n doc: 'application/msword',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n csv: 'text/csv',\n md: 'text/markdown',\n html: 'text/html',\n txt: 'text/plain',\n json: 'application/json',\n xml: 'application/xml',\n tex: 'text/x-tex',\n png: 'image/png',\n jpeg: 'image/jpeg',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n zip: 'application/zip',\n tar: 'application/x-tar',\n py: 'text/x-python',\n js: 'text/javascript',\n ts: 'application/typescript',\n css: 'text/css',\n sh: 'application/x-sh',\n};\n\nconst FORMAT_HINTS: Record<DocumentFormat, string> = {\n pdf: 'fpdf2 or reportlab — polished document with headings, body text, and tables',\n docx: 'python-docx — Word document with heading styles, paragraphs, and lists',\n doc: 'python-docx saving as .doc if supported, otherwise .docx',\n xlsx: 'openpyxl or pandas — spreadsheet with labelled columns, formulas where useful',\n pptx: 'python-pptx — full slide deck: title slide, section slides, bullets, diagrams on slides',\n csv: 'pandas or csv module — tabular data with headers',\n md: 'write the markdown file directly',\n html: 'write a complete, styled HTML page',\n txt: 'write plain text with clear section breaks',\n json: 'json.dumps with readable indentation',\n xml: 'well-formed XML document',\n tex: 'LaTeX source that compiles to the requested content',\n png: 'matplotlib, networkx, or Pillow — render the described chart/diagram as a finished image',\n jpeg: 'matplotlib or Pillow — high-quality visual saved as JPEG',\n jpg: 'matplotlib or Pillow — high-quality visual saved as JPEG',\n gif: 'matplotlib or Pillow — save as GIF',\n zip: 'zipfile — bundle multiple related files if needed',\n tar: 'tarfile — archive if multiple files are required',\n py: 'valid, runnable Python source with comments',\n js: 'valid JavaScript source with comments',\n ts: 'valid TypeScript source with comments',\n css: 'stylesheet file',\n sh: 'shell script file',\n};\n\n/** Extra quality rules appended for formats that need more than a one-line library hint. */\nconst FORMAT_QUALITY_RULES: Partial<Record<DocumentFormat, string[]>> = {\n png: [\n 'Interpret the source content as a visual spec — draw it, do not dump text into the image.',\n 'Charts: labelled axes, legend, title, readable font sizes, 150+ DPI.',\n 'Diagrams/flowcharts: use matplotlib patches, networkx, or Pillow drawing — boxes, arrows, labels.',\n 'Geometry/maps: accurate relative positions; label every important part.',\n 'Use color meaningfully; avoid blank or placeholder images.',\n ],\n jpeg: [\n 'Same visual quality rules as PNG — polished chart or diagram, not a screenshot of text.',\n ],\n jpg: [\n 'Same visual quality rules as PNG — polished chart or diagram, not a screenshot of text.',\n ],\n gif: [\n 'Render a clear educational visual; static GIF is fine unless animation is described.',\n ],\n pptx: [\n 'Split slides on \"---\" lines or \"Slide N:\" / \"# \" headings in the source content.',\n 'Title slide first, then content slides with concise bullets (not walls of text).',\n 'If the content describes a diagram, draw it on a slide (shapes/arrows) or embed a generated chart.',\n 'Use distinct slide layouts where appropriate (title, title+content).',\n ],\n xlsx: [\n 'Parse markdown tables or tabular lists in the source into real rows/columns.',\n 'Bold header row; auto-fit column widths where possible.',\n ],\n pdf: [\n 'If the source describes a figure/chart, generate and embed it — do not leave a \"[diagram]\" placeholder.',\n ],\n docx: [\n 'Use Heading 1/2 styles for section titles; bullets and numbered lists for enumerations.',\n ],\n html: [\n 'Include embedded CSS for readable typography; use tables or simple layout for structured content.',\n ],\n};\n\nexport interface GenerateDocumentInput {\n title: string;\n /** Markdown or plain-text source material for the output file. */\n content: string;\n /** Output format. Defaults to pdf. */\n format?: DocumentFormat | string;\n}\n\nexport interface GeneratedDocumentResult {\n bytes: Buffer;\n filename: string;\n mimeType: string;\n format: DocumentFormat;\n}\n\nexport interface ContainerGeneratedFile {\n containerId: string;\n fileId: string;\n filename: string;\n}\n\nexport function normalizeDocumentFormat(\n format?: string | null,\n): DocumentFormat {\n const raw = (format ?? 'pdf').toLowerCase().replace(/^\\./, '');\n if ((SUPPORTED_DOCUMENT_FORMATS as readonly string[]).includes(raw)) {\n return raw as DocumentFormat;\n }\n return 'pdf';\n}\n\nexport function mimeTypeForFormat(format: DocumentFormat): string {\n return FORMAT_MIME[format];\n}\n\nexport function extensionForFormat(format: DocumentFormat): string {\n return format === 'jpg' ? 'jpg' : format;\n}\n\n/** Pull generated-file citations for a given extension out of a Responses output. */\nexport function extractContainerGeneratedFiles(\n response: Response,\n extension: DocumentFormat,\n): ContainerGeneratedFile[] {\n const seen = new Set<string>();\n const files: ContainerGeneratedFile[] = [];\n const suffix = `.${extension}`;\n\n const add = (containerId: string, fileId: string, filename: string) => {\n const key = `${containerId}:${fileId}`;\n if (seen.has(key)) return;\n seen.add(key);\n files.push({ containerId, fileId, filename });\n };\n\n for (const item of response.output ?? []) {\n if (item.type !== 'message') continue;\n for (const block of item.content ?? []) {\n if (block.type !== 'output_text') continue;\n for (const ann of block.annotations ?? []) {\n if (ann.type !== 'container_file_citation') continue;\n const name = ann.filename?.toLowerCase() ?? '';\n if (name.endsWith(suffix)) {\n add(ann.container_id, ann.file_id, ann.filename);\n }\n }\n }\n }\n\n return files;\n}\n\nfunction containerIdFromResponse(response: Response): string | undefined {\n for (const item of response.output ?? []) {\n if (item.type === 'code_interpreter_call' && item.container_id) {\n return item.container_id;\n }\n }\n return undefined;\n}\n\nasync function listContainerGeneratedFiles(\n client: OpenAI,\n containerId: string,\n extension: DocumentFormat,\n): Promise<ContainerGeneratedFile[]> {\n const suffix = `.${extension}`;\n const files: ContainerGeneratedFile[] = [];\n for await (const file of client.containers.files.list(containerId)) {\n const path = file.path?.toLowerCase() ?? '';\n if (path.endsWith(suffix) && file.source === 'assistant') {\n files.push({\n containerId,\n fileId: file.id,\n filename: file.path.split('/').pop() ?? file.path,\n });\n }\n }\n return files;\n}\n\nasync function downloadContainerFile(\n client: OpenAI,\n file: ContainerGeneratedFile,\n): Promise<Buffer | null> {\n try {\n const res = await client.containers.files.content.retrieve(file.fileId, {\n container_id: file.containerId,\n });\n const bytes = await res.arrayBuffer();\n return Buffer.from(bytes);\n } catch (error) {\n logger.error('Failed to download container file', { error, file });\n return null;\n }\n}\n\nfunction safeBasename(title: string): string {\n const base = title\n .replace(/[^a-zA-Z0-9\\s\\-_]/g, '')\n .replace(/\\s+/g, '_')\n .substring(0, 60);\n return base || 'document';\n}\n\nfunction buildDocumentGenInstructions(format: DocumentFormat): string {\n const qualityRules = FORMAT_QUALITY_RULES[format] ?? [];\n return [\n 'You are a document generator for K-12 and university teachers.',\n 'When given a title, output format, and source content:',\n '1. Use the python tool to create exactly ONE output file of the requested type.',\n `2. For this format use: ${FORMAT_HINTS[format]}.`,\n `3. You MUST output a ${format.toUpperCase()} file — not any other format.`,\n `4. The saved filename MUST end with .${extensionForFormat(format)}.`,\n '5. Faithfully adapt ALL source content to the output medium — do not summarize away detail.',\n '6. Include the document title prominently where the format allows.',\n '7. Put ONLY the educational content in the file — no meta commentary.',\n '8. You MUST save the file to disk in the working directory before you finish.',\n ...(format !== 'pdf'\n ? [`9. Do NOT create a PDF when ${format.toUpperCase()} was requested.`]\n : []),\n ...(qualityRules.length > 0\n ? ['', 'Format-specific quality:', ...qualityRules.map((r, i) => `${i + 1}. ${r}`)]\n : []),\n ].join('\\n');\n}\n\n/** Generate a file via OpenAI Code Interpreter. */\nexport async function generateDocumentWithOpenAI(\n input: GenerateDocumentInput,\n): Promise<GeneratedDocumentResult | null> {\n const client = new OpenAI();\n const format = normalizeDocumentFormat(input.format);\n const ext = extensionForFormat(format);\n const filename = `${safeBasename(input.title)}.${ext}`;\n\n try {\n const response = await client.responses.create({\n model: DOCUMENT_GEN_MODEL,\n instructions: buildDocumentGenInstructions(format),\n tools: [\n {\n type: 'code_interpreter',\n container: { type: 'auto' },\n },\n ],\n tool_choice: 'required',\n input: [\n `Create a ${ext.toUpperCase()} file using the python tool.`,\n `Output filename (exact): ${filename}`,\n `Output format: ${ext}`,\n `Document title: ${input.title}`,\n ['Source content — adapt fully to the output medium (do not paste raw markdown into slides/images):', input.content].join('\\n'),\n ].join('\\n\\n'),\n });\n\n let matches = extractContainerGeneratedFiles(response, format);\n\n if (matches.length === 0) {\n const containerId = containerIdFromResponse(response);\n if (containerId) {\n matches = await listContainerGeneratedFiles(client, containerId, format);\n }\n }\n\n if (matches.length === 0) {\n logger.error('OpenAI document gen produced no matching files', {\n title: input.title,\n format,\n outputTypes: (response.output ?? []).map((o) => o.type),\n });\n return null;\n }\n\n const preferred =\n matches.find((f) => f.filename.toLowerCase() === filename.toLowerCase()) ??\n matches[0];\n\n const bytes = await downloadContainerFile(client, preferred);\n if (!bytes) return null;\n\n return {\n bytes,\n filename: preferred.filename,\n mimeType: mimeTypeForFormat(format),\n format,\n };\n } catch (error) {\n logger.error('OpenAI document generation failed', {\n error,\n title: input.title,\n format,\n });\n return null;\n }\n}\n\n/** @deprecated Use {@link generateDocumentWithOpenAI} */\nexport async function generatePdfWithOpenAI(\n input: Omit<GenerateDocumentInput, 'format'>,\n): Promise<Buffer | null> {\n const result = await generateDocumentWithOpenAI({ ...input, format: 'pdf' });\n return result?.bytes ?? null;\n}\n\n/** @deprecated Use {@link extractContainerGeneratedFiles} */\nexport const extractContainerPdfFiles = (response: Response) =>\n extractContainerGeneratedFiles(response, 'pdf');\n"],"names":[],"mappings":"AAAA;;;GAGG;;;AACH,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,MAAM,kBAAkB,GAAG,SAAS,CAAC;AAErC;;;GAGG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,KAAK;IACL,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,KAAK;IACL,KAAK;IACL,MAAM;IACN,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,KAAK;IACL,IAAI;CACI,CAAC;AAIX,MAAM,WAAW,GAAmC;IAClD,GAAG,EAAE,iBAAiB;IACtB,IAAI,EAAE,yEAAyE;IAC/E,GAAG,EAAE,oBAAoB;IACzB,IAAI,EAAE,mEAAmE;IACzE,IAAI,EAAE,2EAA2E;IACjF,GAAG,EAAE,UAAU;IACf,EAAE,EAAE,eAAe;IACnB,IAAI,EAAE,WAAW;IACjB,GAAG,EAAE,YAAY;IACjB,IAAI,EAAE,kBAAkB;IACxB,GAAG,EAAE,iBAAiB;IACtB,GAAG,EAAE,YAAY;IACjB,GAAG,EAAE,WAAW;IAChB,IAAI,EAAE,YAAY;IAClB,GAAG,EAAE,YAAY;IACjB,GAAG,EAAE,WAAW;IAChB,GAAG,EAAE,iBAAiB;IACtB,GAAG,EAAE,mBAAmB;IACxB,EAAE,EAAE,eAAe;IACnB,EAAE,EAAE,iBAAiB;IACrB,EAAE,EAAE,wBAAwB;IAC5B,GAAG,EAAE,UAAU;IACf,EAAE,EAAE,kBAAkB;CACvB,CAAC;AAEF,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AAC;QAExB,OAAO;YACL,KAAK;YACL,QAAQ,EAAE,SAAS,CAAC,QAAQ;YAC5B,QAAQ,EAAE,iBAAiB,CAAC,MAAM,CAAC;YACnC,MAAM;SACP,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,mCAAmC,EAAE;YAChD,KAAK;YACL,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,MAAM;SACP,CAAC,CAAC;QACH,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,yDAAyD;AACzD,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,KAA4C;IAE5C,MAAM,MAAM,GAAG,MAAM,0BAA0B,CAAC,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IAC7E,OAAO,MAAM,EAAE,KAAK,IAAI,IAAI,CAAC;AAC/B,CAAC;AAED,6DAA6D;AAC7D,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,QAAkB,EAAE,EAAE,CAC7D,8BAA8B,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC","debug_id":"d086b281-e191-5157-a799-843675a76a37"}
@@ -162,6 +162,8 @@ export declare function createSchoolClass(userId: string, input: {
162
162
  email: string;
163
163
  password: string;
164
164
  verified: boolean;
165
+ termsAcceptedAt: Date | null;
166
+ termsVersion: string | null;
165
167
  schoolId: string | null;
166
168
  }[];
167
169
  students: {
@@ -170,6 +172,8 @@ export declare function createSchoolClass(userId: string, input: {
170
172
  email: string;
171
173
  password: string;
172
174
  verified: boolean;
175
+ termsAcceptedAt: Date | null;
176
+ termsVersion: string | null;
173
177
  schoolId: string | null;
174
178
  }[];
175
179
  } & {
@@ -1 +1 @@
1
- {"version":3,"file":"school.d.ts","sourceRoot":"/","sources":["services/school.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,oBAAoB,EAAe,MAAM,gBAAgB,CAAC;AA4DnE,wBAAsB,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EAAE;IACL,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,EAAE,CAAC,EAAE,IAAI,CAAC;CACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyIF;AAED,wBAAsB,YAAY,CAChC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE;IACL,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,oBAAoB,CAAC;IAC3B;sEACkE;IAClE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,uEAAuE;IACvE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;;;;;;;;;;;;;;;;;;;;;;;;;GAkGF;AAED,wBAAsB,YAAY,CAChC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE;;;;;;;;;;;;;;;GAI9C;AAED,wBAAsB,SAAS,CAAC,KAAK,EAAE,MAAM;;;;;;;;;;;GAiB5C;AAED,wBAAsB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;;;;;;;;;;GAsB/D"}
@@ -0,0 +1,86 @@
1
+ /** Export a portable snapshot of the authenticated user's personal data. */
2
+ export declare function exportUserData(userId: string): Promise<{
3
+ exportedAt: string;
4
+ user: {
5
+ id: string;
6
+ username: string;
7
+ email: string;
8
+ verified: boolean;
9
+ termsAcceptedAt: Date | null;
10
+ termsVersion: string | null;
11
+ profile: {
12
+ id: string;
13
+ userId: string;
14
+ displayName: string | null;
15
+ bio: string | null;
16
+ location: string | null;
17
+ website: string | null;
18
+ createdAt: Date;
19
+ updatedAt: Date;
20
+ profilePicture: string | null;
21
+ profilePictureThumbnail: string | null;
22
+ } | null;
23
+ teacherIn: {
24
+ section: string;
25
+ id: string;
26
+ name: string;
27
+ subject: string;
28
+ }[];
29
+ studentIn: {
30
+ section: string;
31
+ id: string;
32
+ name: string;
33
+ subject: string;
34
+ }[];
35
+ submissions: {
36
+ assignment: {
37
+ id: string;
38
+ classId: string;
39
+ title: string;
40
+ };
41
+ id: string;
42
+ createdAt: Date;
43
+ extendedResponse: string | null;
44
+ gradeReceived: number | null;
45
+ submittedAt: Date | null;
46
+ }[];
47
+ events: {
48
+ id: string;
49
+ location: string | null;
50
+ name: string | null;
51
+ startTime: Date;
52
+ endTime: Date;
53
+ remarks: string | null;
54
+ }[];
55
+ notificationsReceived: {
56
+ id: string;
57
+ createdAt: Date;
58
+ title: string;
59
+ content: string;
60
+ read: boolean;
61
+ }[];
62
+ schoolMemberships: {
63
+ status: import(".prisma/client").$Enums.SchoolMembershipStatus;
64
+ school: {
65
+ id: string;
66
+ name: string;
67
+ };
68
+ role: import(".prisma/client").$Enums.SchoolMembershipRole;
69
+ }[];
70
+ sentMessages: {
71
+ id: string;
72
+ createdAt: Date;
73
+ content: string;
74
+ conversationId: string;
75
+ }[];
76
+ };
77
+ }>;
78
+ /**
79
+ * Erase personal account data by anonymizing the user record and removing
80
+ * sessions and memberships. Educational records tied to classes (e.g.
81
+ * submissions) remain with an anonymized identity where required.
82
+ */
83
+ export declare function deleteUserAccount(userId: string): Promise<{
84
+ success: boolean;
85
+ }>;
86
+ //# sourceMappingURL=userPrivacy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"userPrivacy.d.ts","sourceRoot":"/","sources":["services/userPrivacy.ts"],"names":[],"mappings":"AA6DA,4EAA4E;AAC5E,wBAAsB,cAAc,CAAC,MAAM,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4ElD;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CAAC,MAAM,EAAE,MAAM;;GAkDrD"}