@speakableio/core 1.0.57 → 1.0.59

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.
@@ -1,3876 +0,0 @@
1
- // src/providers/SpeakableProvider.tsx
2
- import { createContext, useContext, useEffect, useState } from "react";
3
- import { jsx } from "react/jsx-runtime";
4
- var FsCtx = createContext(null);
5
- function SpeakableProvider({
6
- user,
7
- children,
8
- queryClient,
9
- permissions,
10
- fsClient
11
- }) {
12
- const [speakableApi, setSpeakableApi] = useState(null);
13
- useEffect(() => {
14
- setSpeakableApi(fsClient);
15
- }, [fsClient]);
16
- if (!speakableApi) return null;
17
- return /* @__PURE__ */ jsx(
18
- FsCtx.Provider,
19
- {
20
- value: {
21
- speakableApi,
22
- queryClient,
23
- user,
24
- permissions
25
- },
26
- children
27
- }
28
- );
29
- }
30
- function useSpeakableApi() {
31
- const ctx = useContext(FsCtx);
32
- if (!ctx) throw new Error("useSpeakableApi must be used within a SpeakableProvider");
33
- return ctx;
34
- }
35
-
36
- // src/utils/error-handler.ts
37
- var ServiceError = class extends Error {
38
- constructor(message, originalError, code) {
39
- super(message);
40
- this.originalError = originalError;
41
- this.code = code;
42
- this.name = "ServiceError";
43
- }
44
- };
45
- function withErrorHandler(fn, serviceName) {
46
- return async (...args) => {
47
- try {
48
- return await fn(...args);
49
- } catch (error) {
50
- console.error(`Service ${serviceName} failed with args:`, args);
51
- console.error("Error details:", error);
52
- if (error instanceof Error && "code" in error) {
53
- const firebaseError = error;
54
- throw new ServiceError(
55
- `Error in ${serviceName}: ${firebaseError.message}`,
56
- error,
57
- firebaseError.code
58
- );
59
- }
60
- if (error instanceof Error) {
61
- throw new ServiceError(`Error in ${serviceName}: ${error.message}`, error);
62
- }
63
- throw new ServiceError(`Unknown error in ${serviceName}`, error);
64
- }
65
- };
66
- }
67
-
68
- // src/lib/firebase/api.ts
69
- var FirebaseAPI = class _FirebaseAPI {
70
- // eslint-disable-next-line @typescript-eslint/no-empty-function
71
- constructor() {
72
- this.config = null;
73
- }
74
- static getInstance() {
75
- if (!_FirebaseAPI.instance) {
76
- _FirebaseAPI.instance = new _FirebaseAPI();
77
- }
78
- return _FirebaseAPI.instance;
79
- }
80
- initialize(config) {
81
- this.config = config;
82
- }
83
- get db() {
84
- if (!this.config) throw new Error("Firebase API not initialized");
85
- return this.config.db;
86
- }
87
- get helpers() {
88
- if (!this.config) throw new Error("Firebase API not initialized");
89
- return this.config.helpers;
90
- }
91
- get httpsCallable() {
92
- var _a;
93
- return (_a = this.config) == null ? void 0 : _a.httpsCallable;
94
- }
95
- logEvent(name, data) {
96
- var _a;
97
- (_a = this.config) == null ? void 0 : _a.logEvent(name, data);
98
- }
99
- accessQueryConstraints() {
100
- const { query: query2, orderBy: orderBy2, limit: limit2, startAt: startAt2, startAfter: startAfter2, endAt: endAt2, endBefore: endBefore2, where: where2, increment: increment2 } = this.helpers;
101
- return {
102
- query: query2,
103
- orderBy: orderBy2,
104
- limit: limit2,
105
- startAt: startAt2,
106
- startAfter: startAfter2,
107
- endAt: endAt2,
108
- endBefore: endBefore2,
109
- where: where2,
110
- increment: increment2
111
- };
112
- }
113
- accessHelpers() {
114
- const { doc: doc2, collection: collection2, writeBatch: writeBatch2, serverTimestamp: serverTimestamp2, setDoc: setDoc2 } = this.helpers;
115
- return {
116
- doc: (path) => doc2(this.db, path),
117
- collection: (path) => collection2(this.db, path),
118
- writeBatch: () => writeBatch2(this.db),
119
- serverTimestamp: serverTimestamp2,
120
- setDoc: setDoc2
121
- };
122
- }
123
- async getDoc(path) {
124
- const { getDoc: getDoc2, doc: doc2 } = this.helpers;
125
- const docRef = doc2(this.db, path);
126
- const docSnap = await getDoc2(docRef);
127
- const data = docSnap.exists() ? {
128
- ...docSnap.data(),
129
- id: docSnap.id
130
- } : null;
131
- return {
132
- id: docSnap.id,
133
- data
134
- };
135
- }
136
- async getDocs(path, ...queryConstraints) {
137
- const { getDocs: getDocs2, query: query2, collection: collection2 } = this.helpers;
138
- const collectionRef = collection2(this.db, path);
139
- const q = queryConstraints.length > 0 ? query2(collectionRef, ...queryConstraints) : collectionRef;
140
- const querySnapshot = await getDocs2(q);
141
- const data = querySnapshot.docs.map((doc2) => ({
142
- data: doc2.data(),
143
- id: doc2.id
144
- }));
145
- return {
146
- data,
147
- querySnapshot,
148
- empty: querySnapshot.empty
149
- };
150
- }
151
- async addDoc(path, data) {
152
- const { addDoc: addDoc2, collection: collection2 } = this.helpers;
153
- const collectionRef = collection2(this.db, path);
154
- const docRef = await addDoc2(collectionRef, data);
155
- return {
156
- ...data,
157
- id: docRef.id
158
- };
159
- }
160
- async setDoc(path, data, options = {}) {
161
- const { setDoc: setDoc2, doc: doc2 } = this.helpers;
162
- const docRef = doc2(this.db, path);
163
- await setDoc2(docRef, data, options);
164
- }
165
- async updateDoc(path, data) {
166
- const { updateDoc: updateDoc2, doc: doc2 } = this.helpers;
167
- const docRef = doc2(this.db, path);
168
- await updateDoc2(docRef, data);
169
- }
170
- async deleteDoc(path) {
171
- const { deleteDoc: deleteDoc2, doc: doc2 } = this.helpers;
172
- const docRef = doc2(this.db, path);
173
- await deleteDoc2(docRef);
174
- }
175
- async runTransaction(updateFunction) {
176
- const { runTransaction: runTransaction2 } = this.helpers;
177
- return runTransaction2(this.db, updateFunction);
178
- }
179
- async runBatch(operations) {
180
- const { writeBatch: writeBatch2 } = this.helpers;
181
- const batch = writeBatch2(this.db);
182
- await Promise.all(operations.map((op) => op()));
183
- await batch.commit();
184
- }
185
- writeBatch() {
186
- const { writeBatch: writeBatch2 } = this.helpers;
187
- const batch = writeBatch2(this.db);
188
- return batch;
189
- }
190
- };
191
- var api = FirebaseAPI.getInstance();
192
-
193
- // src/domains/assignment/assignment.constants.ts
194
- var ASSIGNMENT_ANALYTICS_TYPES = [
195
- "macro" /* Macro */,
196
- "gradebook" /* Gradebook */,
197
- "cards" /* Cards */,
198
- "student" /* Student */,
199
- "student_summary" /* StudentSummary */
200
- ];
201
- var ASSIGNMENTS_COLLECTION = "assignments";
202
- var ANALYTICS_SUBCOLLECTION = "analytics";
203
- var SCORES_SUBCOLLECTION = "scores";
204
- var refsAssignmentFiresotre = {
205
- allAssignments: () => ASSIGNMENTS_COLLECTION,
206
- assignment: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}`,
207
- assignmentAllAnalytics: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}/${ANALYTICS_SUBCOLLECTION}`,
208
- assignmentAnalytics: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}/${ANALYTICS_SUBCOLLECTION}/${params.type}`,
209
- assignmentScores: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}/${SCORES_SUBCOLLECTION}/${params.userId}`
210
- };
211
-
212
- // src/domains/assignment/services/get-assignments-score.service.ts
213
- var _getAssignmentScores = async ({
214
- assignmentId,
215
- analyticType = "macro" /* Macro */,
216
- studentId,
217
- currentUserId
218
- }) => {
219
- if (analyticType === "student" /* Student */) {
220
- const path = refsAssignmentFiresotre.assignmentScores({
221
- id: assignmentId,
222
- userId: currentUserId
223
- });
224
- const response = await api.getDoc(path);
225
- return { scores: response.data, id: assignmentId };
226
- }
227
- if (analyticType === "student_summary" /* StudentSummary */ && studentId) {
228
- const path = refsAssignmentFiresotre.assignmentScores({
229
- id: assignmentId,
230
- userId: studentId
231
- });
232
- const response = await api.getDoc(path);
233
- return { scores: response.data, id: assignmentId };
234
- }
235
- if (analyticType !== "all" /* All */ && ASSIGNMENT_ANALYTICS_TYPES.includes(analyticType)) {
236
- const ref = refsAssignmentFiresotre.assignmentAnalytics({
237
- id: assignmentId,
238
- type: analyticType
239
- });
240
- const docData = await api.getDoc(ref);
241
- return { scores: docData.data, id: assignmentId };
242
- } else if (analyticType === "all" /* All */) {
243
- const ref = refsAssignmentFiresotre.assignmentAllAnalytics({ id: assignmentId });
244
- const response = await api.getDocs(ref);
245
- const data = response.data.reduce((acc, curr) => {
246
- acc[curr.id] = curr;
247
- return acc;
248
- }, {});
249
- return { scores: data, id: assignmentId };
250
- }
251
- };
252
- var getAssignmentScores = withErrorHandler(_getAssignmentScores, "getAssignmentScores");
253
-
254
- // src/domains/assignment/services/attach-score-assignment.service.ts
255
- var _attachScoresAssignment = async ({
256
- assignments,
257
- analyticType,
258
- studentId,
259
- currentUserId
260
- }) => {
261
- const scoresPromises = assignments.map((a) => {
262
- return getAssignmentScores({
263
- assignmentId: a.id,
264
- analyticType,
265
- studentId,
266
- currentUserId
267
- });
268
- });
269
- const scores = await Promise.all(scoresPromises);
270
- const scoresObject = scores.reduce((acc, curr) => {
271
- acc[curr.id] = curr.scores;
272
- return acc;
273
- }, {});
274
- const assignmentsWithScores = assignments.map((a) => {
275
- var _a;
276
- return {
277
- ...a,
278
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/ban-ts-comment
279
- // @ts-ignore
280
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
281
- scores: (_a = scoresObject[a.id]) != null ? _a : null
282
- };
283
- });
284
- return assignmentsWithScores;
285
- };
286
- var attachScoresAssignment = withErrorHandler(
287
- _attachScoresAssignment,
288
- "attachScoresAssignment"
289
- );
290
-
291
- // src/domains/assignment/services/get-all-assignment.service.ts
292
- async function _getAllAssignments() {
293
- const path = refsAssignmentFiresotre.allAssignments();
294
- const response = await api.getDocs(path);
295
- return response.data;
296
- }
297
- var getAllAssignments = withErrorHandler(_getAllAssignments, "getAllAssignments");
298
-
299
- // src/domains/assignment/utils/check-assignment-availability.ts
300
- import dayjs from "dayjs";
301
- var checkAssignmentAvailability = (scheduledTime) => {
302
- if (!scheduledTime) return true;
303
- const scheduledDate = typeof scheduledTime === "string" ? dayjs(scheduledTime) : dayjs(scheduledTime.toDate());
304
- if (!scheduledDate.isValid()) return true;
305
- return dayjs().isAfter(scheduledDate);
306
- };
307
-
308
- // src/domains/assignment/services/get-assignment.service.ts
309
- async function _getAssignment(params) {
310
- var _a;
311
- const path = refsAssignmentFiresotre.assignment({ id: params.assignmentId });
312
- const response = await api.getDoc(path);
313
- if (!response.data) return null;
314
- const assignment = response.data;
315
- const isAvailable = checkAssignmentAvailability(assignment.scheduledTime);
316
- const assignmentWithId = {
317
- ...assignment,
318
- isAvailable,
319
- id: params.assignmentId,
320
- scheduledTime: (_a = assignment.scheduledTime) != null ? _a : null
321
- };
322
- if (params.analyticType) {
323
- const assignmentsWithScores = await attachScoresAssignment({
324
- assignments: [assignmentWithId],
325
- analyticType: params.analyticType,
326
- currentUserId: params.currentUserId
327
- });
328
- return assignmentsWithScores.length > 0 ? assignmentsWithScores[0] : assignmentWithId;
329
- }
330
- return assignmentWithId;
331
- }
332
- var getAssignment = withErrorHandler(_getAssignment, "getAssignment");
333
-
334
- // src/domains/assignment/assignment.repo.ts
335
- var createAssignmentRepo = () => {
336
- return {
337
- getAssignment,
338
- attachScoresAssignment,
339
- getAssignmentScores,
340
- getAllAssignments
341
- };
342
- };
343
-
344
- // src/domains/assignment/hooks/assignment.hooks.ts
345
- import { useQuery } from "@tanstack/react-query";
346
- var assignmentQueryKeys = {
347
- all: ["assignments"],
348
- byId: (id) => [...assignmentQueryKeys.all, id],
349
- list: () => [...assignmentQueryKeys.all, "list"]
350
- };
351
- function useAssignment({
352
- assignmentId,
353
- enabled = true,
354
- analyticType,
355
- userId
356
- }) {
357
- const { speakableApi } = useSpeakableApi();
358
- return useQuery({
359
- queryKey: assignmentQueryKeys.byId(assignmentId),
360
- queryFn: () => speakableApi.assignmentRepo.getAssignment({
361
- assignmentId,
362
- analyticType,
363
- currentUserId: userId
364
- }),
365
- enabled
366
- });
367
- }
368
-
369
- // src/domains/assignment/hooks/score-hooks.ts
370
- import { useMutation, useQuery as useQuery2 } from "@tanstack/react-query";
371
-
372
- // src/utils/debounce.utils.ts
373
- function debounce(func, waitFor) {
374
- let timeoutId;
375
- return (...args) => new Promise((resolve, reject) => {
376
- if (timeoutId) {
377
- clearTimeout(timeoutId);
378
- }
379
- timeoutId = setTimeout(async () => {
380
- try {
381
- const result = await func(...args);
382
- resolve(result);
383
- } catch (error) {
384
- reject(error);
385
- }
386
- }, waitFor);
387
- });
388
- }
389
-
390
- // src/lib/tanstack/handle-optimistic-update-query.ts
391
- var handleOptimisticUpdate = async ({
392
- queryClient,
393
- queryKey,
394
- newData
395
- }) => {
396
- await queryClient.cancelQueries({
397
- queryKey
398
- });
399
- const previousData = queryClient.getQueryData(queryKey);
400
- if (previousData === void 0) {
401
- queryClient.setQueryData(queryKey, newData);
402
- } else {
403
- queryClient.setQueryData(queryKey, { ...previousData, ...newData });
404
- }
405
- return { previousData };
406
- };
407
-
408
- // src/constants/speakable-plans.ts
409
- var FEEDBACK_PLANS = {
410
- FEEDBACK_TRANSCRIPT: "FEEDBACK_TRANSCRIPT",
411
- // Transcript from the audio
412
- FEEDBACK_SUMMARY: "FEEDBACK_SUMMARY",
413
- // Chatty summary (Free plan)
414
- FEEDBACK_GRAMMAR_INSIGHTS: "FEEDBACK_GRAMMAR_INSIGHTS",
415
- // Grammar insights
416
- FEEDBACK_SUGGESTED_RESPONSE: "FEEDBACK_SUGGESTED_RESPONSE",
417
- // Suggested Response
418
- FEEDBACK_RUBRIC: "FEEDBACK_RUBRIC",
419
- // Suggested Response
420
- FEEDBACK_GRADING_STANDARDS: "FEEDBACK_GRADING_STANDARDS",
421
- // ACTFL / WIDA Estimate
422
- FEEDBACK_TARGET_LANGUAGE: "FEEDBACK_TARGET_LANGUAGE",
423
- // Ability to set the feedback language to the target language of the student
424
- FEEDBACK_DISABLE_ALLOW_RETRIES: "FEEDBACK_DISABLE_ALLOW_RETRIES"
425
- // Turn of allow retries
426
- };
427
- var AUTO_GRADING_PLANS = {
428
- AUTO_GRADING_PASS_FAIL: "AUTO_GRADING_PASS_FAIL",
429
- // Pass / fail grading
430
- AUTO_GRADING_RUBRICS: "AUTO_GRADING_RUBRICS",
431
- // Autograded rubrics
432
- AUTO_GRADING_STANDARDS_BASED: "AUTO_GRADING_STANDARDS_BASED"
433
- // Standards based grading
434
- };
435
- var AI_ASSISTANT_PLANS = {
436
- AI_ASSISTANT_DOCUMENT_UPLOADS: "AI_ASSISTANT_DOCUMENT_UPLOADS",
437
- // Allow document uploading
438
- AI_ASSISTANT_UNLIMITED_USE: "AI_ASSISTANT_UNLIMITED_USE"
439
- // Allow unlimited use of AI assistant. Otherwise, limits are used.
440
- };
441
- var ASSIGNMENT_SETTINGS_PLANS = {
442
- ASSESSMENTS: "ASSESSMENTS",
443
- // Ability to create assessment assignment types
444
- GOOGLE_CLASSROOM_GRADE_PASSBACK: "GOOGLE_CLASSROOM_GRADE_PASSBACK"
445
- // Assignment scores can sync with classroom
446
- };
447
- var ANALYTICS_PLANS = {
448
- ANALYTICS_GRADEBOOK: "ANALYTICS_GRADEBOOK",
449
- // Access to the gradebook page
450
- ANALYTICS_CLASSROOM_ANALYTICS: "ANALYTICS_CLASSROOM_ANALYTICS",
451
- // Access to the classroom analytics page
452
- ANALYTICS_STUDENT_PROGRESS_REPORTS: "ANALYTICS_STUDENT_PROGRESS_REPORTS",
453
- // Access to the panel that shows an individual student's progress and assignments
454
- ANALYTICS_ASSIGNMENT_RESULTS: "ANALYTICS_ASSIGNMENT_RESULTS",
455
- // Access to the assigment RESULTS page
456
- ANALYTICS_ORGANIZATION: "ANALYTICS_ORGANIZATION"
457
- // Access to the organization analytics panel (for permitted admins)
458
- };
459
- var SPACES_PLANS = {
460
- SPACES_CREATE_SPACE: "SPACES_CREATE_SPACE",
461
- // Ability to create spaces
462
- SPACES_CHECK_POINTS: "SPACES_CHECK_POINTS"
463
- // Feature not available yet. Ability to create checkpoints for spaces for data aggregation
464
- };
465
- var DISCOVER_PLANS = {
466
- DISCOVER_ORGANIZATION_LIBRARY: "DISCOVER_ORGANIZATION_LIBRARY"
467
- // Access to the organizations shared library
468
- };
469
- var MEDIA_AREA_PLANS = {
470
- MEDIA_AREA_DOCUMENT_UPLOAD: "MEDIA_AREA_DOCUMENT_UPLOAD",
471
- MEDIA_AREA_AUDIO_FILES: "MEDIA_AREA_AUDIO_FILES"
472
- };
473
- var FREE_PLAN = [];
474
- var TEACHER_PRO_PLAN = [
475
- FEEDBACK_PLANS.FEEDBACK_TRANSCRIPT,
476
- FEEDBACK_PLANS.FEEDBACK_SUMMARY,
477
- FEEDBACK_PLANS.FEEDBACK_TARGET_LANGUAGE,
478
- AUTO_GRADING_PLANS.AUTO_GRADING_PASS_FAIL,
479
- ANALYTICS_PLANS.ANALYTICS_GRADEBOOK,
480
- SPACES_PLANS.SPACES_CREATE_SPACE
481
- // AUTO_GRADING_PLANS.AUTO_GRADING_STANDARDS_BASED,
482
- ];
483
- var SCHOOL_STARTER = [
484
- FEEDBACK_PLANS.FEEDBACK_TRANSCRIPT,
485
- FEEDBACK_PLANS.FEEDBACK_SUMMARY,
486
- FEEDBACK_PLANS.FEEDBACK_GRAMMAR_INSIGHTS,
487
- FEEDBACK_PLANS.FEEDBACK_SUGGESTED_RESPONSE,
488
- FEEDBACK_PLANS.FEEDBACK_RUBRIC,
489
- FEEDBACK_PLANS.FEEDBACK_GRADING_STANDARDS,
490
- FEEDBACK_PLANS.FEEDBACK_DISABLE_ALLOW_RETRIES,
491
- FEEDBACK_PLANS.FEEDBACK_TARGET_LANGUAGE,
492
- AUTO_GRADING_PLANS.AUTO_GRADING_PASS_FAIL,
493
- AUTO_GRADING_PLANS.AUTO_GRADING_RUBRICS,
494
- AUTO_GRADING_PLANS.AUTO_GRADING_STANDARDS_BASED,
495
- AI_ASSISTANT_PLANS.AI_ASSISTANT_DOCUMENT_UPLOADS,
496
- AI_ASSISTANT_PLANS.AI_ASSISTANT_UNLIMITED_USE,
497
- // ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS,
498
- ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK,
499
- ANALYTICS_PLANS.ANALYTICS_GRADEBOOK,
500
- ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS,
501
- ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS,
502
- // ANALYTICS_PLANS.ANALYTICS_ORGANIZATION,
503
- SPACES_PLANS.SPACES_CREATE_SPACE,
504
- SPACES_PLANS.SPACES_CHECK_POINTS,
505
- // DISCOVER_PLANS.DISCOVER_ORGANIZATION_LIBRARY,
506
- MEDIA_AREA_PLANS.MEDIA_AREA_DOCUMENT_UPLOAD,
507
- MEDIA_AREA_PLANS.MEDIA_AREA_AUDIO_FILES
508
- ];
509
- var ORGANIZATION_PLAN = [
510
- FEEDBACK_PLANS.FEEDBACK_TRANSCRIPT,
511
- FEEDBACK_PLANS.FEEDBACK_SUMMARY,
512
- FEEDBACK_PLANS.FEEDBACK_GRAMMAR_INSIGHTS,
513
- FEEDBACK_PLANS.FEEDBACK_SUGGESTED_RESPONSE,
514
- FEEDBACK_PLANS.FEEDBACK_RUBRIC,
515
- FEEDBACK_PLANS.FEEDBACK_GRADING_STANDARDS,
516
- FEEDBACK_PLANS.FEEDBACK_DISABLE_ALLOW_RETRIES,
517
- FEEDBACK_PLANS.FEEDBACK_TARGET_LANGUAGE,
518
- AUTO_GRADING_PLANS.AUTO_GRADING_PASS_FAIL,
519
- AUTO_GRADING_PLANS.AUTO_GRADING_RUBRICS,
520
- AUTO_GRADING_PLANS.AUTO_GRADING_STANDARDS_BASED,
521
- AI_ASSISTANT_PLANS.AI_ASSISTANT_DOCUMENT_UPLOADS,
522
- AI_ASSISTANT_PLANS.AI_ASSISTANT_UNLIMITED_USE,
523
- ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS,
524
- ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK,
525
- ANALYTICS_PLANS.ANALYTICS_GRADEBOOK,
526
- ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS,
527
- ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS,
528
- ANALYTICS_PLANS.ANALYTICS_ORGANIZATION,
529
- SPACES_PLANS.SPACES_CREATE_SPACE,
530
- SPACES_PLANS.SPACES_CHECK_POINTS,
531
- DISCOVER_PLANS.DISCOVER_ORGANIZATION_LIBRARY,
532
- MEDIA_AREA_PLANS.MEDIA_AREA_DOCUMENT_UPLOAD,
533
- MEDIA_AREA_PLANS.MEDIA_AREA_AUDIO_FILES
534
- ];
535
- var SpeakablePlanTypes = {
536
- basic: "basic",
537
- teacher_pro: "teacher_pro",
538
- school_starter: "school_starter",
539
- organization: "organization",
540
- // OLD PLANS
541
- starter: "starter",
542
- growth: "growth",
543
- professional: "professional"
544
- };
545
- var SpeakablePermissionsMap = {
546
- [SpeakablePlanTypes.basic]: FREE_PLAN,
547
- [SpeakablePlanTypes.starter]: TEACHER_PRO_PLAN,
548
- [SpeakablePlanTypes.teacher_pro]: TEACHER_PRO_PLAN,
549
- [SpeakablePlanTypes.growth]: ORGANIZATION_PLAN,
550
- [SpeakablePlanTypes.professional]: ORGANIZATION_PLAN,
551
- [SpeakablePlanTypes.organization]: ORGANIZATION_PLAN,
552
- [SpeakablePlanTypes.school_starter]: SCHOOL_STARTER
553
- };
554
- var SpeakablePlanHierarchy = [
555
- SpeakablePlanTypes.basic,
556
- SpeakablePlanTypes.starter,
557
- SpeakablePlanTypes.teacher_pro,
558
- SpeakablePlanTypes.growth,
559
- SpeakablePlanTypes.professional,
560
- SpeakablePlanTypes.school_starter,
561
- SpeakablePlanTypes.organization
562
- ];
563
-
564
- // src/hooks/usePermissions.ts
565
- var usePermissions = () => {
566
- const { permissions } = useSpeakableApi();
567
- const has = (permission) => {
568
- var _a;
569
- return (_a = permissions.permissions) == null ? void 0 : _a.includes(permission);
570
- };
571
- return {
572
- plan: permissions.plan,
573
- permissionsLoaded: permissions.loaded,
574
- isStripePlan: permissions.isStripePlan,
575
- refreshDate: permissions.refreshDate,
576
- isInstitutionPlan: permissions.isInstitutionPlan,
577
- subscriptionId: permissions.subscriptionId,
578
- contact: permissions.contact,
579
- hasGradebook: has(ANALYTICS_PLANS.ANALYTICS_GRADEBOOK),
580
- hasGoogleClassroomGradePassback: has(ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK),
581
- hasAssessments: has(ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS),
582
- hasSectionAnalytics: has(ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS),
583
- hasStudentReports: has(ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS),
584
- permissions: permissions || [],
585
- hasStudentPortfolios: permissions.hasStudentPortfolios,
586
- isFreeOrgTrial: permissions.type === "free_org_trial",
587
- freeOrgTrialExpired: permissions.freeOrgTrialExpired
588
- };
589
- };
590
- var usePermissions_default = usePermissions;
591
-
592
- // src/domains/notification/notification.constants.ts
593
- var SPEAKABLE_NOTIFICATIONS = {
594
- NEW_ASSIGNMENT: "new_assignment",
595
- ASSESSMENT_SUBMITTED: "assessment_submitted",
596
- ASSESSMENT_SCORED: "assessment_scored",
597
- NEW_COMMENT: "NEW_COMMENT"
598
- };
599
- var SpeakableNotificationTypes = {
600
- NEW_ASSIGNMENT: "NEW_ASSIGNMENT",
601
- FEEDBACK_FROM_TEACHER: "FEEDBACK_FROM_TEACHER",
602
- MESSAGE_FROM_STUDENT: "MESSAGE_FROM_STUDENT",
603
- PHRASE_MARKED_CORRECT: "PHRASE_MARKED_CORRECT",
604
- STUDENT_PROGRESS: "STUDENT_PROGRESS",
605
- PLAYLIST_FOLLOWERS: "PLAYLIST_FOLLOWERS",
606
- PLAYLIST_PLAYS: "PLAYLIST_PLAYS",
607
- // New notifications
608
- ASSESSMENT_SUBMITTED: "ASSESSMENT_SUBMITTED",
609
- // Notification FOR TEACHER when student submits assessment
610
- ASSESSMENT_SCORED: "ASSESSMENT_SCORED",
611
- // Notification FOR STUDENT when teacher scores assessment
612
- // Comment
613
- NEW_COMMENT: "NEW_COMMENT"
614
- };
615
-
616
- // src/domains/notification/services/create-notification.service.ts
617
- import dayjs2 from "dayjs";
618
-
619
- // src/constants/web.constants.ts
620
- var WEB_BASE_URL = "https://app.speakable.io";
621
-
622
- // src/domains/notification/services/send-notification.service.ts
623
- var _sendNotification = async (sendTo, notification) => {
624
- var _a, _b, _c;
625
- const results = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "createNotificationV2")) == null ? void 0 : _c({
626
- sendTo,
627
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
628
- notification
629
- }));
630
- return results;
631
- };
632
- var sendNotification = withErrorHandler(_sendNotification, "sendNotification");
633
-
634
- // src/domains/notification/services/create-notification.service.ts
635
- var createNotification = async ({
636
- data,
637
- type,
638
- userId,
639
- profile
640
- }) => {
641
- let result;
642
- switch (type) {
643
- case SPEAKABLE_NOTIFICATIONS.NEW_ASSIGNMENT:
644
- result = await handleAssignNotifPromise({ data, profile });
645
- break;
646
- case SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SUBMITTED:
647
- result = await createAssessmentSubmissionNotification({
648
- data,
649
- profile,
650
- userId
651
- });
652
- break;
653
- case SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SCORED:
654
- result = await createAssessmentScoredNotification({
655
- data,
656
- profile
657
- });
658
- break;
659
- default:
660
- result = null;
661
- break;
662
- }
663
- return result;
664
- };
665
- var handleAssignNotifPromise = async ({
666
- data: assignments,
667
- profile
668
- }) => {
669
- if (!assignments.length) return;
670
- try {
671
- const notifsPromises = assignments.map(async (assignment) => {
672
- const {
673
- section,
674
- section: { members },
675
- ...rest
676
- } = assignment;
677
- if (!section || !members) throw new Error("Invalid assignment data");
678
- const data = { section, sendTo: members, assignment: { ...rest } };
679
- return createNewAssignmentNotification({ data, profile });
680
- });
681
- await Promise.all(notifsPromises);
682
- return {
683
- success: true,
684
- message: "Assignment notifications sent successfully"
685
- };
686
- } catch (error) {
687
- console.error("Error in handleAssignNotifPromise:", error);
688
- throw error;
689
- }
690
- };
691
- var createNewAssignmentNotification = async ({
692
- data,
693
- profile
694
- }) => {
695
- var _a;
696
- const { assignment, sendTo } = data;
697
- const teacherName = profile.displayName || "Your teacher";
698
- const dueDate = assignment.dueDateTimestamp ? dayjs2(assignment.dueDateTimestamp.toDate()).format("MMM Do") : null;
699
- const results = await sendNotification(sendTo, {
700
- courseId: assignment.courseId,
701
- type: SPEAKABLE_NOTIFICATIONS.NEW_ASSIGNMENT,
702
- senderName: teacherName,
703
- link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
704
- messagePreview: `A new assignment "${assignment.name}" is now available. ${dueDate ? `Due ${dueDate}` : ""}`,
705
- title: "New Assignment Available!",
706
- imageUrl: (_a = profile.image) == null ? void 0 : _a.url
707
- });
708
- return results;
709
- };
710
- var createAssessmentSubmissionNotification = async ({
711
- data: assignment,
712
- profile,
713
- userId
714
- }) => {
715
- var _a;
716
- const studentName = profile.displayName || "Your student";
717
- const results = await sendNotification(assignment.owners, {
718
- courseId: assignment.courseId,
719
- type: SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SUBMITTED,
720
- link: `${WEB_BASE_URL}/a/${assignment.id}?studentId=${userId}`,
721
- title: `Assessment Submitted!`,
722
- senderName: studentName,
723
- messagePreview: `${studentName} has submitted the assessment "${assignment.name}"`,
724
- imageUrl: (_a = profile.image) == null ? void 0 : _a.url
725
- });
726
- return results;
727
- };
728
- var createAssessmentScoredNotification = async ({
729
- data,
730
- profile
731
- }) => {
732
- var _a, _b, _c, _d, _e;
733
- const { assignment, sendTo } = data;
734
- const teacherName = profile.displayName || "Your teacher";
735
- const title = `${assignment.isAssessment ? "Assessment" : "Assignment"} Reviewed!`;
736
- const messagePreview = `Your ${assignment.isAssessment ? "assessment" : "assignment"} has been reviewed by your teacher. Click to view the feedback.`;
737
- const results = await sendNotification(sendTo, {
738
- courseId: assignment.courseId,
739
- type: SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SCORED,
740
- link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
741
- title,
742
- messagePreview,
743
- imageUrl: (_a = profile.image) == null ? void 0 : _a.url,
744
- senderName: teacherName
745
- });
746
- await ((_e = (_c = (_b = api).httpsCallable) == null ? void 0 : _c.call(_b, "sendAssessmentScoredEmail")) == null ? void 0 : _e({
747
- assessmentTitle: assignment.name,
748
- link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
749
- senderImage: ((_d = profile.image) == null ? void 0 : _d.url) || "",
750
- studentId: sendTo[0],
751
- teacherName: profile.displayName
752
- }));
753
- return results;
754
- };
755
-
756
- // src/domains/notification/hooks/notification.hooks.ts
757
- var notificationQueryKeys = {
758
- all: ["notifications"],
759
- byId: (id) => [...notificationQueryKeys.all, id]
760
- };
761
- var useCreateNotification = () => {
762
- const { user, queryClient } = useSpeakableApi();
763
- const handleCreateNotifications = async (type, data) => {
764
- var _a, _b;
765
- const result = await createNotification({
766
- type,
767
- userId: user.auth.uid,
768
- profile: (_a = user == null ? void 0 : user.profile) != null ? _a : {},
769
- data
770
- });
771
- queryClient.invalidateQueries({
772
- queryKey: notificationQueryKeys.byId((_b = user == null ? void 0 : user.auth.uid) != null ? _b : "")
773
- });
774
- return result;
775
- };
776
- return {
777
- createNotification: handleCreateNotifications
778
- };
779
- };
780
-
781
- // src/hooks/useGoogleClassroom.ts
782
- var useGoogleClassroom = () => {
783
- const submitAssignmentToGoogleClassroom = async ({
784
- assignment,
785
- scores,
786
- googleUserId = null
787
- // optional to override the user's googleUserId
788
- }) => {
789
- var _a, _b, _c;
790
- try {
791
- const { googleClassroomUserId = null } = scores;
792
- const googleId = googleUserId || googleClassroomUserId;
793
- if (!googleId)
794
- return {
795
- error: true,
796
- message: "No Google Classroom ID found"
797
- };
798
- const { courseWorkId, maxPoints, owners, courseId } = assignment;
799
- const draftGrade = (scores == null ? void 0 : scores.score) ? (scores == null ? void 0 : scores.score) / 100 * maxPoints : 0;
800
- const result = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssignmentToGoogleClassroomV2")) == null ? void 0 : _c({
801
- teacherId: owners[0],
802
- courseId,
803
- courseWorkId,
804
- userId: googleId,
805
- draftGrade
806
- }));
807
- return result;
808
- } catch (error) {
809
- return { error: true, message: error.message };
810
- }
811
- };
812
- return {
813
- submitAssignmentToGoogleClassroom
814
- };
815
- };
816
-
817
- // src/lib/firebase/firebase-analytics/grading-standard.ts
818
- var logGradingStandardLog = (data) => {
819
- var _a, _b, _c;
820
- if (data.courseId && data.type && data.level) {
821
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
822
- eventType: data.type || "custom",
823
- level: data.level,
824
- courseId: data.courseId
825
- });
826
- }
827
- api.logEvent("logGradingStandard", data);
828
- };
829
-
830
- // src/constants/analytics.constants.ts
831
- var SPEAKABLE_ANALYTICS = {
832
- VOICE_SUCCESS: "voice_success",
833
- VOICE_FALLBACK_SUCCESS: "voice_fallback_success",
834
- VOICE_FALLBACK_FAIL: "voice_fallback_fail",
835
- VOICE_FAIL: "voice_fail",
836
- RESPOND_CARD_SUCCESS: "respond_card_success",
837
- RESPOND_CARD_FAIL: "respond_card_fail",
838
- RESPOND_WRITE_CARD_SUCCESS: "respond_write_card_success",
839
- RESPOND_WRITE_CARD_FAIL: "respond_write_card_fail",
840
- RESPOND_WRITE_CARD_SUBMITTED: "respond_write_card_submitted",
841
- RESPOND_WRITE_CARD_ERROR: "respond_write_card_error",
842
- RESPOND_CARD_ERROR: "respond_card_error",
843
- RESPOND_CARD_SUBMITTED: "respond_card_submitted",
844
- RESPOND_FREE_PLAN: "respond_free_plan",
845
- RESPOND_WRITE_FREE_PLAN: "respond_write_free_plan",
846
- SUBMISSION: "assignment_submitted",
847
- ASSIGNMENT_STARTED: "assignment_started",
848
- CREATE_ASSIGNMENT: "create_assignment",
849
- MC_SUCCESS: "multiple_choice_success",
850
- MC_FAIL: "multiple_choice_fail",
851
- MC_ERROR: "multiple_choice_error",
852
- ACTFL_LEVEL: "actfl_level",
853
- WIDA_LEVEL: "wida_level",
854
- // New events
855
- VIEW_SCORES_MODAL: "view_scores_modal",
856
- SHORT_ANSWER_SUCCESS: "short_answer_success",
857
- SHORT_ANSWER_FAIL: "short_answer_fail",
858
- SHORT_ANSWER_ERROR: "short_answer_error",
859
- RETRY: "retry",
860
- MESSAGE_SENT: "message_sent",
861
- MESSAGE_ERROR: "message_error",
862
- VIEW_DETAILS_CLICK: "view_details_click",
863
- TABS_CLICK: "tabs_click",
864
- VIEW_MEDIA: "view_media",
865
- VIEW_SCORES: "view_scores",
866
- VIEW_GRADING_METHOD: "view_grading_method",
867
- VIEW_FEEDBACK: "view_feedback"
868
- };
869
-
870
- // src/lib/firebase/firebase-analytics/assignment.ts
871
- var logOpenAssignment = (data = {}) => {
872
- api.logEvent("open_assignment", data);
873
- };
874
- var logOpenActivityPreview = (data = {}) => {
875
- api.logEvent("open_activity_preview", data);
876
- };
877
- var logSubmitAssignment = (data = {}) => {
878
- var _a, _b, _c;
879
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
880
- eventType: SPEAKABLE_ANALYTICS.SUBMISSION,
881
- ...data
882
- });
883
- api.logEvent(SPEAKABLE_ANALYTICS.SUBMISSION, data);
884
- };
885
- var logStartAssignment = (data = {}) => {
886
- var _a, _b, _c;
887
- if (data.courseId) {
888
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
889
- eventType: SPEAKABLE_ANALYTICS.ASSIGNMENT_STARTED,
890
- ...data
891
- });
892
- }
893
- api.logEvent(SPEAKABLE_ANALYTICS.ASSIGNMENT_STARTED, data);
894
- };
895
-
896
- // src/domains/assignment/utils/create-default-score.ts
897
- var defaultScore = (props) => {
898
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
899
- const score = {
900
- progress: 0,
901
- score: 0,
902
- startDate: serverTimestamp2(),
903
- status: "IN_PROGRESS",
904
- submitted: false,
905
- cards: {},
906
- lastPlayed: serverTimestamp2(),
907
- owners: props.owners,
908
- userId: props.userId
909
- };
910
- if (props.googleClassroomUserId) {
911
- score.googleClassroomUserId = props.googleClassroomUserId;
912
- }
913
- if (props.courseId) {
914
- score.courseId = props.courseId;
915
- }
916
- return score;
917
- };
918
-
919
- // src/domains/assignment/score-practice.constants.ts
920
- var SCORES_PRACTICE_COLLECTION = "users";
921
- var SCORES_PRACTICE_SUBCOLLECTION = "practice";
922
- var refsScoresPractice = {
923
- practiceScores: (params) => `${SCORES_PRACTICE_COLLECTION}/${params.userId}/${SCORES_PRACTICE_SUBCOLLECTION}/${params.setId}`,
924
- practiceScoreHistoryRefDoc: (params) => `${SCORES_PRACTICE_COLLECTION}/${params.userId}/${SCORES_PRACTICE_SUBCOLLECTION}/${params.setId}/attempts/${params.date}`
925
- };
926
-
927
- // src/domains/assignment/services/create-score.service.ts
928
- var _updateAssignmentGradebookStatus = async ({
929
- assignmentId,
930
- userId,
931
- status,
932
- score
933
- }) => {
934
- var _a, _b, _c;
935
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "updateAssignmentGradebookStatus")) == null ? void 0 : _c({
936
- assignmentId,
937
- userId,
938
- status,
939
- score
940
- }));
941
- };
942
- var updateAssignmentGradebookStatus = withErrorHandler(
943
- _updateAssignmentGradebookStatus,
944
- "updateAssignmentGradebookStatus"
945
- );
946
- async function _createScore(params) {
947
- var _a, _b, _c;
948
- if (params.isAssignment) {
949
- const ref = refsAssignmentFiresotre.assignmentScores({
950
- id: params.activityId,
951
- userId: params.userId
952
- });
953
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "updateAssignmentGradebookStatus")) == null ? void 0 : _c({
954
- assignmentId: params.activityId,
955
- userId: params.userId,
956
- status: "IN_PROGRESS",
957
- score: null
958
- }));
959
- await api.setDoc(ref, params.scoreData, { merge: true });
960
- await updateAssignmentGradebookStatus({
961
- assignmentId: params.activityId,
962
- userId: params.userId,
963
- status: "IN_PROGRESS",
964
- score: null
965
- });
966
- return {
967
- id: params.userId
968
- };
969
- } else {
970
- const ref = refsScoresPractice.practiceScores({
971
- userId: params.userId,
972
- setId: params.activityId
973
- });
974
- await api.setDoc(ref, params.scoreData);
975
- return {
976
- id: params.userId
977
- };
978
- }
979
- }
980
- var createScore = withErrorHandler(_createScore, "createScore");
981
-
982
- // src/domains/assignment/services/get-score.service.ts
983
- async function getAssignmentScore({
984
- userId,
985
- assignment,
986
- googleClassroomUserId
987
- }) {
988
- const path = refsAssignmentFiresotre.assignmentScores({
989
- id: assignment.id,
990
- userId
991
- });
992
- const response = await api.getDoc(path);
993
- if (response.data == null) {
994
- const newScore = {
995
- ...defaultScore({
996
- owners: [userId],
997
- userId,
998
- courseId: assignment.courseId,
999
- googleClassroomUserId
1000
- }),
1001
- assignmentId: assignment.id
1002
- };
1003
- logStartAssignment({
1004
- courseId: assignment.courseId
1005
- });
1006
- const result = await createScore({
1007
- activityId: assignment.id,
1008
- userId,
1009
- isAssignment: true,
1010
- scoreData: newScore
1011
- });
1012
- return {
1013
- ...newScore,
1014
- id: result.id
1015
- };
1016
- }
1017
- return response.data;
1018
- }
1019
- async function getPracticeScore({ userId, setId }) {
1020
- const path = refsScoresPractice.practiceScores({ userId, setId });
1021
- const response = await api.getDoc(path);
1022
- if (response.data == null) {
1023
- const newScore = {
1024
- ...defaultScore({
1025
- owners: [userId],
1026
- userId
1027
- }),
1028
- setId
1029
- };
1030
- const result = await createScore({
1031
- activityId: setId,
1032
- userId,
1033
- isAssignment: false,
1034
- scoreData: newScore
1035
- });
1036
- return {
1037
- ...newScore,
1038
- id: result.id
1039
- };
1040
- }
1041
- return response.data;
1042
- }
1043
- async function _getScore(params) {
1044
- if (params.isAssignment) {
1045
- return await getAssignmentScore({
1046
- userId: params.userId,
1047
- assignment: {
1048
- id: params.activityId,
1049
- courseId: params.courseId
1050
- },
1051
- googleClassroomUserId: params.googleClassroomUserId
1052
- });
1053
- } else {
1054
- return await getPracticeScore({
1055
- userId: params.userId,
1056
- setId: params.activityId
1057
- });
1058
- }
1059
- }
1060
- var getScore = withErrorHandler(_getScore, "getScore");
1061
-
1062
- // src/domains/assignment/utils/calculateScoreAndProgress.ts
1063
- var calculateScoreAndProgress = (scores, cardsList, weights) => {
1064
- const filteredScoreCards = Object.keys((scores == null ? void 0 : scores.cards) || {}).reduce(
1065
- (acc, cardId) => {
1066
- var _a;
1067
- const cardScores = (_a = scores == null ? void 0 : scores.cards) == null ? void 0 : _a[cardId];
1068
- if (cardScores && !cardScores.media_area_opened) {
1069
- acc[cardId] = cardScores;
1070
- }
1071
- return acc;
1072
- },
1073
- {}
1074
- );
1075
- const totalSetPoints = cardsList.reduce((acc, cardId) => {
1076
- acc += (weights == null ? void 0 : weights[cardId]) || 1;
1077
- return acc;
1078
- }, 0);
1079
- const totalPointsAwarded = Object.keys(filteredScoreCards).reduce((acc, cardId) => {
1080
- var _a;
1081
- const cardScores = filteredScoreCards[cardId];
1082
- if ((cardScores == null ? void 0 : cardScores.completed) || (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0) {
1083
- const score2 = (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0 ? Number((_a = cardScores == null ? void 0 : cardScores.score) != null ? _a : 0) : null;
1084
- const weight = (weights == null ? void 0 : weights[cardId]) || 1;
1085
- const fraction = (score2 != null ? score2 : 0) / 100;
1086
- if (score2 || score2 === 0) {
1087
- acc += weight * fraction;
1088
- } else {
1089
- acc += weight;
1090
- }
1091
- }
1092
- return acc;
1093
- }, 0);
1094
- const totalCompletedCards = Object.keys(filteredScoreCards).reduce((acc, cardId) => {
1095
- const cardScores = filteredScoreCards[cardId];
1096
- if ((cardScores == null ? void 0 : cardScores.completed) || (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0) {
1097
- acc += 1;
1098
- }
1099
- return acc;
1100
- }, 0);
1101
- const percent = totalPointsAwarded / totalSetPoints;
1102
- const score = Math.round(percent * 100);
1103
- const progress = Math.round(totalCompletedCards / (cardsList.length || 1) * 100);
1104
- return { score, progress };
1105
- };
1106
- var calculateScoreAndProgress_default = calculateScoreAndProgress;
1107
-
1108
- // src/domains/assignment/services/update-score.service.ts
1109
- async function _updateScore(params) {
1110
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1111
- id: params.activityId,
1112
- userId: params.userId
1113
- }) : refsScoresPractice.practiceScores({
1114
- setId: params.activityId,
1115
- userId: params.userId
1116
- });
1117
- await api.updateDoc(path, {
1118
- ...params.data
1119
- });
1120
- }
1121
- var updateScore = withErrorHandler(_updateScore, "updateScore");
1122
- async function _updateCardScore(params) {
1123
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1124
- id: params.activityId,
1125
- userId: params.userId
1126
- }) : refsScoresPractice.practiceScores({
1127
- setId: params.activityId,
1128
- userId: params.userId
1129
- });
1130
- const updates = Object.keys(params.updates.cardScore).reduce(
1131
- (acc, key) => {
1132
- acc[`cards.${params.cardId}.${key}`] = params.updates.cardScore[key];
1133
- return acc;
1134
- },
1135
- {}
1136
- );
1137
- if (params.updates.progress) {
1138
- updates.progress = params.updates.progress;
1139
- }
1140
- if (params.updates.score) {
1141
- updates.score = params.updates.score;
1142
- }
1143
- await api.updateDoc(path, {
1144
- ...updates
1145
- });
1146
- }
1147
- var updateCardScore = withErrorHandler(_updateCardScore, "updateCardScore");
1148
-
1149
- // src/domains/assignment/services/clear-score.service.ts
1150
- import dayjs3 from "dayjs";
1151
- async function clearScore(params) {
1152
- var _a, _b, _c, _d, _e;
1153
- const update = {
1154
- [`cards.${params.cardId}`]: {
1155
- attempts: ((_a = params.cardScores.attempts) != null ? _a : 1) + 1,
1156
- correct: (_b = params.cardScores.correct) != null ? _b : 0,
1157
- // save old score history
1158
- history: [
1159
- {
1160
- ...params.cardScores,
1161
- attempts: (_c = params.cardScores.attempts) != null ? _c : 1,
1162
- correct: (_d = params.cardScores.correct) != null ? _d : 0,
1163
- retryTime: dayjs3().format("YYYY-MM-DD HH:mm:ss"),
1164
- history: null
1165
- },
1166
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1167
- ...(_e = params.cardScores.history) != null ? _e : []
1168
- ]
1169
- }
1170
- };
1171
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1172
- id: params.activityId,
1173
- userId: params.userId
1174
- }) : refsScoresPractice.practiceScores({
1175
- setId: params.activityId,
1176
- userId: params.userId
1177
- });
1178
- await api.updateDoc(path, update);
1179
- return {
1180
- update,
1181
- activityId: params.activityId
1182
- };
1183
- }
1184
- async function clearScoreV2(params) {
1185
- var _a, _b, _c, _d, _e;
1186
- const update = {
1187
- [`cards.${params.cardId}`]: {
1188
- ...params.cardScores,
1189
- attempts: ((_a = params.cardScores.attempts) != null ? _a : 1) + 1,
1190
- correct: (_b = params.cardScores.correct) != null ? _b : 0,
1191
- history: [
1192
- {
1193
- ...params.cardScores,
1194
- attempts: (_c = params.cardScores.attempts) != null ? _c : 1,
1195
- correct: (_d = params.cardScores.correct) != null ? _d : 0,
1196
- retryTime: dayjs3().format("YYYY-MM-DD HH:mm:ss"),
1197
- history: null
1198
- },
1199
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1200
- ...(_e = params.cardScores.history) != null ? _e : []
1201
- ]
1202
- }
1203
- };
1204
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1205
- id: params.activityId,
1206
- userId: params.userId
1207
- }) : refsScoresPractice.practiceScores({
1208
- setId: params.activityId,
1209
- userId: params.userId
1210
- });
1211
- await api.updateDoc(path, update);
1212
- return {
1213
- update,
1214
- activityId: params.activityId
1215
- };
1216
- }
1217
-
1218
- // src/domains/assignment/services/submit-assignment-score.service.ts
1219
- import dayjs4 from "dayjs";
1220
- async function _submitAssignmentScore({
1221
- assignment,
1222
- userId,
1223
- status,
1224
- studentName
1225
- }) {
1226
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1227
- const path = refsAssignmentFiresotre.assignmentScores({ id: assignment.id, userId });
1228
- const fieldsUpdated = {
1229
- submitted: true,
1230
- progress: 100,
1231
- submissionDate: serverTimestamp2(),
1232
- status
1233
- };
1234
- if (assignment.isAssessment) {
1235
- const result = await handleAssessment(assignment, userId, fieldsUpdated, studentName);
1236
- return result;
1237
- } else if (assignment.courseId) {
1238
- await handleCourseAssignment(assignment, userId);
1239
- }
1240
- await api.updateDoc(path, { ...fieldsUpdated });
1241
- return { success: true, fieldsUpdated };
1242
- }
1243
- var submitAssignmentScore = withErrorHandler(
1244
- _submitAssignmentScore,
1245
- "submitAssignmentScore"
1246
- );
1247
- async function handleAssessment(assignment, userId, fieldsUpdated, studentName) {
1248
- var _a, _b, _c;
1249
- const path = refsAssignmentFiresotre.assignmentScores({ id: assignment.id, userId });
1250
- const response = await api.getDoc(path);
1251
- if (!response.data) {
1252
- throw new Error("Score not found");
1253
- }
1254
- await api.updateDoc(path, { status: "PENDING_REVIEW" });
1255
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssessment")) == null ? void 0 : _c({
1256
- assignmentId: assignment.id,
1257
- assignmentTitle: assignment.name,
1258
- userId,
1259
- teacherId: assignment.owners[0],
1260
- studentName
1261
- }));
1262
- fieldsUpdated.status = "PENDING_REVIEW";
1263
- return { success: true, fieldsUpdated };
1264
- }
1265
- async function handleCourseAssignment(assignment, userId) {
1266
- var _a, _b, _c;
1267
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssignmentV2")) == null ? void 0 : _c({
1268
- assignmentId: assignment.id,
1269
- userId
1270
- }));
1271
- }
1272
- async function submitPracticeScore({
1273
- setId,
1274
- userId,
1275
- scores
1276
- }) {
1277
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1278
- const date = dayjs4().format("YYYY-MM-DD-HH-mm");
1279
- const ref = refsScoresPractice.practiceScoreHistoryRefDoc({ setId, userId, date });
1280
- const fieldsUpdated = {
1281
- ...scores,
1282
- submitted: true,
1283
- progress: 100,
1284
- submissionDate: serverTimestamp2(),
1285
- status: "SUBMITTED"
1286
- };
1287
- await api.setDoc(ref, { ...fieldsUpdated });
1288
- const refScores = refsScoresPractice.practiceScores({ userId, setId });
1289
- await api.deleteDoc(refScores);
1290
- return { success: true, fieldsUpdated };
1291
- }
1292
-
1293
- // src/domains/assignment/hooks/score-hooks.ts
1294
- var scoreQueryKeys = {
1295
- all: ["scores"],
1296
- byId: (id) => [...scoreQueryKeys.all, id],
1297
- list: () => [...scoreQueryKeys.all, "list"]
1298
- };
1299
- function useScore({
1300
- isAssignment,
1301
- activityId,
1302
- userId = "",
1303
- courseId,
1304
- enabled = true,
1305
- googleClassroomUserId
1306
- }) {
1307
- return useQuery2({
1308
- queryFn: () => getScore({
1309
- userId,
1310
- courseId,
1311
- activityId,
1312
- googleClassroomUserId,
1313
- isAssignment
1314
- }),
1315
- queryKey: scoreQueryKeys.byId(activityId),
1316
- enabled
1317
- });
1318
- }
1319
- var debounceUpdateScore = debounce(updateScore, 500);
1320
- function useUpdateScore() {
1321
- const { queryClient } = useSpeakableApi();
1322
- const mutation = useMutation({
1323
- mutationFn: debounceUpdateScore,
1324
- onMutate: (variables) => {
1325
- return handleOptimisticUpdate({
1326
- queryClient,
1327
- queryKey: scoreQueryKeys.byId(variables.activityId),
1328
- newData: variables.data
1329
- });
1330
- },
1331
- onError: (_, variables, context) => {
1332
- if (context == null ? void 0 : context.previousData)
1333
- queryClient.setQueryData(scoreQueryKeys.byId(variables.activityId), context.previousData);
1334
- },
1335
- onSettled: (_, err, variables) => {
1336
- queryClient.invalidateQueries({
1337
- queryKey: scoreQueryKeys.byId(variables.activityId)
1338
- });
1339
- }
1340
- });
1341
- return {
1342
- mutationUpdateScore: mutation
1343
- };
1344
- }
1345
- function useUpdateCardScore({
1346
- isAssignment,
1347
- activityId,
1348
- userId,
1349
- cardIds,
1350
- weights
1351
- }) {
1352
- const { queryClient } = useSpeakableApi();
1353
- const queryKey = scoreQueryKeys.byId(activityId);
1354
- const mutation = useMutation({
1355
- mutationFn: async ({ cardId, cardScore }) => {
1356
- const previousScores = queryClient.getQueryData(queryKey);
1357
- const { progress, score, newScoreUpdated, updatedCardScore } = getScoreUpdated({
1358
- previousScores: previousScores != null ? previousScores : {},
1359
- cardId,
1360
- cardScore,
1361
- cardIds,
1362
- weights
1363
- });
1364
- await updateCardScore({
1365
- userId,
1366
- cardId,
1367
- isAssignment,
1368
- activityId,
1369
- updates: {
1370
- cardScore: updatedCardScore,
1371
- progress,
1372
- score
1373
- }
1374
- });
1375
- return { cardId, scoresUpdated: newScoreUpdated };
1376
- },
1377
- onMutate: ({ cardId, cardScore }) => {
1378
- const previousData = queryClient.getQueryData(queryKey);
1379
- queryClient.setQueryData(queryKey, (previousScore) => {
1380
- const updates = handleOptimisticScore({
1381
- score: previousScore,
1382
- cardId,
1383
- cardScore,
1384
- cardIds,
1385
- weights
1386
- });
1387
- return {
1388
- ...previousScore,
1389
- ...updates
1390
- };
1391
- });
1392
- return { previousData };
1393
- },
1394
- onError: (error, variables, context) => {
1395
- console.log("Error updating card score:", error.message);
1396
- if (context == null ? void 0 : context.previousData) {
1397
- queryClient.setQueryData(queryKey, context.previousData);
1398
- }
1399
- },
1400
- onSettled: () => {
1401
- queryClient.invalidateQueries({
1402
- queryKey
1403
- });
1404
- }
1405
- });
1406
- return {
1407
- mutationUpdateCardScore: mutation
1408
- };
1409
- }
1410
- var getScoreUpdated = ({
1411
- cardId,
1412
- cardScore,
1413
- previousScores,
1414
- cardIds,
1415
- weights
1416
- }) => {
1417
- var _a, _b;
1418
- const previousCard = (_a = previousScores.cards) == null ? void 0 : _a[cardId];
1419
- const newCardScore = {
1420
- ...previousCard != null ? previousCard : {},
1421
- ...cardScore
1422
- };
1423
- const newScores = {
1424
- ...previousScores,
1425
- cards: {
1426
- ...(_b = previousScores.cards) != null ? _b : {},
1427
- [cardId]: newCardScore
1428
- }
1429
- };
1430
- const { score, progress } = calculateScoreAndProgress_default(newScores, cardIds, weights);
1431
- return {
1432
- newScoreUpdated: newScores,
1433
- updatedCardScore: cardScore,
1434
- score,
1435
- progress
1436
- };
1437
- };
1438
- var handleOptimisticScore = ({
1439
- score,
1440
- cardId,
1441
- cardScore,
1442
- cardIds,
1443
- weights
1444
- }) => {
1445
- var _a;
1446
- let cards = { ...(_a = score == null ? void 0 : score.cards) != null ? _a : {} };
1447
- cards = {
1448
- ...cards,
1449
- [cardId]: {
1450
- ...cards[cardId],
1451
- ...cardScore
1452
- }
1453
- };
1454
- const { score: scoreValue, progress } = calculateScoreAndProgress_default(
1455
- // @ts-ignore
1456
- {
1457
- ...score != null ? score : {},
1458
- cards
1459
- },
1460
- cardIds,
1461
- weights
1462
- );
1463
- return { cards, score: scoreValue, progress };
1464
- };
1465
- function useClearScore() {
1466
- const { queryClient } = useSpeakableApi();
1467
- const mutation = useMutation({
1468
- mutationFn: clearScore,
1469
- onError: (error) => {
1470
- console.log("Error clearing score:", error.message);
1471
- },
1472
- onSettled: (result) => {
1473
- var _a;
1474
- queryClient.invalidateQueries({
1475
- queryKey: scoreQueryKeys.byId((_a = result == null ? void 0 : result.activityId) != null ? _a : "")
1476
- });
1477
- }
1478
- });
1479
- return {
1480
- mutationClearScore: mutation
1481
- };
1482
- }
1483
- function useClearScoreV2() {
1484
- const { queryClient } = useSpeakableApi();
1485
- const mutation = useMutation({
1486
- mutationFn: clearScoreV2,
1487
- onError: (error) => {
1488
- console.log("Error clearing score V2:", error.message);
1489
- },
1490
- onSettled: (result) => {
1491
- var _a;
1492
- queryClient.invalidateQueries({
1493
- queryKey: scoreQueryKeys.byId((_a = result == null ? void 0 : result.activityId) != null ? _a : "")
1494
- });
1495
- }
1496
- });
1497
- return {
1498
- mutationClearScore: mutation
1499
- };
1500
- }
1501
- function useSubmitAssignmentScore({
1502
- onAssignmentSubmitted,
1503
- studentName
1504
- }) {
1505
- const { queryClient } = useSpeakableApi();
1506
- const { hasGoogleClassroomGradePassback } = usePermissions_default();
1507
- const { submitAssignmentToGoogleClassroom } = useGoogleClassroom();
1508
- const { createNotification: createNotification2 } = useCreateNotification();
1509
- const mutation = useMutation({
1510
- mutationFn: async ({
1511
- assignment,
1512
- userId,
1513
- scores,
1514
- status
1515
- }) => {
1516
- try {
1517
- const scoreUpdated = await submitAssignmentScore({
1518
- assignment,
1519
- userId,
1520
- status,
1521
- studentName
1522
- });
1523
- if (assignment.courseWorkId != null && !assignment.isAssessment && hasGoogleClassroomGradePassback) {
1524
- await submitAssignmentToGoogleClassroom({
1525
- assignment,
1526
- scores
1527
- });
1528
- }
1529
- if (assignment.isAssessment) {
1530
- createNotification2(SpeakableNotificationTypes.ASSESSMENT_SUBMITTED, assignment);
1531
- }
1532
- if (assignment == null ? void 0 : assignment.id) {
1533
- logSubmitAssignment({
1534
- courseId: assignment == null ? void 0 : assignment.courseId
1535
- });
1536
- }
1537
- onAssignmentSubmitted(assignment.id);
1538
- queryClient.setQueryData(scoreQueryKeys.byId(assignment.id), {
1539
- ...scores,
1540
- ...scoreUpdated.fieldsUpdated
1541
- });
1542
- return {
1543
- success: true,
1544
- message: "Score submitted successfully"
1545
- };
1546
- } catch (error) {
1547
- return {
1548
- success: false,
1549
- error
1550
- };
1551
- }
1552
- }
1553
- });
1554
- return {
1555
- submitAssignmentScore: mutation.mutateAsync,
1556
- isLoading: mutation.isPending
1557
- };
1558
- }
1559
- function useSubmitPracticeScore() {
1560
- const { queryClient } = useSpeakableApi();
1561
- const mutation = useMutation({
1562
- mutationFn: async ({
1563
- setId,
1564
- userId,
1565
- scores
1566
- }) => {
1567
- try {
1568
- await submitPracticeScore({
1569
- setId,
1570
- userId,
1571
- scores
1572
- });
1573
- queryClient.invalidateQueries({
1574
- queryKey: scoreQueryKeys.byId(setId)
1575
- });
1576
- return {
1577
- success: true,
1578
- message: "Score submitted successfully"
1579
- };
1580
- } catch (error) {
1581
- return {
1582
- success: false,
1583
- error
1584
- };
1585
- }
1586
- }
1587
- });
1588
- return {
1589
- submitPracticeScore: mutation.mutateAsync,
1590
- isLoading: mutation.isPending
1591
- };
1592
- }
1593
-
1594
- // src/domains/cards/card.hooks.ts
1595
- import { useMutation as useMutation2, useQueries, useQuery as useQuery3 } from "@tanstack/react-query";
1596
- import { useMemo } from "react";
1597
-
1598
- // src/domains/cards/card.model.ts
1599
- var ConversationPageMode = /* @__PURE__ */ ((ConversationPageMode2) => {
1600
- ConversationPageMode2["VoiceAndText"] = "voice_and_text";
1601
- ConversationPageMode2["PhoneCall"] = "phone_call";
1602
- return ConversationPageMode2;
1603
- })(ConversationPageMode || {});
1604
- var ActivityPageType = /* @__PURE__ */ ((ActivityPageType2) => {
1605
- ActivityPageType2["READ_REPEAT"] = "READ_REPEAT";
1606
- ActivityPageType2["READ_RESPOND"] = "READ_RESPOND";
1607
- ActivityPageType2["FREE_RESPONSE"] = "FREE_RESPONSE";
1608
- ActivityPageType2["REPEAT"] = "REPEAT";
1609
- ActivityPageType2["RESPOND"] = "RESPOND";
1610
- ActivityPageType2["RESPOND_WRITE"] = "RESPOND_WRITE";
1611
- ActivityPageType2["MULTIPLE_CHOICE"] = "MULTIPLE_CHOICE";
1612
- ActivityPageType2["MEDIA_PAGE"] = "MEDIA_PAGE";
1613
- ActivityPageType2["SHORT_ANSWER"] = "SHORT_ANSWER";
1614
- ActivityPageType2["CONVERSATION"] = "CONVERSATION";
1615
- return ActivityPageType2;
1616
- })(ActivityPageType || {});
1617
- var RESPOND_PAGE_ACTIVITY_TYPES = [
1618
- "READ_RESPOND" /* READ_RESPOND */,
1619
- "RESPOND" /* RESPOND */,
1620
- "RESPOND_WRITE" /* RESPOND_WRITE */,
1621
- "FREE_RESPONSE" /* FREE_RESPONSE */
1622
- ];
1623
- var MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES = ["MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */];
1624
- var REPEAT_PAGE_ACTIVITY_TYPES = ["READ_REPEAT" /* READ_REPEAT */, "REPEAT" /* REPEAT */];
1625
- var RESPOND_WRITE_PAGE_ACTIVITY_TYPES = [
1626
- "RESPOND_WRITE" /* RESPOND_WRITE */,
1627
- "FREE_RESPONSE" /* FREE_RESPONSE */
1628
- ];
1629
- var RESPOND_AUDIO_PAGE_ACTIVITY_TYPES = [
1630
- "RESPOND" /* RESPOND */,
1631
- "READ_RESPOND" /* READ_RESPOND */
1632
- ];
1633
- var CONVERSATION_PAGE_ACTIVITY_TYPES = ["CONVERSATION" /* CONVERSATION */];
1634
-
1635
- // src/domains/cards/card.constants.ts
1636
- var FeedbackTypesCard = /* @__PURE__ */ ((FeedbackTypesCard2) => {
1637
- FeedbackTypesCard2["SuggestedResponse"] = "suggested_response";
1638
- FeedbackTypesCard2["Wida"] = "wida";
1639
- FeedbackTypesCard2["GrammarInsights"] = "grammar_insights";
1640
- FeedbackTypesCard2["Actfl"] = "actfl";
1641
- FeedbackTypesCard2["ProficiencyLevel"] = "proficiency_level";
1642
- return FeedbackTypesCard2;
1643
- })(FeedbackTypesCard || {});
1644
- var LeniencyCard = /* @__PURE__ */ ((LeniencyCard2) => {
1645
- LeniencyCard2["CONFIDENCE"] = "confidence";
1646
- LeniencyCard2["EASY"] = "easy";
1647
- LeniencyCard2["NORMAL"] = "normal";
1648
- LeniencyCard2["HARD"] = "hard";
1649
- return LeniencyCard2;
1650
- })(LeniencyCard || {});
1651
- var LENIENCY_OPTIONS = [
1652
- {
1653
- label: "Build Confidence - most lenient",
1654
- value: "confidence" /* CONFIDENCE */
1655
- },
1656
- {
1657
- label: "Very Lenient",
1658
- value: "easy" /* EASY */
1659
- },
1660
- {
1661
- label: "Normal",
1662
- value: "normal" /* NORMAL */
1663
- },
1664
- {
1665
- label: "No leniency - most strict",
1666
- value: "hard" /* HARD */
1667
- }
1668
- ];
1669
- var STUDENT_LEVELS_OPTIONS = [
1670
- {
1671
- label: "Beginner",
1672
- description: "Beginner Level: Just starting out. Can say a few basic words and phrases.",
1673
- value: "beginner"
1674
- },
1675
- {
1676
- label: "Elementary",
1677
- description: "Elementary Level: Can understand simple sentences and have very basic conversations.",
1678
- value: "elementary"
1679
- },
1680
- {
1681
- label: "Intermediate",
1682
- description: "Intermediate Level: Can talk about everyday topics and handle common situations.",
1683
- value: "intermediate"
1684
- },
1685
- {
1686
- label: "Advanced",
1687
- description: "Advanced Level: Can speak and understand with ease, and explain ideas clearly.",
1688
- value: "advanced"
1689
- },
1690
- {
1691
- label: "Fluent",
1692
- description: "Fluent Level: Speaks naturally and easily. Can use the language in work or school settings.",
1693
- value: "fluent"
1694
- },
1695
- {
1696
- label: "Native-like",
1697
- description: "Native-like Level: Understands and speaks like a native. Can discuss complex ideas accurately.",
1698
- value: "nativeLike"
1699
- }
1700
- ];
1701
- var BASE_RESPOND_FIELD_VALUES = {
1702
- title: "",
1703
- allowRetries: true,
1704
- respondTime: 180,
1705
- maxCharacters: 1e4
1706
- };
1707
- var BASE_REPEAT_FIELD_VALUES = {
1708
- repeat: 1
1709
- };
1710
- var BASE_MULTIPLE_CHOICE_FIELD_VALUES = {
1711
- MCQType: "single",
1712
- answer: ["A"],
1713
- choices: [
1714
- { option: "A", value: "Option A" },
1715
- { option: "B", value: "Option B" },
1716
- { option: "C", value: "Option C" }
1717
- ]
1718
- };
1719
- var VerificationCardStatus = /* @__PURE__ */ ((VerificationCardStatus2) => {
1720
- VerificationCardStatus2["VERIFIED"] = "VERIFIED";
1721
- VerificationCardStatus2["WARNING"] = "WARNING";
1722
- VerificationCardStatus2["NOT_RECOMMENDED"] = "NOT_RECOMMENDED";
1723
- VerificationCardStatus2["NOT_WORKING"] = "NOT_WORKING";
1724
- VerificationCardStatus2["NOT_CHECKED"] = "NOT_CHECKED";
1725
- return VerificationCardStatus2;
1726
- })(VerificationCardStatus || {});
1727
- var CARDS_COLLECTION = "flashcards";
1728
- var refsCardsFiresotre = {
1729
- allCards: CARDS_COLLECTION,
1730
- card: (id) => `${CARDS_COLLECTION}/${id}`
1731
- };
1732
-
1733
- // src/domains/cards/services/get-card.service.ts
1734
- async function _getCard(params) {
1735
- const ref = refsCardsFiresotre.card(params.cardId);
1736
- const response = await api.getDoc(ref);
1737
- if (!response.data) return null;
1738
- const type = response.data.type || "READ_REPEAT" /* READ_REPEAT */;
1739
- const cardsMapped = {
1740
- ...response.data,
1741
- type
1742
- };
1743
- return cardsMapped;
1744
- }
1745
- var getCard = withErrorHandler(_getCard, "getCard");
1746
-
1747
- // src/domains/cards/services/create-card.service.ts
1748
- import { v4 } from "uuid";
1749
-
1750
- // src/utils/text-utils.ts
1751
- import { sha1 } from "js-sha1";
1752
- var purify = (word) => {
1753
- return word.normalize("NFD").replace(/\/([^" "]*)/g, "").replace(/\([^()]*\)/g, "").replace(/([^()]*)/g, "").replace(/[\u0300-\u036f]/g, "").replace(/[-]/g, " ").replace(/[.,/#!¡¿?؟。,.?$%^&*;:{}=\-_`~()’'…\s]/g, "").replace(/\s\s+/g, " ").toLowerCase().trim();
1754
- };
1755
- var cleanString = (words) => {
1756
- const splitWords = words == null ? void 0 : words.split("+");
1757
- if (splitWords && splitWords.length === 1) {
1758
- const newWord = purify(words);
1759
- return newWord;
1760
- } else if (splitWords && splitWords.length > 1) {
1761
- const split = splitWords.map((w) => purify(w));
1762
- return split;
1763
- } else {
1764
- return "";
1765
- }
1766
- };
1767
- var getWordHash = (word, language) => {
1768
- const cleanedWord = cleanString(word);
1769
- const wordHash = sha1(`${language}-${cleanedWord}`);
1770
- console.log("wordHash core library", wordHash);
1771
- return wordHash;
1772
- };
1773
- function getPhraseLength(phrase, input) {
1774
- if (Array.isArray(phrase) && phrase.includes(input)) {
1775
- return phrase[phrase.indexOf(input)].split(" ").length;
1776
- } else {
1777
- return phrase ? phrase.split(" ").length : 0;
1778
- }
1779
- }
1780
-
1781
- // src/domains/cards/services/get-card-verification-status.service.ts
1782
- var charactarLanguages = ["zh", "ja", "ko"];
1783
- var getVerificationStatus = async (target_text, language) => {
1784
- if ((target_text == null ? void 0 : target_text.length) < 3 && !charactarLanguages.includes(language)) {
1785
- return "NOT_RECOMMENDED" /* NOT_RECOMMENDED */;
1786
- }
1787
- const hash = getWordHash(target_text, language);
1788
- const response = await api.getDoc(`checked-pronunciations/${hash}`);
1789
- try {
1790
- if (response.data) {
1791
- return processRecord(response.data);
1792
- } else {
1793
- return "NOT_CHECKED" /* NOT_CHECKED */;
1794
- }
1795
- } catch (e) {
1796
- return "NOT_CHECKED" /* NOT_CHECKED */;
1797
- }
1798
- };
1799
- var processRecord = (data) => {
1800
- const { pronunciations = 0, fails = 0 } = data;
1801
- const attempts = pronunciations + fails;
1802
- const successRate = attempts > 0 ? pronunciations / attempts * 100 : 0;
1803
- let newStatus = null;
1804
- if (attempts < 6) {
1805
- return "NOT_CHECKED" /* NOT_CHECKED */;
1806
- }
1807
- if (successRate > 25) {
1808
- newStatus = "VERIFIED" /* VERIFIED */;
1809
- } else if (successRate > 10) {
1810
- newStatus = "WARNING" /* WARNING */;
1811
- } else if (fails > 20 && successRate < 10 && pronunciations > 1) {
1812
- newStatus = "NOT_RECOMMENDED" /* NOT_RECOMMENDED */;
1813
- } else if (pronunciations === 0 && fails > 20) {
1814
- newStatus = "NOT_WORKING" /* NOT_WORKING */;
1815
- } else {
1816
- newStatus = "NOT_CHECKED" /* NOT_CHECKED */;
1817
- }
1818
- return newStatus;
1819
- };
1820
-
1821
- // src/domains/cards/services/create-card.service.ts
1822
- async function _createCard({ data }) {
1823
- const response = await api.addDoc(refsCardsFiresotre.allCards, data);
1824
- return response;
1825
- }
1826
- var createCard = withErrorHandler(_createCard, "createCard");
1827
- async function _createCards({ cards }) {
1828
- const { writeBatch: writeBatch2, doc: doc2 } = api.accessHelpers();
1829
- const batch = writeBatch2();
1830
- const cardsWithId = [];
1831
- for (const card of cards) {
1832
- const cardId = v4();
1833
- const ref = doc2(refsCardsFiresotre.card(cardId));
1834
- const newCardObject = {
1835
- ...card,
1836
- id: cardId
1837
- };
1838
- if (card.type === "READ_REPEAT" /* READ_REPEAT */ && card.target_text && card.language) {
1839
- const verificationStatus = await getVerificationStatus(card.target_text, card.language);
1840
- newCardObject.verificationStatus = verificationStatus || null;
1841
- }
1842
- cardsWithId.push(newCardObject);
1843
- batch.set(ref, newCardObject);
1844
- }
1845
- await batch.commit();
1846
- return cardsWithId;
1847
- }
1848
- var createCards = withErrorHandler(_createCards, "createCards");
1849
-
1850
- // src/domains/cards/card.hooks.ts
1851
- var cardsQueryKeys = {
1852
- all: ["cards"],
1853
- one: (params) => [...cardsQueryKeys.all, params.cardId]
1854
- };
1855
- function useCards({
1856
- cardIds,
1857
- enabled = true,
1858
- asObject
1859
- }) {
1860
- const queries = useQueries({
1861
- queries: cardIds.map((cardId) => ({
1862
- enabled: enabled && cardIds.length > 0,
1863
- queryKey: cardsQueryKeys.one({
1864
- cardId
1865
- }),
1866
- queryFn: () => getCard({ cardId })
1867
- }))
1868
- });
1869
- const cards = queries.map((query2) => query2.data).filter(Boolean);
1870
- const cardsObject = useMemo(() => {
1871
- if (!asObject) return null;
1872
- return cards.reduce((acc, card) => {
1873
- acc[card.id] = card;
1874
- return acc;
1875
- }, {});
1876
- }, [asObject, cards]);
1877
- return {
1878
- cards,
1879
- cardsObject,
1880
- cardsQueries: queries
1881
- };
1882
- }
1883
- function useCreateCard() {
1884
- const { queryClient } = useSpeakableApi();
1885
- const mutationCreateCard = useMutation2({
1886
- mutationFn: createCard,
1887
- onSuccess: (cardCreated) => {
1888
- queryClient.invalidateQueries({ queryKey: cardsQueryKeys.one({ cardId: cardCreated.id }) });
1889
- }
1890
- });
1891
- return {
1892
- mutationCreateCard
1893
- };
1894
- }
1895
- function useCreateCards() {
1896
- const mutationCreateCards = useMutation2({
1897
- mutationFn: createCards
1898
- });
1899
- return {
1900
- mutationCreateCards
1901
- };
1902
- }
1903
- function getCardFromCache({
1904
- cardId,
1905
- queryClient
1906
- }) {
1907
- return queryClient.getQueryData(cardsQueryKeys.one({ cardId }));
1908
- }
1909
- function updateCardInCache({
1910
- cardId,
1911
- card,
1912
- queryClient
1913
- }) {
1914
- queryClient.setQueryData(cardsQueryKeys.one({ cardId }), card);
1915
- }
1916
- function useGetCard({ cardId, enabled = true }) {
1917
- const query2 = useQuery3({
1918
- queryKey: cardsQueryKeys.one({ cardId }),
1919
- queryFn: () => getCard({ cardId }),
1920
- enabled: enabled && !!cardId
1921
- });
1922
- return query2;
1923
- }
1924
-
1925
- // src/domains/cards/card.repo.ts
1926
- var createCardRepo = () => {
1927
- return {
1928
- createCard,
1929
- createCards,
1930
- getCard
1931
- };
1932
- };
1933
-
1934
- // src/domains/cards/utils/check-page-type.ts
1935
- function checkIsRepeatPage(cardType) {
1936
- if (cardType === void 0) return false;
1937
- return REPEAT_PAGE_ACTIVITY_TYPES.includes(cardType);
1938
- }
1939
- function checkIsMCPage(cardType) {
1940
- if (cardType === void 0) return false;
1941
- return MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES.includes(cardType);
1942
- }
1943
- function checkIsRespondPage(cardType) {
1944
- if (cardType === void 0) return false;
1945
- return RESPOND_PAGE_ACTIVITY_TYPES.includes(cardType);
1946
- }
1947
- function checkIsRespondWrittenPage(cardType) {
1948
- if (cardType === void 0) return false;
1949
- return RESPOND_WRITE_PAGE_ACTIVITY_TYPES.includes(cardType);
1950
- }
1951
- function checkIsRespondAudioPage(cardType) {
1952
- if (cardType === void 0) return false;
1953
- return RESPOND_AUDIO_PAGE_ACTIVITY_TYPES.includes(cardType);
1954
- }
1955
- var checkIsMediaPage = (cardType) => {
1956
- if (cardType === void 0) return false;
1957
- return cardType === "MEDIA_PAGE" /* MEDIA_PAGE */;
1958
- };
1959
- var checkIsShortAnswerPage = (cardType) => {
1960
- if (cardType === void 0) return false;
1961
- return cardType === "SHORT_ANSWER" /* SHORT_ANSWER */;
1962
- };
1963
- var checkIsConversationPage = (cardType) => {
1964
- if (cardType === void 0) return false;
1965
- return cardType === "CONVERSATION" /* CONVERSATION */;
1966
- };
1967
- var checkTypePageActivity = (cardType) => {
1968
- const isRespondAudio = checkIsRespondAudioPage(cardType);
1969
- const isRespondWritten = checkIsRespondWrittenPage(cardType);
1970
- const isRespond = checkIsRespondPage(cardType);
1971
- const isMC = checkIsMCPage(cardType);
1972
- const isRepeat = checkIsRepeatPage(cardType);
1973
- const isMediaPage = checkIsMediaPage(cardType);
1974
- const isShortAnswer = checkIsShortAnswerPage(cardType);
1975
- const isConversation = checkIsConversationPage(cardType);
1976
- const isNoOneOfThem = !isRespond && !isMC && !isRepeat && !isMediaPage && !isShortAnswer && !isConversation;
1977
- if (isNoOneOfThem) {
1978
- return {
1979
- isRespondAudio: false,
1980
- isRespondWritten: false,
1981
- isRespond: false,
1982
- isMC: false,
1983
- isRepeat: true,
1984
- isMediaPage: false,
1985
- isShortAnswer: false,
1986
- hasSomeType: false,
1987
- isConversation: false
1988
- };
1989
- }
1990
- return {
1991
- isRespondAudio,
1992
- isRespondWritten,
1993
- isRespond,
1994
- isMC,
1995
- isRepeat,
1996
- isMediaPage,
1997
- isShortAnswer,
1998
- hasSomeType: true,
1999
- isConversation
2000
- };
2001
- };
2002
-
2003
- // src/domains/cards/utils/get-page-prompt.ts
2004
- function extractTextFromRichText(richText) {
2005
- if (!richText) return "";
2006
- return richText.replace(/<[^>]*>/g, "").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").trim();
2007
- }
2008
- function getPagePrompt(card) {
2009
- if (!card) return { has: false, text: "", rich_text: "", isTextEqualToRichText: false };
2010
- const { isMC, isRepeat, isRespond, isShortAnswer, isConversation } = checkTypePageActivity(
2011
- card == null ? void 0 : card.type
2012
- );
2013
- const hidePrompt = (card == null ? void 0 : card.hidePrompt) === true;
2014
- const createReturnObject = (text, richText, extraText) => {
2015
- const plainText = text || "";
2016
- const richTextPlain = extractTextFromRichText(richText);
2017
- return {
2018
- has: true,
2019
- text: plainText,
2020
- rich_text: richText || "",
2021
- isTextEqualToRichText: plainText.trim() === richTextPlain.trim(),
2022
- extraText: extraText || ""
2023
- };
2024
- };
2025
- if (isRepeat) {
2026
- return createReturnObject(card == null ? void 0 : card.target_text, card == null ? void 0 : card.rich_text);
2027
- }
2028
- if (isConversation) {
2029
- return createReturnObject(card == null ? void 0 : card.prompt, card == null ? void 0 : card.rich_text, card == null ? void 0 : card.goal);
2030
- }
2031
- if (isRespond && !hidePrompt) {
2032
- return createReturnObject(card == null ? void 0 : card.prompt, card == null ? void 0 : card.rich_text);
2033
- }
2034
- if (isMC) {
2035
- return createReturnObject(card == null ? void 0 : card.question, card == null ? void 0 : card.rich_text);
2036
- }
2037
- if (isShortAnswer && !hidePrompt) {
2038
- return createReturnObject(card == null ? void 0 : card.prompt, card == null ? void 0 : card.rich_text);
2039
- }
2040
- return {
2041
- has: false,
2042
- text: "",
2043
- rich_text: "",
2044
- isTextEqualToRichText: false,
2045
- extraText: ""
2046
- };
2047
- }
2048
-
2049
- // src/domains/cards/utils/get-completed-pages.ts
2050
- var getTotalCompletedCards = (pageScores) => {
2051
- return Object.values(pageScores != null ? pageScores : {}).reduce((acc, cardScore) => {
2052
- var _a, _b;
2053
- if (((_b = (_a = cardScore.completed) != null ? _a : cardScore.score) != null ? _b : cardScore.score === 0) && !cardScore.media_area_opened) {
2054
- acc++;
2055
- }
2056
- return acc;
2057
- }, 0);
2058
- };
2059
-
2060
- // src/domains/cards/utils/get-label-page.ts
2061
- var labels = {
2062
- repeat: {
2063
- short: "Repeat",
2064
- long: "Listen & Repeat"
2065
- },
2066
- mc: {
2067
- short: "Multiple Choice",
2068
- long: "Multiple Choice"
2069
- },
2070
- mediaPage: {
2071
- short: "Media Page",
2072
- long: "Media Page"
2073
- },
2074
- shortAnswer: {
2075
- short: "Short Answer",
2076
- long: "Short Answer"
2077
- },
2078
- respondWritten: {
2079
- short: "Open Response",
2080
- long: "Written Open Response"
2081
- },
2082
- respondAudio: {
2083
- short: "Open Response",
2084
- long: "Spoken Open Response"
2085
- }
2086
- };
2087
- var getLabelPage = (pageType) => {
2088
- if (!pageType) {
2089
- return {
2090
- short: "",
2091
- long: ""
2092
- };
2093
- }
2094
- const { isRepeat, isMC, isMediaPage, isShortAnswer, isRespondWritten, isRespondAudio } = checkTypePageActivity(pageType);
2095
- if (isRepeat) {
2096
- return labels.repeat;
2097
- }
2098
- if (isMC) {
2099
- return labels.mc;
2100
- }
2101
- if (isMediaPage) {
2102
- return labels.mediaPage;
2103
- }
2104
- if (isShortAnswer) {
2105
- return labels.shortAnswer;
2106
- }
2107
- if (isRespondWritten) {
2108
- return labels.respondWritten;
2109
- }
2110
- if (isRespondAudio) {
2111
- return labels.respondAudio;
2112
- }
2113
- return {
2114
- short: "",
2115
- long: ""
2116
- };
2117
- };
2118
-
2119
- // src/domains/cards/utils/get-page-media-data.ts
2120
- function getPageMediaData(page) {
2121
- var _a, _b, _c, _d;
2122
- const direction = (_a = page.media_area_layout) != null ? _a : "left";
2123
- const { isMediaPage } = checkTypePageActivity(page.type);
2124
- const singleMedia = getSingleMediaPageData(page);
2125
- const resource = {
2126
- id: (_c = (_b = page.media_area_id) != null ? _b : page.media_area_context_ref) != null ? _c : void 0,
2127
- shouldRender: ((_d = page.media_area_id) != null ? _d : page.media_area_context_ref) != null ? true : false
2128
- };
2129
- const promptMedia = {
2130
- direction,
2131
- content: singleMedia,
2132
- shouldRender: singleMedia !== void 0
2133
- };
2134
- return {
2135
- isMediaPage,
2136
- resource,
2137
- promptMedia
2138
- };
2139
- }
2140
- function getSingleMediaPageData(page) {
2141
- if (!page.media) return void 0;
2142
- const media = {
2143
- type: page.media.type,
2144
- content: page.media.url
2145
- };
2146
- return {
2147
- ...media,
2148
- rawObject: page.media
2149
- };
2150
- }
2151
-
2152
- // src/domains/sets/set.hooks.ts
2153
- import { useQuery as useQuery4 } from "@tanstack/react-query";
2154
-
2155
- // src/domains/sets/set.constants.ts
2156
- var SETS_COLLECTION = "sets";
2157
- var refsSetsFirestore = {
2158
- allSets: SETS_COLLECTION,
2159
- set: (id) => `${SETS_COLLECTION}/${id}`
2160
- };
2161
-
2162
- // src/domains/sets/services/get-set.service.ts
2163
- async function _getSet({ setId }) {
2164
- const response = await api.getDoc(refsSetsFirestore.set(setId));
2165
- return response.data;
2166
- }
2167
- var getSet = withErrorHandler(_getSet, "getSet");
2168
-
2169
- // src/domains/sets/set.hooks.ts
2170
- var setsQueryKeys = {
2171
- all: ["sets"],
2172
- one: (params) => [...setsQueryKeys.all, params.setId]
2173
- };
2174
- var useSet = ({ setId, enabled }) => {
2175
- return useQuery4({
2176
- queryKey: setsQueryKeys.one({ setId }),
2177
- queryFn: () => getSet({ setId }),
2178
- enabled: setId !== void 0 && setId !== "" && enabled
2179
- });
2180
- };
2181
- function getSetFromCache({
2182
- setId,
2183
- queryClient
2184
- }) {
2185
- if (!setId) return null;
2186
- return queryClient.getQueryData(setsQueryKeys.one({ setId }));
2187
- }
2188
- function updateSetInCache({
2189
- set,
2190
- queryClient
2191
- }) {
2192
- const { id, ...setData } = set;
2193
- queryClient.setQueryData(setsQueryKeys.one({ setId: id }), setData);
2194
- }
2195
-
2196
- // src/domains/sets/set.repo.ts
2197
- var createSetRepo = () => {
2198
- return {
2199
- getSet
2200
- };
2201
- };
2202
-
2203
- // src/utils/ai/detect-transcript-hallucionation.ts
2204
- var HALLUCINATION_THRESHOLDS = {
2205
- // Short repeats
2206
- MIN_CONSECUTIVE_REPEATS: 5,
2207
- // Increased from 3 to allow phrases like "pio pio pio" or "no no no no"
2208
- MIN_WORDS_FOR_RATIO_CHECK: 15,
2209
- // Increased from 10 to require longer text for ratio check
2210
- MAX_UNIQUE_WORDS_FOR_RATIO: 3,
2211
- MIN_REPETITION_RATIO: 4,
2212
- // Increased from 3 to be more permissive
2213
- // Phrase repeats
2214
- MIN_SENTENCE_LENGTH: 15,
2215
- // Increased from 10 to avoid flagging short natural sentences
2216
- MIN_CONSECUTIVE_SIMILAR_SENTENCES: 3,
2217
- // Increased from 2 to allow some natural repetition
2218
- MIN_SENTENCES_FOR_DUPLICATE_CHECK: 4,
2219
- // Increased from 3
2220
- // Cyclic patterns
2221
- MIN_CYCLE_LENGTH: 30,
2222
- // Increased from 20 to focus on longer patterns
2223
- MIN_CYCLE_REPEATS: 3,
2224
- // Entropy detection
2225
- MIN_LENGTH_FOR_ENTROPY_CHECK: 60,
2226
- // Increased from 50
2227
- MAX_ENTROPY_THRESHOLD: 2.2,
2228
- // Decreased from 2.5 to be more strict on entropy (lower = more repetitive needed)
2229
- // Similarity
2230
- SENTENCE_SIMILARITY_THRESHOLD: 0.85,
2231
- // Increased from 0.8 to require more similarity
2232
- SEGMENT_SIMILARITY_THRESHOLD: 0.9
2233
- // Increased from 0.85
2234
- };
2235
- function detectTranscriptHallucinationWithDetails(transcript) {
2236
- if (!transcript || transcript.trim().length === 0) {
2237
- return { isHallucination: false };
2238
- }
2239
- const text = transcript.trim();
2240
- if (text.length < 10) {
2241
- return { isHallucination: false };
2242
- }
2243
- const shortRepeats = detectShortRepeats(text);
2244
- if (shortRepeats) {
2245
- return {
2246
- isHallucination: true,
2247
- reason: "Detected repeated short words or phrases",
2248
- confidence: 0.9
2249
- };
2250
- }
2251
- const phraseRepeats = detectPhraseRepeats(text);
2252
- if (phraseRepeats) {
2253
- return {
2254
- isHallucination: true,
2255
- reason: "Detected repeated sentences or phrases",
2256
- confidence: 0.85
2257
- };
2258
- }
2259
- const cyclicRepeats = detectCyclicPattern(text);
2260
- if (cyclicRepeats) {
2261
- return {
2262
- isHallucination: true,
2263
- reason: "Detected cyclic repetition pattern",
2264
- confidence: 0.8
2265
- };
2266
- }
2267
- if (text.length >= HALLUCINATION_THRESHOLDS.MIN_LENGTH_FOR_ENTROPY_CHECK) {
2268
- const entropy = calculateEntropy(text);
2269
- if (entropy < HALLUCINATION_THRESHOLDS.MAX_ENTROPY_THRESHOLD) {
2270
- return {
2271
- isHallucination: true,
2272
- reason: "Detected low entropy (likely gibberish or excessive repetition)",
2273
- confidence: 0.75
2274
- };
2275
- }
2276
- }
2277
- return { isHallucination: false };
2278
- }
2279
- function detectShortRepeats(text) {
2280
- const words = text.toLowerCase().split(/[\s,;.!?]+/).filter((w) => w.length > 0);
2281
- if (words.length < 4) return false;
2282
- let repeatCount = 1;
2283
- for (let i = 1; i < words.length; i++) {
2284
- if (words[i] === words[i - 1]) {
2285
- repeatCount++;
2286
- if (repeatCount >= HALLUCINATION_THRESHOLDS.MIN_CONSECUTIVE_REPEATS) {
2287
- return true;
2288
- }
2289
- } else {
2290
- repeatCount = 1;
2291
- }
2292
- }
2293
- const uniqueWords = new Set(words);
2294
- const repetitionRatio = words.length / uniqueWords.size;
2295
- if (words.length >= HALLUCINATION_THRESHOLDS.MIN_WORDS_FOR_RATIO_CHECK && uniqueWords.size <= HALLUCINATION_THRESHOLDS.MAX_UNIQUE_WORDS_FOR_RATIO && repetitionRatio >= HALLUCINATION_THRESHOLDS.MIN_REPETITION_RATIO) {
2296
- return true;
2297
- }
2298
- return false;
2299
- }
2300
- function detectPhraseRepeats(text) {
2301
- const sentences = text.split(/[.!?]+/).map((s) => s.trim().toLowerCase()).filter((s) => s.length > HALLUCINATION_THRESHOLDS.MIN_SENTENCE_LENGTH);
2302
- if (sentences.length < 2) return false;
2303
- for (let i = 0; i < sentences.length - 1; i++) {
2304
- let consecutiveRepeats = 1;
2305
- for (let j = i + 1; j < sentences.length; j++) {
2306
- if (isSimilarSentence(sentences[i], sentences[j])) {
2307
- consecutiveRepeats++;
2308
- } else {
2309
- break;
2310
- }
2311
- }
2312
- if (consecutiveRepeats >= HALLUCINATION_THRESHOLDS.MIN_CONSECUTIVE_SIMILAR_SENTENCES) {
2313
- return true;
2314
- }
2315
- }
2316
- const uniqueSentences = new Set(sentences);
2317
- if (sentences.length >= HALLUCINATION_THRESHOLDS.MIN_SENTENCES_FOR_DUPLICATE_CHECK && uniqueSentences.size === 1) {
2318
- return true;
2319
- }
2320
- return false;
2321
- }
2322
- function isSimilarSentence(s1, s2, threshold = HALLUCINATION_THRESHOLDS.SENTENCE_SIMILARITY_THRESHOLD) {
2323
- if (s1 === s2) return true;
2324
- const normalized1 = s1.replace(/\s+/g, " ").trim();
2325
- const normalized2 = s2.replace(/\s+/g, " ").trim();
2326
- if (normalized1 === normalized2) return true;
2327
- const words1 = normalized1.split(/\s+/);
2328
- const words2 = normalized2.split(/\s+/);
2329
- if (Math.abs(words1.length - words2.length) > 2) return false;
2330
- const set1 = new Set(words1);
2331
- const set2 = new Set(words2);
2332
- const intersection = new Set([...set1].filter((w) => set2.has(w)));
2333
- const similarity = intersection.size * 2 / (set1.size + set2.size);
2334
- return similarity >= threshold;
2335
- }
2336
- function detectCyclicPattern(text) {
2337
- const normalized = text.toLowerCase().replace(/\s+/g, " ").trim();
2338
- const length = normalized.length;
2339
- const minCycleLength = HALLUCINATION_THRESHOLDS.MIN_CYCLE_LENGTH;
2340
- const maxCycleLength = Math.floor(length / 2);
2341
- if (maxCycleLength < minCycleLength) return false;
2342
- const step = 5;
2343
- for (let cycleLen = minCycleLength; cycleLen <= maxCycleLength; cycleLen += step) {
2344
- const pattern = normalized.substring(0, cycleLen);
2345
- let matchCount = 0;
2346
- let pos = 0;
2347
- while (pos < length) {
2348
- const segment = normalized.substring(pos, pos + cycleLen);
2349
- if (segment.length < cycleLen) {
2350
- const partialMatch = pattern.startsWith(segment);
2351
- if (partialMatch && matchCount > 0) {
2352
- matchCount++;
2353
- }
2354
- break;
2355
- }
2356
- if (segment === pattern || isSegmentSimilar(segment, pattern)) {
2357
- matchCount++;
2358
- pos += cycleLen;
2359
- } else {
2360
- break;
2361
- }
2362
- }
2363
- if (matchCount >= HALLUCINATION_THRESHOLDS.MIN_CYCLE_REPEATS) {
2364
- return true;
2365
- }
2366
- }
2367
- return false;
2368
- }
2369
- function isSegmentSimilar(s1, s2) {
2370
- if (s1 === s2) return true;
2371
- if (s1.length !== s2.length) return false;
2372
- let matches = 0;
2373
- const minLength = Math.min(s1.length, s2.length);
2374
- for (let i = 0; i < minLength; i++) {
2375
- if (s1[i] === s2[i]) {
2376
- matches++;
2377
- }
2378
- }
2379
- const similarity = matches / minLength;
2380
- return similarity >= HALLUCINATION_THRESHOLDS.SEGMENT_SIMILARITY_THRESHOLD;
2381
- }
2382
- function calculateEntropy(text) {
2383
- if (!text || text.length === 0) {
2384
- return 0;
2385
- }
2386
- const frequencies = /* @__PURE__ */ new Map();
2387
- for (const char of text.toLowerCase()) {
2388
- frequencies.set(char, (frequencies.get(char) || 0) + 1);
2389
- }
2390
- let entropy = 0;
2391
- const length = text.length;
2392
- for (const count of frequencies.values()) {
2393
- const probability = count / length;
2394
- entropy -= probability * Math.log2(probability);
2395
- }
2396
- return entropy;
2397
- }
2398
- function cleanHallucinatedTranscript(transcript) {
2399
- var _a, _b;
2400
- const result = detectTranscriptHallucinationWithDetails(transcript);
2401
- if (result.isHallucination) {
2402
- console.warn(
2403
- "Hallucinated transcript detected and removed:",
2404
- transcript.substring(0, 100),
2405
- `
2406
- Reason: ${(_a = result.reason) != null ? _a : "Unknown"}`,
2407
- `Confidence: ${String((_b = result.confidence) != null ? _b : "Unknown")}`
2408
- );
2409
- return "";
2410
- }
2411
- return transcript;
2412
- }
2413
-
2414
- // src/utils/ai/get-transcript.ts
2415
- async function getTranscript(model, args, cleanHallucinations = true) {
2416
- var _a, _b, _c, _d, _e, _f;
2417
- const getGeminiTranscript = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "getGeminiTranscript");
2418
- const getAssemblyAITranscript = (_d = (_c = api).httpsCallable) == null ? void 0 : _d.call(_c, "transcribeAssemblyAIAudio");
2419
- const getWhisperTranscript = (_f = (_e = api).httpsCallable) == null ? void 0 : _f.call(_e, "transcribeAudio");
2420
- if (model === "whisper") {
2421
- try {
2422
- const { data } = await (getWhisperTranscript == null ? void 0 : getWhisperTranscript({
2423
- audioUrl: args.audioUrl,
2424
- language: args.language
2425
- }));
2426
- return cleanHallucinations ? cleanHallucinatedTranscript(data) : data;
2427
- } catch (error) {
2428
- console.error("Error getting transcript from Whisper:", error);
2429
- throw error;
2430
- }
2431
- }
2432
- if (model === "gemini") {
2433
- try {
2434
- const { data } = await (getGeminiTranscript == null ? void 0 : getGeminiTranscript({
2435
- audioUrl: args.audioUrl,
2436
- targetLanguage: args.language,
2437
- prompt: args.prompt
2438
- }));
2439
- return cleanHallucinations ? cleanHallucinatedTranscript(data.transcript) : data.transcript;
2440
- } catch (error) {
2441
- console.error("Error getting transcript from Gemini:", error);
2442
- throw error;
2443
- }
2444
- }
2445
- if (model === "assemblyai") {
2446
- try {
2447
- const response = await (getAssemblyAITranscript == null ? void 0 : getAssemblyAITranscript({
2448
- audioUrl: args.audioUrl,
2449
- language: args.language
2450
- }));
2451
- return cleanHallucinations ? cleanHallucinatedTranscript(response.data) : response.data;
2452
- } catch (error) {
2453
- console.error("Error getting transcript from AssemblyAI:", error);
2454
- throw error;
2455
- }
2456
- }
2457
- return null;
2458
- }
2459
- async function getTranscriptCycle(args) {
2460
- const models = ["whisper", "gemini", "assemblyai"];
2461
- let transcript = "";
2462
- let lastError = null;
2463
- for (const model of models) {
2464
- try {
2465
- const transcriptResult = await getTranscript(model, args, false);
2466
- const rawTranscript = transcriptResult || "";
2467
- transcript = cleanHallucinatedTranscript(rawTranscript);
2468
- if (transcript !== "") {
2469
- console.log(`Successfully got transcript from ${model}`);
2470
- break;
2471
- }
2472
- console.warn(`${model} returned empty transcript, trying next model`);
2473
- } catch (e) {
2474
- console.error(`Error with ${model} transcript:`, e);
2475
- lastError = e;
2476
- }
2477
- }
2478
- if (transcript === "") {
2479
- console.error("All transcript models failed or returned empty", lastError);
2480
- return {
2481
- transcript: "",
2482
- success: false
2483
- };
2484
- }
2485
- return {
2486
- transcript,
2487
- success: true
2488
- };
2489
- }
2490
-
2491
- // src/constants/all-langs.json
2492
- var all_langs_default = {
2493
- af: "Afrikaans",
2494
- sq: "Albanian",
2495
- am: "Amharic",
2496
- ar: "Arabic",
2497
- hy: "Armenian",
2498
- az: "Azerbaijani",
2499
- eu: "Basque",
2500
- be: "Belarusian",
2501
- bn: "Bengali",
2502
- bs: "Bosnian",
2503
- bg: "Bulgarian",
2504
- ca: "Catalan",
2505
- ceb: "Cebuano",
2506
- zh: "Chinese",
2507
- co: "Corsican",
2508
- hr: "Croatian",
2509
- cs: "Czech",
2510
- da: "Danish",
2511
- nl: "Dutch",
2512
- en: "English",
2513
- eo: "Esperanto",
2514
- et: "Estonian",
2515
- fi: "Finnish",
2516
- fr: "French",
2517
- fy: "Frisian",
2518
- gl: "Galician",
2519
- ka: "Georgian",
2520
- de: "German",
2521
- el: "Greek",
2522
- gu: "Gujarati",
2523
- ht: "Haitian Creole",
2524
- ha: "Hausa",
2525
- haw: "Hawaiian",
2526
- he: "Hebrew",
2527
- hi: "Hindi",
2528
- hmn: "Hmong",
2529
- hu: "Hungarian",
2530
- is: "Icelandic",
2531
- ig: "Igbo",
2532
- id: "Indonesian",
2533
- ga: "Irish",
2534
- it: "Italian",
2535
- ja: "Japanese",
2536
- jv: "Javanese",
2537
- kn: "Kannada",
2538
- kk: "Kazakh",
2539
- km: "Khmer",
2540
- ko: "Korean",
2541
- ku: "Kurdish",
2542
- ky: "Kyrgyz",
2543
- lo: "Lao",
2544
- la: "Latin",
2545
- lv: "Latvian",
2546
- lt: "Lithuanian",
2547
- lb: "Luxembourgish",
2548
- mk: "Macedonian",
2549
- mg: "Malagasy",
2550
- ms: "Malay",
2551
- ml: "Malayalam",
2552
- mt: "Maltese",
2553
- mi: "Maori",
2554
- mr: "Marathi",
2555
- mn: "Mongolian",
2556
- my: "Myanmar (Burmese)",
2557
- ne: "Nepali",
2558
- no: "Norwegian",
2559
- ny: "Nyanja (Chichewa)",
2560
- ps: "Pashto",
2561
- fa: "Persian",
2562
- pl: "Polish",
2563
- pt: "Portuguese",
2564
- pa: "Punjabi",
2565
- ro: "Romanian",
2566
- ru: "Russian",
2567
- sm: "Samoan",
2568
- gd: "Scots Gaelic",
2569
- sr: "Serbian",
2570
- st: "Sesotho",
2571
- sn: "Shona",
2572
- sd: "Sindhi",
2573
- si: "Sinhala (Sinhalese)",
2574
- sk: "Slovak",
2575
- sl: "Slovenian",
2576
- so: "Somali",
2577
- es: "Spanish",
2578
- su: "Sundanese",
2579
- sw: "Swahili",
2580
- sv: "Swedish",
2581
- tl: "Tagalog (Filipino)",
2582
- tg: "Tajik",
2583
- ta: "Tamil",
2584
- te: "Telugu",
2585
- th: "Thai",
2586
- tr: "Turkish",
2587
- uk: "Ukrainian",
2588
- ur: "Urdu",
2589
- uz: "Uzbek",
2590
- vi: "Vietnamese",
2591
- cy: "Welsh",
2592
- xh: "Xhosa",
2593
- yi: "Yiddish",
2594
- yo: "Yoruba",
2595
- zu: "Zulu"
2596
- };
2597
-
2598
- // src/utils/ai/get-respond-card-tool.ts
2599
- var getRespondCardTool = ({
2600
- language,
2601
- standard = "actfl"
2602
- }) => {
2603
- const lang = all_langs_default[language] || "English";
2604
- const tool = {
2605
- tool_choice: {
2606
- type: "function",
2607
- function: { name: "get_feedback" }
2608
- },
2609
- tools: [
2610
- {
2611
- type: "function",
2612
- function: {
2613
- name: "get_feedback",
2614
- description: "Get feedback on a student's response",
2615
- parameters: {
2616
- type: "object",
2617
- required: [
2618
- "success",
2619
- "score",
2620
- "score_justification",
2621
- "errors",
2622
- "improvedResponse",
2623
- "compliments"
2624
- ],
2625
- properties: {
2626
- success: {
2627
- type: "boolean",
2628
- description: "Mark true if the student's response was on-topic and generally demonstrated understanding. A few grammar mistakes are acceptable. Mark false if the student's response was off-topic or did not demonstrate understanding."
2629
- },
2630
- errors: {
2631
- type: "array",
2632
- items: {
2633
- type: "object",
2634
- required: ["error", "grammar_error_type", "correction", "justification"],
2635
- properties: {
2636
- error: {
2637
- type: "string",
2638
- description: "The grammatical error in the student's response."
2639
- },
2640
- correction: {
2641
- type: "string",
2642
- description: "The suggested correction to the error"
2643
- },
2644
- justification: {
2645
- type: "string",
2646
- description: `An explanation of the rationale behind the suggested correction. WRITE THIS IN ${lang}!`
2647
- },
2648
- grammar_error_type: {
2649
- type: "string",
2650
- enum: [
2651
- "subjVerbAgree",
2652
- "tenseErrors",
2653
- "articleMisuse",
2654
- "prepositionErrors",
2655
- "adjNounAgree",
2656
- "pronounErrors",
2657
- "wordOrder",
2658
- "verbConjugation",
2659
- "pluralization",
2660
- "negationErrors",
2661
- "modalVerbMisuse",
2662
- "relativeClause",
2663
- "auxiliaryVerb",
2664
- "complexSentenceAgreement",
2665
- "idiomaticExpression",
2666
- "registerInconsistency",
2667
- "voiceMisuse"
2668
- ],
2669
- description: "The type of grammatical error found. It should be one of the following categories: subject-verb agreement, tense errors, article misuse, preposition errors, adjective-noun agreement, pronoun errors, word order, verb conjugation, pluralization errors, negation errors, modal verb misuse, relative clause errors, auxiliary verb misuse, complex sentence agreement, idiomatic expression, register inconsistency, or voice misuse"
2670
- }
2671
- }
2672
- },
2673
- description: "An array of objects, each representing a grammatical error in the student's response. Each object should have the following properties: error, grammar_error_type, correction, and justification. If there were no errors, return an empty array."
2674
- },
2675
- compliments: {
2676
- type: "array",
2677
- items: {
2678
- type: "string"
2679
- },
2680
- description: `An array of strings, each representing something the student did well. Each string should be WRITTEN IN ${lang}!`
2681
- },
2682
- improvedResponse: {
2683
- type: "string",
2684
- description: "An improved response with proper grammar and more detail, if applicable."
2685
- },
2686
- score: {
2687
- type: "number",
2688
- description: "A score between 0 and 100, reflecting the overall quality of the response"
2689
- },
2690
- score_justification: {
2691
- type: "string",
2692
- description: "An explanation of the rationale behind the assigned score, considering both accuracy and fluency"
2693
- }
2694
- }
2695
- }
2696
- }
2697
- }
2698
- ]
2699
- };
2700
- if (standard === "wida") {
2701
- const wida_level = {
2702
- type: "number",
2703
- enum: [1, 2, 3, 4, 5, 6],
2704
- description: `The student's WIDA (World-Class Instructional Design and Assessment) proficiency level. Choose one of the following options: 1, 2, 3, 4, 5, 6 which corresponds to
2705
-
2706
- 1 - Entering
2707
- 2 - Emerging
2708
- 3 - Developing
2709
- 4 - Expanding
2710
- 5 - Bridging
2711
- 6 - Reaching
2712
-
2713
- This is an estimate based on the level of the student's response. Use the descriptions of the WIDA speaking standards to guide your decision.
2714
- `
2715
- };
2716
- const wida_justification = {
2717
- type: "string",
2718
- description: `An explanation of the rationale behind the assigned WIDA level of the response, considering both accuracy and fluency. WRITE THIS IN ENGLISH!`
2719
- };
2720
- tool.tools[0].function.parameters.required.push("wida_level");
2721
- tool.tools[0].function.parameters.required.push("wida_justification");
2722
- tool.tools[0].function.parameters.properties.wida_level = wida_level;
2723
- tool.tools[0].function.parameters.properties.wida_justification = wida_justification;
2724
- } else {
2725
- const actfl_level = {
2726
- type: "string",
2727
- enum: ["NL", "NM", "NH", "IL", "IM", "IH", "AL", "AM", "AH", "S", "D"],
2728
- description: "The student's ACTFL (American Council on the Teaching of Foreign Languages) proficiency level. Choose one of the following options: NL, NM, NH, IL, IM, IH, AL, AM, AH, S, or D"
2729
- };
2730
- const actfl_justification = {
2731
- type: "string",
2732
- description: "An explanation of the rationale behind the assigned ACTFL level, considering both accuracy and fluency"
2733
- };
2734
- tool.tools[0].function.parameters.required.push("actfl_level");
2735
- tool.tools[0].function.parameters.required.push("actfl_justification");
2736
- tool.tools[0].function.parameters.properties.actfl_level = actfl_level;
2737
- tool.tools[0].function.parameters.properties.actfl_justification = actfl_justification;
2738
- }
2739
- return tool;
2740
- };
2741
-
2742
- // src/hooks/useActivity.ts
2743
- import { useEffect as useEffect2 } from "react";
2744
-
2745
- // src/services/add-grading-standard.ts
2746
- var addGradingStandardLog = async (gradingStandard, userId) => {
2747
- logGradingStandardLog(gradingStandard);
2748
- const path = `users/${userId}/grading_standard_logs`;
2749
- await api.addDoc(path, gradingStandard);
2750
- };
2751
-
2752
- // src/hooks/useActivityTracker.ts
2753
- import { v4 as v42 } from "uuid";
2754
- function useActivityTracker({ userId }) {
2755
- const trackActivity = async ({
2756
- activityName,
2757
- activityType,
2758
- id = v42(),
2759
- language = ""
2760
- }) => {
2761
- if (userId) {
2762
- const { doc: doc2, serverTimestamp: serverTimestamp2, setDoc: setDoc2 } = api.accessHelpers();
2763
- const activityRef = doc2(`users/${userId}/activity/${id}`);
2764
- const timestamp = serverTimestamp2();
2765
- await setDoc2(activityRef, {
2766
- name: activityName,
2767
- type: activityType,
2768
- lastSeen: timestamp,
2769
- id,
2770
- language
2771
- });
2772
- }
2773
- };
2774
- return {
2775
- trackActivity
2776
- };
2777
- }
2778
-
2779
- // src/hooks/useActivity.ts
2780
- function useActivity({
2781
- id,
2782
- isAssignment,
2783
- onAssignmentSubmitted,
2784
- ltiData
2785
- }) {
2786
- var _a, _b;
2787
- const { queryClient, user } = useSpeakableApi();
2788
- const userId = user.auth.uid;
2789
- const assignmentQuery = useAssignment({
2790
- assignmentId: id,
2791
- userId,
2792
- enabled: isAssignment
2793
- });
2794
- const activeAssignment = assignmentQuery.data;
2795
- const setId = isAssignment ? (_a = activeAssignment == null ? void 0 : activeAssignment.setId) != null ? _a : "" : id;
2796
- const querySet = useSet({ setId });
2797
- const setData = querySet.data;
2798
- const assignmentContent = activeAssignment == null ? void 0 : activeAssignment.content;
2799
- const assignmentWeights = activeAssignment == null ? void 0 : activeAssignment.weights;
2800
- const setContent = setData == null ? void 0 : setData.content;
2801
- const setWeights = setData == null ? void 0 : setData.weights;
2802
- const contentCardsToUse = isAssignment ? assignmentContent != null ? assignmentContent : setContent : setContent;
2803
- const weightsToUse = isAssignment ? assignmentWeights != null ? assignmentWeights : setWeights : setWeights;
2804
- const activityId = isAssignment ? (_b = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b : "" : setId;
2805
- const { cardsObject, cardsQueries, cards } = useCards({
2806
- cardIds: contentCardsToUse != null ? contentCardsToUse : [],
2807
- enabled: querySet.isSuccess,
2808
- asObject: true
2809
- });
2810
- const scorableCardIds = (contentCardsToUse != null ? contentCardsToUse : []).filter((cardId) => {
2811
- const card = cardsObject == null ? void 0 : cardsObject[cardId];
2812
- return (card == null ? void 0 : card.type) !== "MEDIA_PAGE" /* MEDIA_PAGE */;
2813
- });
2814
- const scoreQuery = useScore({
2815
- isAssignment,
2816
- activityId: id,
2817
- userId,
2818
- courseId: activeAssignment == null ? void 0 : activeAssignment.courseId,
2819
- googleClassroomUserId: user.profile.googleClassroomUserId,
2820
- enabled: isAssignment ? assignmentQuery.isSuccess : querySet.isSuccess
2821
- });
2822
- const { mutationUpdateScore } = useUpdateScore();
2823
- const { mutationUpdateCardScore } = useUpdateCardScore({
2824
- activityId,
2825
- isAssignment,
2826
- userId,
2827
- cardIds: scorableCardIds,
2828
- weights: weightsToUse != null ? weightsToUse : {}
2829
- });
2830
- const { mutationClearScore } = useClearScore();
2831
- const { submitAssignmentScore: submitAssignmentScore2 } = useSubmitAssignmentScore({
2832
- onAssignmentSubmitted,
2833
- studentName: user.profile.displayName
2834
- });
2835
- const { submitPracticeScore: submitPracticeScore2 } = useSubmitPracticeScore();
2836
- const handleUpdateScore = (data) => {
2837
- mutationUpdateScore.mutate({
2838
- data,
2839
- isAssignment,
2840
- activityId,
2841
- userId
2842
- });
2843
- };
2844
- const handleUpdateCardScore = (cardId, cardScore) => {
2845
- mutationUpdateCardScore.mutate({ cardId, cardScore });
2846
- if (cardScore.proficiency_level) {
2847
- logGradingStandardEntry({
2848
- type: cardScore.proficiency_level.standardId,
2849
- cardId,
2850
- gradingStandard: cardScore.proficiency_level
2851
- });
2852
- } else if (cardScore.wida || cardScore.actfl) {
2853
- logGradingStandardEntry({
2854
- type: cardScore.wida ? "wida" : "actfl",
2855
- cardId,
2856
- gradingStandard: cardScore.wida || cardScore.actfl || { level: "", justification: "" }
2857
- });
2858
- }
2859
- };
2860
- const onClearScore = ({
2861
- cardId,
2862
- wasCompleted = true
2863
- }) => {
2864
- var _a2, _b2;
2865
- const currentCard = cardsObject == null ? void 0 : cardsObject[cardId];
2866
- if ((currentCard == null ? void 0 : currentCard.type) === "MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */ || (currentCard == null ? void 0 : currentCard.type) === "READ_REPEAT" /* READ_REPEAT */) {
2867
- return;
2868
- }
2869
- const queryKeys = scoreQueryKeys.byId(activityId);
2870
- const activeCardScores = (_b2 = (_a2 = queryClient.getQueryData(queryKeys)) == null ? void 0 : _a2.cards) == null ? void 0 : _b2[cardId];
2871
- if (activeCardScores === void 0) return;
2872
- mutationClearScore.mutate({
2873
- isAssignment,
2874
- activityId,
2875
- cardScores: activeCardScores,
2876
- cardId,
2877
- userId
2878
- });
2879
- };
2880
- const onSubmitScore = async () => {
2881
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
2882
- try {
2883
- let results;
2884
- if (isAssignment) {
2885
- const someCardIsManualGraded = cards.some((page) => page.grading_method === "manual");
2886
- results = await submitAssignmentScore2({
2887
- assignment: {
2888
- id: (_b2 = (_a2 = assignmentQuery.data) == null ? void 0 : _a2.id) != null ? _b2 : "",
2889
- name: (_d = (_c = assignmentQuery.data) == null ? void 0 : _c.name) != null ? _d : "",
2890
- owners: (_f = (_e = assignmentQuery.data) == null ? void 0 : _e.owners) != null ? _f : [],
2891
- courseId: (_h = (_g = assignmentQuery.data) == null ? void 0 : _g.courseId) != null ? _h : "",
2892
- courseWorkId: (_j = (_i = assignmentQuery.data) == null ? void 0 : _i.courseWorkId) != null ? _j : "",
2893
- isAssessment: (_l = (_k = assignmentQuery.data) == null ? void 0 : _k.isAssessment) != null ? _l : false,
2894
- maxPoints: (_n = (_m = assignmentQuery.data) == null ? void 0 : _m.maxPoints) != null ? _n : 0
2895
- },
2896
- userId,
2897
- scores: scoreQuery.data,
2898
- status: someCardIsManualGraded ? "PENDING_REVIEW" : "SUBMITTED"
2899
- });
2900
- if ((_o = assignmentQuery.data) == null ? void 0 : _o.ltiDeeplink) {
2901
- submitLTIScore({
2902
- maxPoints: (_p = assignmentQuery.data) == null ? void 0 : _p.maxPoints,
2903
- score: (_r = (_q = scoreQuery.data) == null ? void 0 : _q.score) != null ? _r : 0,
2904
- SERVICE_KEY: (_s = ltiData == null ? void 0 : ltiData.serviceKey) != null ? _s : "",
2905
- lineItemId: (_t = ltiData == null ? void 0 : ltiData.lineItemId) != null ? _t : "",
2906
- lti_id: (_u = ltiData == null ? void 0 : ltiData.lti_id) != null ? _u : ""
2907
- });
2908
- }
2909
- } else {
2910
- results = await submitPracticeScore2({
2911
- setId: (_w = (_v = querySet.data) == null ? void 0 : _v.id) != null ? _w : "",
2912
- userId,
2913
- scores: scoreQuery.data
2914
- });
2915
- }
2916
- return results;
2917
- } catch (error) {
2918
- return {
2919
- success: false,
2920
- error
2921
- };
2922
- }
2923
- };
2924
- const logGradingStandardEntry = ({
2925
- cardId,
2926
- gradingStandard,
2927
- type
2928
- }) => {
2929
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
2930
- const card = cardsObject == null ? void 0 : cardsObject[cardId];
2931
- const scoresObject = queryClient.getQueryData(scoreQueryKeys.byId(activityId));
2932
- const cardScore = (_a2 = scoresObject == null ? void 0 : scoresObject.cards) == null ? void 0 : _a2[cardId];
2933
- const serverTimestamp2 = api.helpers.serverTimestamp;
2934
- addGradingStandardLog(
2935
- {
2936
- assignmentId: (_b2 = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b2 : "",
2937
- courseId: (_c = activeAssignment == null ? void 0 : activeAssignment.courseId) != null ? _c : "",
2938
- teacherId: (_d = activeAssignment == null ? void 0 : activeAssignment.owners[0]) != null ? _d : "",
2939
- setId: (_e = setData == null ? void 0 : setData.id) != null ? _e : "",
2940
- cardId,
2941
- level: gradingStandard.level,
2942
- justification: gradingStandard.justification,
2943
- transcript: (_f = cardScore == null ? void 0 : cardScore.transcript) != null ? _f : "",
2944
- audioUrl: (_g = cardScore == null ? void 0 : cardScore.audio) != null ? _g : "",
2945
- prompt: (_h = card == null ? void 0 : card.prompt) != null ? _h : "",
2946
- responseType: (card == null ? void 0 : card.type) === "RESPOND_WRITE" /* RESPOND_WRITE */ ? "written" : "spoken",
2947
- type,
2948
- dateMade: serverTimestamp2(),
2949
- language: (_i = card == null ? void 0 : card.language) != null ? _i : ""
2950
- },
2951
- userId
2952
- );
2953
- };
2954
- useEffect2(() => {
2955
- if (isAssignment) {
2956
- logOpenAssignment({ assignmentId: id });
2957
- } else {
2958
- logOpenActivityPreview({ setId: id });
2959
- }
2960
- }, []);
2961
- useInitActivity({
2962
- assignment: activeAssignment != null ? activeAssignment : void 0,
2963
- set: setData != null ? setData : void 0,
2964
- enabled: !!setData,
2965
- userId
2966
- });
2967
- return {
2968
- set: {
2969
- data: setData,
2970
- query: querySet
2971
- },
2972
- cards: {
2973
- data: cardsObject,
2974
- query: cardsQueries,
2975
- cardsArray: cards
2976
- },
2977
- assignment: {
2978
- data: isAssignment ? activeAssignment : void 0,
2979
- query: assignmentQuery
2980
- },
2981
- scores: {
2982
- data: scoreQuery.data,
2983
- query: scoreQuery,
2984
- actions: {
2985
- update: handleUpdateScore,
2986
- clear: onClearScore,
2987
- submit: onSubmitScore,
2988
- updateCard: handleUpdateCardScore,
2989
- logGradingStandardEntry
2990
- }
2991
- }
2992
- };
2993
- }
2994
- var useInitActivity = ({
2995
- assignment,
2996
- set,
2997
- enabled,
2998
- userId
2999
- }) => {
3000
- const { trackActivity } = useActivityTracker({ userId });
3001
- const init = () => {
3002
- var _a, _b, _c, _d, _e, _f, _g;
3003
- if (!enabled) return;
3004
- if (!assignment) {
3005
- trackActivity({
3006
- activityName: (_a = set == null ? void 0 : set.name) != null ? _a : "",
3007
- activityType: "set",
3008
- id: set == null ? void 0 : set.id,
3009
- language: set == null ? void 0 : set.language
3010
- });
3011
- } else if (assignment.name) {
3012
- trackActivity({
3013
- activityName: assignment.name,
3014
- activityType: assignment.isAssessment ? "assessment" : "assignment",
3015
- id: assignment.id,
3016
- language: set == null ? void 0 : set.language
3017
- });
3018
- }
3019
- if (set == null ? void 0 : set.public) {
3020
- (_d = (_c = (_b = api).httpsCallable) == null ? void 0 : _c.call(_b, "onSetOpened")) == null ? void 0 : _d({
3021
- setId: set.id,
3022
- language: set.language
3023
- });
3024
- }
3025
- (_g = (_f = (_e = api).httpsCallable) == null ? void 0 : _f.call(_e, "updateAlgoliaIndex")) == null ? void 0 : _g({
3026
- updatePlays: true,
3027
- objectID: set == null ? void 0 : set.id
3028
- });
3029
- };
3030
- useEffect2(() => {
3031
- init();
3032
- }, [set]);
3033
- };
3034
- var submitLTIScore = async ({
3035
- maxPoints,
3036
- score,
3037
- SERVICE_KEY,
3038
- lineItemId,
3039
- lti_id
3040
- }) => {
3041
- var _a, _b, _c;
3042
- try {
3043
- if (!SERVICE_KEY || !lineItemId || !lti_id) {
3044
- throw new Error("Missing required LTI credentials");
3045
- }
3046
- const earnedPoints = score ? score / 100 * maxPoints : 0;
3047
- const { data } = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitLTIAssignmentScore")) == null ? void 0 : _c({
3048
- SERVICE_KEY,
3049
- scoreData: {
3050
- lineItemId,
3051
- userId: lti_id,
3052
- maxPoints,
3053
- earnedPoints
3054
- }
3055
- }));
3056
- return { success: true, data };
3057
- } catch (error) {
3058
- console.error("Failed to submit LTI score:", error);
3059
- return {
3060
- success: false,
3061
- error: error instanceof Error ? error : new Error("Unknown error occurred")
3062
- };
3063
- }
3064
- };
3065
-
3066
- // src/hooks/useCredits.ts
3067
- import { useQuery as useQuery5 } from "@tanstack/react-query";
3068
- var creditQueryKeys = {
3069
- userCredits: (uid) => ["userCredits", uid]
3070
- };
3071
- var useUserCredits = () => {
3072
- const { user } = useSpeakableApi();
3073
- const email = user.auth.email;
3074
- const uid = user.auth.uid;
3075
- const query2 = useQuery5({
3076
- queryKey: creditQueryKeys.userCredits(uid),
3077
- queryFn: () => fetchUserCredits({ uid, email }),
3078
- enabled: !!uid,
3079
- refetchInterval: 1e3 * 60 * 5
3080
- });
3081
- return {
3082
- ...query2
3083
- };
3084
- };
3085
- var fetchUserCredits = async ({ uid, email }) => {
3086
- if (!uid) {
3087
- throw new Error("User ID is required");
3088
- }
3089
- const contractSnap = await api.getDoc(`creditContracts/${uid}`);
3090
- if (contractSnap.data == null) {
3091
- return {
3092
- id: uid,
3093
- userId: uid,
3094
- email,
3095
- effectivePlanId: "free_tier",
3096
- status: "inactive",
3097
- isUnlimited: false,
3098
- creditsAvailable: 100,
3099
- creditsAllocatedThisPeriod: 100,
3100
- topOffCreditsAvailable: 0,
3101
- topOffCreditsTotal: 0,
3102
- allocationSource: "free_tier",
3103
- sourceDetails: {},
3104
- periodStart: null,
3105
- periodEnd: null,
3106
- planTermEndTimestamp: null,
3107
- ownerType: "individual",
3108
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3109
- lastUpdatedAt: (/* @__PURE__ */ new Date()).toISOString()
3110
- };
3111
- }
3112
- const contractData = contractSnap.data;
3113
- const monthlyCredits = (contractData == null ? void 0 : contractData.creditsAvailable) || 0;
3114
- const topOffCredits = (contractData == null ? void 0 : contractData.topOffCreditsAvailable) || 0;
3115
- const totalCredits = monthlyCredits + topOffCredits;
3116
- return {
3117
- id: contractSnap.id,
3118
- ...contractData,
3119
- // Add computed total for convenience
3120
- totalCreditsAvailable: totalCredits
3121
- };
3122
- };
3123
-
3124
- // src/hooks/useOrganizationAccess.ts
3125
- import { useQuery as useQuery6 } from "@tanstack/react-query";
3126
- var useOrganizationAccess = () => {
3127
- const { user } = useSpeakableApi();
3128
- const email = user.auth.email;
3129
- const query2 = useQuery6({
3130
- queryKey: ["organizationAccess", email],
3131
- queryFn: async () => {
3132
- if (!email) {
3133
- return {
3134
- hasUnlimitedAccess: false,
3135
- subscriptionId: null,
3136
- organizationId: null,
3137
- organizationName: null,
3138
- subscriptionEndDate: null,
3139
- accessType: "individual"
3140
- };
3141
- }
3142
- return getOrganizationAccess(email);
3143
- },
3144
- enabled: !!email,
3145
- // Only run query if we have a user email
3146
- staleTime: 5 * 60 * 1e3,
3147
- // Consider data fresh for 5 minutes
3148
- gcTime: 10 * 60 * 1e3,
3149
- // Keep in cache for 10 minutes
3150
- retry: 2
3151
- // Retry failed requests twice
3152
- });
3153
- return {
3154
- ...query2
3155
- };
3156
- };
3157
- var getOrganizationAccess = async (email) => {
3158
- const { limit: limit2, where: where2 } = api.accessQueryConstraints();
3159
- try {
3160
- const organizationSnapshot = await api.getDocs(
3161
- "organizations",
3162
- where2("members", "array-contains", email),
3163
- where2("masterSubscriptionStatus", "==", "active"),
3164
- limit2(1)
3165
- );
3166
- if (!organizationSnapshot.empty) {
3167
- const orgData = organizationSnapshot.data[0];
3168
- return {
3169
- hasUnlimitedAccess: true,
3170
- subscriptionId: orgData == null ? void 0 : orgData.masterSubscriptionId,
3171
- organizationId: orgData.id,
3172
- organizationName: orgData.name || "Unknown Organization",
3173
- subscriptionEndDate: orgData.masterSubscriptionEndDate || null,
3174
- accessType: "organization"
3175
- };
3176
- }
3177
- const institutionSnapshot = await api.getDocs(
3178
- "institution_subscriptions",
3179
- where2("users", "array-contains", email),
3180
- where2("active", "==", true),
3181
- limit2(1)
3182
- );
3183
- if (!institutionSnapshot.empty) {
3184
- const institutionData = institutionSnapshot.data[0];
3185
- const isUnlimited = (institutionData == null ? void 0 : institutionData.plan) === "organization" || (institutionData == null ? void 0 : institutionData.plan) === "school_starter";
3186
- return {
3187
- hasUnlimitedAccess: isUnlimited,
3188
- subscriptionId: institutionData.id,
3189
- organizationId: institutionData == null ? void 0 : institutionData.institutionId,
3190
- organizationName: institutionData.name || institutionData.institutionId || "Legacy Institution",
3191
- subscriptionEndDate: institutionData.endDate || null,
3192
- accessType: "institution_subscriptions"
3193
- };
3194
- }
3195
- return {
3196
- hasUnlimitedAccess: false,
3197
- subscriptionId: null,
3198
- organizationId: null,
3199
- organizationName: null,
3200
- subscriptionEndDate: null,
3201
- accessType: "individual"
3202
- };
3203
- } catch (error) {
3204
- console.error("Error checking organization access:", error);
3205
- return {
3206
- hasUnlimitedAccess: false,
3207
- subscriptionId: null,
3208
- organizationId: null,
3209
- organizationName: null,
3210
- subscriptionEndDate: null,
3211
- accessType: "individual"
3212
- };
3213
- }
3214
- };
3215
-
3216
- // src/hooks/useSpeakableTranscript.ts
3217
- import { useMutation as useMutation3 } from "@tanstack/react-query";
3218
- function useSpeakableTranscript() {
3219
- const mutation = useMutation3({
3220
- mutationFn: async ({
3221
- model,
3222
- audioUrl,
3223
- language,
3224
- prompt
3225
- }) => {
3226
- return getTranscript(model, { audioUrl, language, prompt });
3227
- },
3228
- retry: false
3229
- });
3230
- return {
3231
- mutation
3232
- };
3233
- }
3234
- function useSpeakableTranscriptCycle() {
3235
- const mutation = useMutation3({
3236
- mutationFn: async (args) => {
3237
- return getTranscriptCycle(args);
3238
- },
3239
- retry: false
3240
- });
3241
- return {
3242
- mutationTranscriptCycle: mutation
3243
- };
3244
- }
3245
-
3246
- // src/hooks/useUpdateStudentVoc.ts
3247
- var useUpdateStudentVocab = (page) => {
3248
- const { user } = useSpeakableApi();
3249
- const currentUserId = user == null ? void 0 : user.auth.uid;
3250
- if (!page || !currentUserId || !page.target_text || !page.language) {
3251
- return {
3252
- studentVocabMarkVoiceSuccess: void 0,
3253
- studentVocabMarkVoiceFail: void 0
3254
- };
3255
- }
3256
- const getDataObject = () => {
3257
- var _a, _b;
3258
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
3259
- const language = (_a = page.language) != null ? _a : "en";
3260
- const word = (_b = page.target_text) != null ? _b : "";
3261
- const phrase_length = getPhraseLength(word);
3262
- const wordHash = getWordHash(word, language);
3263
- const docPath = `users/${currentUserId}/vocab/${wordHash}`;
3264
- const communityPath = `checked-pronunciations/${wordHash}`;
3265
- const id = `${language}-${cleanString(word)}`;
3266
- const data = {
3267
- id,
3268
- word,
3269
- words: (word == null ? void 0 : word.split(" ")) || [],
3270
- wordHash,
3271
- language,
3272
- lastSeen: serverTimestamp2(),
3273
- phrase_length
3274
- };
3275
- return {
3276
- docPath,
3277
- communityPath,
3278
- data
3279
- };
3280
- };
3281
- const markVoiceSuccess = async () => {
3282
- const { docPath, communityPath, data } = getDataObject();
3283
- const { increment: increment2 } = api.accessQueryConstraints();
3284
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
3285
- data.voiceSuccess = increment2(1);
3286
- try {
3287
- await api.updateDoc(docPath, data);
3288
- } catch (error) {
3289
- if (error instanceof Error && "code" in error) {
3290
- const firebaseError = error;
3291
- if (firebaseError.code === "not-found") {
3292
- data.firstSeen = serverTimestamp2();
3293
- await api.setDoc(docPath, data, { merge: true });
3294
- } else {
3295
- console.error("Error actualizando vocabulario:", error);
3296
- }
3297
- } else {
3298
- console.error("Error desconocido:", error);
3299
- }
3300
- }
3301
- try {
3302
- data.pronunciations = increment2(1);
3303
- await api.setDoc(communityPath, data, { merge: true });
3304
- } catch (error) {
3305
- console.log(error);
3306
- }
3307
- };
3308
- const markVoiceFail = async () => {
3309
- const { docPath, communityPath, data } = getDataObject();
3310
- const { increment: increment2 } = api.accessQueryConstraints();
3311
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
3312
- data.voiceFail = increment2(1);
3313
- try {
3314
- await api.updateDoc(docPath, data);
3315
- } catch (error) {
3316
- if (error instanceof Error && error.message === "not-found") {
3317
- data.firstSeen = serverTimestamp2();
3318
- await api.setDoc(docPath, data, { merge: true });
3319
- } else {
3320
- console.log(error);
3321
- }
3322
- }
3323
- try {
3324
- data.fails = increment2(1);
3325
- await api.setDoc(communityPath, data, { merge: true });
3326
- } catch (error) {
3327
- console.log(error);
3328
- }
3329
- };
3330
- return {
3331
- studentVocabMarkVoiceSuccess: markVoiceSuccess,
3332
- studentVocabMarkVoiceFail: markVoiceFail
3333
- };
3334
- };
3335
-
3336
- // src/hooks/useActivityFeedbackAccess.ts
3337
- import { useQuery as useQuery7 } from "@tanstack/react-query";
3338
- var activityFeedbackAccessQueryKeys = {
3339
- activityFeedbackAccess: (args) => ["activityFeedbackAccess", ...Object.values(args)]
3340
- };
3341
- var useActivityFeedbackAccess = ({
3342
- aiEnabled = false,
3343
- isActivityRoute = false
3344
- }) => {
3345
- var _a, _b, _c;
3346
- const { user } = useSpeakableApi();
3347
- const uid = user.auth.uid;
3348
- const isTeacher = (_a = user.profile) == null ? void 0 : _a.isTeacher;
3349
- const isStudent = (_b = user.profile) == null ? void 0 : _b.isStudent;
3350
- const userRoles = ((_c = user.profile) == null ? void 0 : _c.roles) || [];
3351
- const query2 = useQuery7({
3352
- queryKey: activityFeedbackAccessQueryKeys.activityFeedbackAccess({
3353
- aiEnabled,
3354
- isActivityRoute
3355
- }),
3356
- queryFn: async () => {
3357
- var _a2, _b2, _c2;
3358
- if (!uid) {
3359
- return {
3360
- canAccessFeedback: false,
3361
- reason: "Missing user ID",
3362
- isUnlimited: false,
3363
- accessType: "none"
3364
- };
3365
- }
3366
- try {
3367
- if (aiEnabled) {
3368
- return {
3369
- canAccessFeedback: true,
3370
- reason: "AI feedback enabled",
3371
- isUnlimited: true,
3372
- accessType: "ai_enabled"
3373
- };
3374
- }
3375
- if (isTeacher || userRoles.includes("ADMIN")) {
3376
- return {
3377
- canAccessFeedback: true,
3378
- reason: "Teacher preview access",
3379
- isUnlimited: true,
3380
- accessType: "teacher_preview"
3381
- };
3382
- }
3383
- if (isStudent && isActivityRoute) {
3384
- try {
3385
- const result = await ((_c2 = (_b2 = (_a2 = api).httpsCallable) == null ? void 0 : _b2.call(_a2, "checkStudentTeacherPlan")) == null ? void 0 : _c2({
3386
- studentId: uid
3387
- }));
3388
- const planCheckResult = result.data;
3389
- if (planCheckResult.canAccessFeedback) {
3390
- return {
3391
- canAccessFeedback: true,
3392
- reason: planCheckResult.reason || "Student access via teacher with active plan",
3393
- isUnlimited: planCheckResult.hasTeacherWithUnlimitedAccess,
3394
- accessType: "student_with_teacher_plan"
3395
- };
3396
- } else {
3397
- return {
3398
- canAccessFeedback: false,
3399
- reason: planCheckResult.reason || "No teacher with active plan found",
3400
- isUnlimited: false,
3401
- accessType: "none"
3402
- };
3403
- }
3404
- } catch (error) {
3405
- console.error("Error checking student teacher plan:", error);
3406
- return {
3407
- canAccessFeedback: false,
3408
- reason: "Error checking teacher plans",
3409
- isUnlimited: false,
3410
- accessType: "none"
3411
- };
3412
- }
3413
- }
3414
- return {
3415
- canAccessFeedback: false,
3416
- reason: "No access permissions found for current context",
3417
- isUnlimited: false,
3418
- accessType: "none"
3419
- };
3420
- } catch (error) {
3421
- console.error("Error checking activity feedback access:", error);
3422
- return {
3423
- canAccessFeedback: false,
3424
- reason: "Error checking access permissions",
3425
- isUnlimited: false,
3426
- accessType: "none"
3427
- };
3428
- }
3429
- },
3430
- enabled: !!uid,
3431
- staleTime: 5 * 60 * 1e3,
3432
- // 5 minutes
3433
- gcTime: 10 * 60 * 1e3
3434
- // 10 minutes
3435
- });
3436
- return {
3437
- ...query2
3438
- };
3439
- };
3440
-
3441
- // src/hooks/useOpenAI.ts
3442
- var useBaseOpenAI = ({
3443
- onTranscriptSuccess,
3444
- onTranscriptError,
3445
- onCompletionSuccess,
3446
- onCompletionError,
3447
- aiEnabled,
3448
- submitAudioResponse,
3449
- uploadAudioAndGetTranscript,
3450
- onGetAudioUrlAndTranscript
3451
- }) => {
3452
- const { user, queryClient } = useSpeakableApi();
3453
- const currentUserId = user.auth.uid;
3454
- const { data: feedbackAccess } = useActivityFeedbackAccess({
3455
- aiEnabled
3456
- });
3457
- const getTranscript2 = async (audioUrl, language, prompt) => {
3458
- var _a, _b, _c, _d, _e, _f;
3459
- const getGeminiTranscript = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "getGeminiTranscript");
3460
- const getAssemblyAITranscript = (_d = (_c = api).httpsCallable) == null ? void 0 : _d.call(_c, "transcribeAssemblyAIAudio");
3461
- const getWhisperTranscript = (_f = (_e = api).httpsCallable) == null ? void 0 : _f.call(_e, "transcribeAudio");
3462
- try {
3463
- const { data } = await (getWhisperTranscript == null ? void 0 : getWhisperTranscript({
3464
- audioUrl,
3465
- language
3466
- }));
3467
- const transcript = data;
3468
- if (transcript) {
3469
- return transcript;
3470
- }
3471
- } catch (error) {
3472
- console.log("Whisper transcript failed, trying Gemini fallback:", error);
3473
- }
3474
- try {
3475
- const { data } = await (getGeminiTranscript == null ? void 0 : getGeminiTranscript({
3476
- audioUrl,
3477
- targetLanguage: language,
3478
- prompt: prompt || ""
3479
- }));
3480
- const transcript = data.transcript;
3481
- if (transcript) {
3482
- return transcript;
3483
- }
3484
- } catch (error) {
3485
- console.log("Gemini transcript failed, trying AssemblyAI fallback:", error);
3486
- }
3487
- try {
3488
- const response = await (getAssemblyAITranscript == null ? void 0 : getAssemblyAITranscript({
3489
- audioUrl,
3490
- language
3491
- }));
3492
- const transcript = response == null ? void 0 : response.data;
3493
- if (transcript) {
3494
- return transcript;
3495
- }
3496
- throw new Error("Both transcript services failed");
3497
- } catch (error) {
3498
- console.log("AssemblyAI transcript also failed:", error);
3499
- onTranscriptError({
3500
- type: "TRANSCRIPT",
3501
- message: (error == null ? void 0 : error.message) || "Error getting transcript from both services"
3502
- });
3503
- throw new Error(error);
3504
- }
3505
- };
3506
- const getFreeResponseCompletion = async (messages, isFreeResponse, feedbackLanguage, gradingStandard = "actfl") => {
3507
- var _a, _b, _c, _d, _e;
3508
- const responseTool = getRespondCardTool({
3509
- language: feedbackLanguage,
3510
- standard: gradingStandard
3511
- });
3512
- try {
3513
- const createChatCompletion = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "createChatCompletion");
3514
- const {
3515
- data: {
3516
- response,
3517
- prompt_tokens = 0,
3518
- completion_tokens = 0,
3519
- success: aiSuccess = false
3520
- // the AI was able to generate a response
3521
- }
3522
- } = await (createChatCompletion == null ? void 0 : createChatCompletion({
3523
- chat: {
3524
- model: isFreeResponse ? "gpt-4-1106-preview" : "gpt-3.5-turbo-1106",
3525
- messages,
3526
- temperature: 0.7,
3527
- ...responseTool
3528
- },
3529
- type: isFreeResponse ? "LONG_RESPONSE" : "SHORT_RESPONSE"
3530
- }));
3531
- const functionArguments = JSON.parse(((_e = (_d = (_c = response == null ? void 0 : response.tool_calls) == null ? void 0 : _c[0]) == null ? void 0 : _d.function) == null ? void 0 : _e.arguments) || "{}");
3532
- const result = {
3533
- ...functionArguments,
3534
- prompt_tokens,
3535
- completion_tokens,
3536
- aiSuccess
3537
- };
3538
- onCompletionSuccess(result);
3539
- return result;
3540
- } catch (error) {
3541
- onCompletionError({
3542
- type: "COMPLETION",
3543
- message: (error == null ? void 0 : error.message) || "Error getting completion"
3544
- });
3545
- throw new Error(error);
3546
- }
3547
- };
3548
- const getFeedback = async ({
3549
- cardId,
3550
- language = "en",
3551
- // required
3552
- writtenResponse = null,
3553
- // if the type = RESPOND_WRITE
3554
- audio = null,
3555
- autoGrade = true,
3556
- file = null,
3557
- pagePrompt = null
3558
- }) => {
3559
- try {
3560
- if (!(feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback)) {
3561
- const result = {
3562
- noFeedbackAvailable: true,
3563
- success: true,
3564
- reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
3565
- accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
3566
- };
3567
- onCompletionSuccess(result);
3568
- return result;
3569
- }
3570
- let transcript;
3571
- let audioUrl = void 0;
3572
- if (writtenResponse) {
3573
- transcript = writtenResponse;
3574
- onTranscriptSuccess(writtenResponse);
3575
- } else if (typeof audio === "string" && file) {
3576
- if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
3577
- transcript = await getTranscript2(audio, language, pagePrompt != null ? pagePrompt : "");
3578
- audioUrl = audio;
3579
- onTranscriptSuccess(transcript);
3580
- } else {
3581
- console.info(
3582
- `Transcript not available: ${(feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access"}`
3583
- );
3584
- }
3585
- } else {
3586
- const response = await uploadAudioAndGetTranscript(audio || "", language, pagePrompt != null ? pagePrompt : "");
3587
- transcript = response.transcript;
3588
- audioUrl = response.audioUrl;
3589
- }
3590
- onGetAudioUrlAndTranscript == null ? void 0 : onGetAudioUrlAndTranscript({ transcript, audioUrl });
3591
- if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
3592
- const results = await getAIResponse({
3593
- cardId,
3594
- transcript: transcript || ""
3595
- });
3596
- let output = results;
3597
- if (!autoGrade) {
3598
- output = {
3599
- ...output,
3600
- noFeedbackAvailable: true,
3601
- success: true
3602
- };
3603
- }
3604
- onCompletionSuccess(output);
3605
- return output;
3606
- } else {
3607
- const result = {
3608
- noFeedbackAvailable: true,
3609
- success: true,
3610
- reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
3611
- accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
3612
- };
3613
- onCompletionSuccess(result);
3614
- return result;
3615
- }
3616
- } catch (error) {
3617
- console.error("Error getting feedback:", error);
3618
- throw new Error(error);
3619
- }
3620
- };
3621
- const onGetGeminiFeedback = async ({
3622
- cardId,
3623
- studentId,
3624
- studentResponse
3625
- }) => {
3626
- var _a, _b;
3627
- try {
3628
- const getGeminiFeedback = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "callGetFeedback");
3629
- return await (getGeminiFeedback == null ? void 0 : getGeminiFeedback({
3630
- cardId,
3631
- studentId,
3632
- studentResponse
3633
- }));
3634
- } catch (error) {
3635
- console.error("Error getting Gemini feedback:", error);
3636
- throw error;
3637
- }
3638
- };
3639
- const onGetProficiencyEstimate = async ({
3640
- cardId,
3641
- studentId,
3642
- studentResponse
3643
- }) => {
3644
- var _a, _b;
3645
- try {
3646
- const getProficiencyEstimate = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "getProficiencyEstimate");
3647
- return await (getProficiencyEstimate == null ? void 0 : getProficiencyEstimate({
3648
- cardId,
3649
- studentId,
3650
- studentResponse
3651
- }));
3652
- } catch (error) {
3653
- console.error("Error getting proficiency estimate:", error);
3654
- return {};
3655
- }
3656
- };
3657
- const getAIResponse = async ({ cardId, transcript }) => {
3658
- var _a;
3659
- try {
3660
- const card = getCardFromCache({
3661
- cardId,
3662
- queryClient
3663
- });
3664
- let feedbackData;
3665
- let proficiencyData = {};
3666
- if (card && card.grading_method === "manual") {
3667
- } else if (card && card.grading_method !== "standards_based") {
3668
- const [geminiResult, proficiencyResult] = await Promise.all([
3669
- onGetGeminiFeedback == null ? void 0 : onGetGeminiFeedback({
3670
- cardId,
3671
- studentId: currentUserId,
3672
- studentResponse: transcript
3673
- }),
3674
- onGetProficiencyEstimate == null ? void 0 : onGetProficiencyEstimate({
3675
- cardId,
3676
- studentId: currentUserId,
3677
- studentResponse: transcript
3678
- })
3679
- ]);
3680
- proficiencyData = (proficiencyResult == null ? void 0 : proficiencyResult.data) || {};
3681
- feedbackData = {
3682
- ...(_a = geminiResult == null ? void 0 : geminiResult.data) != null ? _a : {},
3683
- // @ts-ignore
3684
- proficiency_level: (proficiencyData == null ? void 0 : proficiencyData.proficiency_level) || null
3685
- };
3686
- } else {
3687
- const geminiResult = await (onGetGeminiFeedback == null ? void 0 : onGetGeminiFeedback({
3688
- cardId,
3689
- studentId: currentUserId,
3690
- studentResponse: transcript
3691
- }));
3692
- feedbackData = geminiResult == null ? void 0 : geminiResult.data;
3693
- }
3694
- const results = {
3695
- ...proficiencyData,
3696
- ...feedbackData,
3697
- aiSuccess: true,
3698
- promptSuccess: (feedbackData == null ? void 0 : feedbackData.success) || false,
3699
- transcript
3700
- };
3701
- return results;
3702
- } catch (error) {
3703
- onCompletionError({
3704
- type: "AI_FEEDBACK",
3705
- message: (error == null ? void 0 : error.message) || "Error getting ai feedback"
3706
- });
3707
- throw new Error(error);
3708
- }
3709
- };
3710
- return {
3711
- submitAudioResponse,
3712
- uploadAudioAndGetTranscript,
3713
- getTranscript: getTranscript2,
3714
- getFreeResponseCompletion,
3715
- getFeedback
3716
- };
3717
- };
3718
-
3719
- // src/lib/create-firebase-client-native.ts
3720
- import {
3721
- getDoc,
3722
- getDocs,
3723
- addDoc,
3724
- setDoc,
3725
- updateDoc,
3726
- deleteDoc,
3727
- runTransaction,
3728
- writeBatch,
3729
- doc,
3730
- collection,
3731
- query,
3732
- serverTimestamp,
3733
- orderBy,
3734
- limit,
3735
- startAt,
3736
- startAfter,
3737
- endAt,
3738
- endBefore,
3739
- where,
3740
- increment
3741
- } from "@react-native-firebase/firestore";
3742
-
3743
- // src/lib/create-firebase-client.ts
3744
- function createFsClientBase({
3745
- db,
3746
- helpers,
3747
- httpsCallable,
3748
- logEvent
3749
- }) {
3750
- const dbAsFirestore = db;
3751
- api.initialize({
3752
- db: dbAsFirestore,
3753
- helpers,
3754
- httpsCallable,
3755
- logEvent
3756
- });
3757
- return {
3758
- assignmentRepo: createAssignmentRepo(),
3759
- cardRepo: createCardRepo()
3760
- };
3761
- }
3762
-
3763
- // src/lib/create-firebase-client-native.ts
3764
- var createFsClientNative = ({ db, httpsCallable, logEvent }) => {
3765
- return createFsClientBase({
3766
- db,
3767
- httpsCallable,
3768
- logEvent,
3769
- helpers: {
3770
- getDoc,
3771
- getDocs,
3772
- addDoc,
3773
- setDoc,
3774
- updateDoc,
3775
- deleteDoc,
3776
- runTransaction,
3777
- writeBatch,
3778
- doc,
3779
- collection,
3780
- query,
3781
- serverTimestamp,
3782
- orderBy,
3783
- limit,
3784
- startAt,
3785
- startAfter,
3786
- endAt,
3787
- endBefore,
3788
- where,
3789
- increment
3790
- }
3791
- });
3792
- };
3793
- export {
3794
- ActivityPageType,
3795
- BASE_MULTIPLE_CHOICE_FIELD_VALUES,
3796
- BASE_REPEAT_FIELD_VALUES,
3797
- BASE_RESPOND_FIELD_VALUES,
3798
- CONVERSATION_PAGE_ACTIVITY_TYPES,
3799
- ConversationPageMode,
3800
- FeedbackTypesCard,
3801
- FsCtx,
3802
- LENIENCY_OPTIONS,
3803
- LeniencyCard,
3804
- MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES,
3805
- REPEAT_PAGE_ACTIVITY_TYPES,
3806
- RESPOND_AUDIO_PAGE_ACTIVITY_TYPES,
3807
- RESPOND_PAGE_ACTIVITY_TYPES,
3808
- RESPOND_WRITE_PAGE_ACTIVITY_TYPES,
3809
- SPEAKABLE_ANALYTICS,
3810
- SPEAKABLE_NOTIFICATIONS,
3811
- STUDENT_LEVELS_OPTIONS,
3812
- SpeakableNotificationTypes,
3813
- SpeakableProvider,
3814
- VerificationCardStatus,
3815
- assignmentQueryKeys,
3816
- cardsQueryKeys,
3817
- checkIsConversationPage,
3818
- checkIsMCPage,
3819
- checkIsMediaPage,
3820
- checkIsRepeatPage,
3821
- checkIsRespondAudioPage,
3822
- checkIsRespondPage,
3823
- checkIsRespondWrittenPage,
3824
- checkIsShortAnswerPage,
3825
- checkTypePageActivity,
3826
- cleanString,
3827
- createAssignmentRepo,
3828
- createCardRepo,
3829
- createFsClientNative as createFsClient,
3830
- createSetRepo,
3831
- creditQueryKeys,
3832
- debounce,
3833
- getCardFromCache,
3834
- getLabelPage,
3835
- getPageMediaData,
3836
- getPagePrompt,
3837
- getPhraseLength,
3838
- getRespondCardTool,
3839
- getSetFromCache,
3840
- getSingleMediaPageData,
3841
- getTotalCompletedCards,
3842
- getTranscript,
3843
- getTranscriptCycle,
3844
- getWordHash,
3845
- purify,
3846
- refsCardsFiresotre,
3847
- refsSetsFirestore,
3848
- scoreQueryKeys,
3849
- setsQueryKeys,
3850
- updateCardInCache,
3851
- updateSetInCache,
3852
- useActivity,
3853
- useActivityFeedbackAccess,
3854
- useAssignment,
3855
- useBaseOpenAI,
3856
- useCards,
3857
- useClearScore,
3858
- useClearScoreV2,
3859
- useCreateCard,
3860
- useCreateCards,
3861
- useCreateNotification,
3862
- useGetCard,
3863
- useOrganizationAccess,
3864
- useScore,
3865
- useSet,
3866
- useSpeakableApi,
3867
- useSpeakableTranscript,
3868
- useSpeakableTranscriptCycle,
3869
- useSubmitAssignmentScore,
3870
- useSubmitPracticeScore,
3871
- useUpdateCardScore,
3872
- useUpdateScore,
3873
- useUpdateStudentVocab,
3874
- useUserCredits
3875
- };
3876
- //# sourceMappingURL=index.native.mjs.map