@speakableio/core 1.0.59 → 1.0.60

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