@vue-skuilder/db 0.2.36 → 0.2.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/index.cjs +91 -70
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/navigators/generators/prescribed.mjs +29 -11
- package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
- package/dist/core/versionStamps.mjs +1 -1
- package/dist/impl/common/BaseUserDB.mjs +14 -2
- package/dist/impl/common/BaseUserDB.mjs.map +1 -1
- package/dist/impl/couch/CourseSyncService.mjs +88 -10
- package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
- package/dist/impl/couch/PouchDataLayerProvider.mjs +16 -1
- package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -1
- package/dist/impl/couch/courseAPI.mjs +24 -10
- package/dist/impl/couch/courseAPI.mjs.map +1 -1
- package/dist/impl/couch/courseDB.mjs +15 -9
- package/dist/impl/couch/courseDB.mjs.map +1 -1
- package/dist/impl/couch/index.cjs +163 -62
- package/dist/impl/couch/index.cjs.map +1 -1
- package/dist/impl/couch/index.d.ts +22 -1
- package/dist/impl/couch/index.mjs +20 -3
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/static/index.cjs +39 -15
- package/dist/impl/static/index.cjs.map +1 -1
- package/dist/index.cjs +202 -92
- package/dist/index.cjs.map +1 -1
- package/package.json +3 -3
- package/src/core/navigators/generators/prescribed.ts +42 -16
- package/src/impl/common/BaseUserDB.ts +15 -2
- package/src/impl/couch/CourseSyncService.ts +130 -20
- package/src/impl/couch/PouchDataLayerProvider.ts +14 -1
- package/src/impl/couch/courseAPI.ts +26 -12
- package/src/impl/couch/courseDB.ts +20 -12
- package/src/impl/couch/index.ts +16 -5
- package/tests/impl/courseSync.test.ts +139 -0
|
@@ -171,6 +171,7 @@ declare function getClassroomConfig(classID: string): Promise<ClassroomConfig>;
|
|
|
171
171
|
declare function addNote55(courseID: string, codeCourse: string, shape: DataShape, data: unknown, author: string, tags: string[], uploads?: {
|
|
172
172
|
[x: string]: PouchDB.Core.FullAttachment;
|
|
173
173
|
}, elo?: CourseElo): Promise<PouchDB.Core.Response>;
|
|
174
|
+
declare function invalidateCourseConfigCache(courseID: string): void;
|
|
174
175
|
declare function getCredentialledCourseConfig(courseID: string): Promise<CourseConfig$1>;
|
|
175
176
|
/**
|
|
176
177
|
Assciates a tag with a card.
|
|
@@ -467,6 +468,19 @@ declare class CourseSyncService {
|
|
|
467
468
|
* LettersPractice hardcodes this).
|
|
468
469
|
*/
|
|
469
470
|
ensureSynced(courseId: string, forceEnabled?: boolean): Promise<void>;
|
|
471
|
+
/**
|
|
472
|
+
* A replica completed on an earlier page load is ready now, refreshed in the
|
|
473
|
+
* background; anything else goes through a full performSync.
|
|
474
|
+
*/
|
|
475
|
+
private startSync;
|
|
476
|
+
/**
|
|
477
|
+
* Bring a ready replica up to date without taking it away from readers.
|
|
478
|
+
* Failures leave it ready (and outdated).
|
|
479
|
+
*/
|
|
480
|
+
private refreshInBackground;
|
|
481
|
+
private hasSyncMarker;
|
|
482
|
+
private writeSyncMarker;
|
|
483
|
+
private clearSyncMarker;
|
|
470
484
|
/**
|
|
471
485
|
* Get the local PouchDB for a course, or null if not available.
|
|
472
486
|
*
|
|
@@ -591,6 +605,13 @@ declare const localUserDB: PouchDB.Database;
|
|
|
591
605
|
* - Falls back to cookie auth for browser environments
|
|
592
606
|
*/
|
|
593
607
|
declare function createPouchDBConfig(): PouchDB.Configuration.RemoteDatabaseConfiguration;
|
|
608
|
+
/**
|
|
609
|
+
* The remote course DB, one handle per URL for the page's lifetime.
|
|
610
|
+
*
|
|
611
|
+
* `skip_setup`: a fresh handle otherwise checks the DB exists (and would try to
|
|
612
|
+
* create it) before its first request: one extra round trip per handle. Course
|
|
613
|
+
* DBs are only created server-side (express), never through this handle.
|
|
614
|
+
*/
|
|
594
615
|
declare function getCourseDB(courseID: string): PouchDB.Database;
|
|
595
616
|
declare function getLatestVersion(): Promise<string>;
|
|
596
617
|
/**
|
|
@@ -624,4 +645,4 @@ declare function getStartAndEndKeys(key: string): {
|
|
|
624
645
|
endkey: string;
|
|
625
646
|
};
|
|
626
647
|
|
|
627
|
-
export { AdminDB, CLASSROOM_CONFIG, ClassroomLookupDB, type ClassroomMessage, CouchDBSyncStrategy, CourseDB, CourseSyncService, type CourseSyncState, type CourseSyncStatus, CoursesDB, REVIEW_TIME_FORMAT, type ReplicationOptions, StudentClassroomDB, StudyContentSource, StudySessionItem, TeacherClassroomDB, addNote55, addTagToCard, createPouchDBConfig, createTag, deleteTag, filterAllDocsByPrefix, getAncestorTagIDs, getAppliedTags, getChildTagStubs, getClassroomConfig, getClassroomDB, getCouchUserDB, getCourseDB, getCourseDataShapes, getCourseDoc, getCourseDocs, getCourseQuestionTypes, getCourseTagStubs, getCredentialledCourseConfig, getCredentialledDataShapes, getLatestVersion, getRandomCards, getStartAndEndKeys, getTag, getTagID, localUserDB, removeTagFromCard, scheduleCardReview, updateCardElo, updateCredentialledCourseConfig, updateGuestAccountExpirationDate, updateTag, usernameIsAvailable };
|
|
648
|
+
export { AdminDB, CLASSROOM_CONFIG, ClassroomLookupDB, type ClassroomMessage, CouchDBSyncStrategy, CourseDB, CourseSyncService, type CourseSyncState, type CourseSyncStatus, CoursesDB, REVIEW_TIME_FORMAT, type ReplicationOptions, StudentClassroomDB, StudyContentSource, StudySessionItem, TeacherClassroomDB, addNote55, addTagToCard, createPouchDBConfig, createTag, deleteTag, filterAllDocsByPrefix, getAncestorTagIDs, getAppliedTags, getChildTagStubs, getClassroomConfig, getClassroomDB, getCouchUserDB, getCourseDB, getCourseDataShapes, getCourseDoc, getCourseDocs, getCourseQuestionTypes, getCourseTagStubs, getCredentialledCourseConfig, getCredentialledDataShapes, getLatestVersion, getRandomCards, getStartAndEndKeys, getTag, getTagID, invalidateCourseConfigCache, localUserDB, removeTagFromCard, scheduleCardReview, updateCardElo, updateCredentialledCourseConfig, updateGuestAccountExpirationDate, updateTag, usernameIsAvailable };
|
|
@@ -6,7 +6,7 @@ import { DocType, DocTypePrefixes, GuestUsername, log } from "../../core/types/t
|
|
|
6
6
|
import { hexEncode } from "../common/userDBKeys.mjs";
|
|
7
7
|
import { AdminDB } from "./adminDB.mjs";
|
|
8
8
|
import { CourseDB, CoursesDB, createTag, deleteTag, getAncestorTagIDs, getAppliedTags, getChildTagStubs, getCourseDataShapes, getCourseQuestionTypes, getCourseTagStubs, getCredentialledDataShapes, getTag, removeTagFromCard, updateCardElo, updateCredentialledCourseConfig, updateTag } from "./courseDB.mjs";
|
|
9
|
-
import { addNote55, addTagToCard, getCredentialledCourseConfig, getTagID } from "./courseAPI.mjs";
|
|
9
|
+
import { addNote55, addTagToCard, getCredentialledCourseConfig, getTagID, invalidateCourseConfigCache } from "./courseAPI.mjs";
|
|
10
10
|
import { CourseSyncService } from "./CourseSyncService.mjs";
|
|
11
11
|
import { CouchDBSyncStrategy } from "./CouchDBSyncStrategy.mjs";
|
|
12
12
|
import { CLASSROOM_CONFIG, ClassroomLookupDB, StudentClassroomDB, TeacherClassroomDB, getClassroomConfig, getClassroomDB } from "./classroomDB.mjs";
|
|
@@ -41,8 +41,25 @@ function createPouchDBConfig() {
|
|
|
41
41
|
function getCouchDB(dbName) {
|
|
42
42
|
return new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + dbName, createPouchDBConfig());
|
|
43
43
|
}
|
|
44
|
+
const courseDBHandles = /* @__PURE__ */ new Map();
|
|
45
|
+
/**
|
|
46
|
+
* The remote course DB, one handle per URL for the page's lifetime.
|
|
47
|
+
*
|
|
48
|
+
* `skip_setup`: a fresh handle otherwise checks the DB exists (and would try to
|
|
49
|
+
* create it) before its first request: one extra round trip per handle. Course
|
|
50
|
+
* DBs are only created server-side (express), never through this handle.
|
|
51
|
+
*/
|
|
44
52
|
function getCourseDB(courseID) {
|
|
45
|
-
|
|
53
|
+
const url = ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + "coursedb-" + courseID;
|
|
54
|
+
let db = courseDBHandles.get(url);
|
|
55
|
+
if (!db) {
|
|
56
|
+
db = new pouchdb_setup_default(url, {
|
|
57
|
+
...createPouchDBConfig(),
|
|
58
|
+
skip_setup: true
|
|
59
|
+
});
|
|
60
|
+
courseDBHandles.set(url, db);
|
|
61
|
+
}
|
|
62
|
+
return db;
|
|
46
63
|
}
|
|
47
64
|
async function getLatestVersion() {
|
|
48
65
|
try {
|
|
@@ -152,6 +169,6 @@ function getStartAndEndKeys(key) {
|
|
|
152
169
|
};
|
|
153
170
|
}
|
|
154
171
|
//#endregion
|
|
155
|
-
export { AdminDB, CLASSROOM_CONFIG, ClassroomLookupDB, CouchDBSyncStrategy, CourseDB, CourseSyncService, CoursesDB, REVIEW_TIME_FORMAT, StudentClassroomDB, TeacherClassroomDB, addNote55, addTagToCard, createPouchDBConfig, createTag, deleteTag, filterAllDocsByPrefix, getAncestorTagIDs, getAppliedTags, getChildTagStubs, getClassroomConfig, getClassroomDB, getCouchUserDB, getCourseDB, getCourseDataShapes, getCourseDoc, getCourseDocs, getCourseQuestionTypes, getCourseTagStubs, getCredentialledCourseConfig, getCredentialledDataShapes, getLatestVersion, getRandomCards, getStartAndEndKeys, getStudySource, getTag, getTagID, hexEncode, isReview, localUserDB, removeTagFromCard, scheduleCardReview, updateCardElo, updateCredentialledCourseConfig, updateGuestAccountExpirationDate, updateTag, usernameIsAvailable };
|
|
172
|
+
export { AdminDB, CLASSROOM_CONFIG, ClassroomLookupDB, CouchDBSyncStrategy, CourseDB, CourseSyncService, CoursesDB, REVIEW_TIME_FORMAT, StudentClassroomDB, TeacherClassroomDB, addNote55, addTagToCard, createPouchDBConfig, createTag, deleteTag, filterAllDocsByPrefix, getAncestorTagIDs, getAppliedTags, getChildTagStubs, getClassroomConfig, getClassroomDB, getCouchUserDB, getCourseDB, getCourseDataShapes, getCourseDoc, getCourseDocs, getCourseQuestionTypes, getCourseTagStubs, getCredentialledCourseConfig, getCredentialledDataShapes, getLatestVersion, getRandomCards, getStartAndEndKeys, getStudySource, getTag, getTagID, hexEncode, invalidateCourseConfigCache, isReview, localUserDB, removeTagFromCard, scheduleCardReview, updateCardElo, updateCredentialledCourseConfig, updateGuestAccountExpirationDate, updateTag, usernameIsAvailable };
|
|
156
173
|
|
|
157
174
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["pouch"],"sources":["../../../src/impl/couch/index.ts"],"sourcesContent":["import { ENV } from '@db/factory';\nimport {\n DocType,\n DocTypePrefixes,\n GuestUsername,\n log,\n SkuilderCourseData,\n} from '../../core/types/types-legacy';\nimport fetch from 'cross-fetch';\n// import { getCurrentUser } from '../../stores/useAuthStore';\nimport moment, { Moment } from 'moment';\nimport { logger } from '@db/util/logger';\n\nimport pouch from './pouchdb-setup';\nimport { hexEncode } from '../common/userDBKeys';\n\nimport { ScheduledCard } from '@db/core/types/user';\n\nconst expiryDocID: string = 'GuestAccountExpirationDate';\n\nconst GUEST_LOCAL_DB = `userdb-${GuestUsername}`;\nexport const localUserDB: PouchDB.Database = new pouch(GUEST_LOCAL_DB);\n\nexport { hexEncode };\nconst pouchDBincludeCredentialsConfig: PouchDB.Configuration.RemoteDatabaseConfiguration = {\n fetch(url: string | Request, opts: RequestInit): Promise<Response> {\n opts.credentials = 'include';\n\n return (pouch as any).fetch(url, opts);\n },\n} as PouchDB.Configuration.RemoteDatabaseConfiguration;\n\n/**\n * Creates PouchDB configuration with appropriate authentication method\n * - Uses HTTP Basic Auth when credentials are available (Node.js/MCP)\n * - Falls back to cookie auth for browser environments\n */\nexport function createPouchDBConfig(): PouchDB.Configuration.RemoteDatabaseConfiguration {\n // Check if running in Node.js with explicit credentials\n const hasExplicitCredentials = ENV.COUCHDB_USERNAME && ENV.COUCHDB_PASSWORD;\n const isNodeEnvironment = typeof window === 'undefined';\n \n if (hasExplicitCredentials && isNodeEnvironment) {\n // Use HTTP Basic Auth for Node.js environments (MCP server)\n return {\n fetch(url: string | Request, opts: RequestInit = {}): Promise<Response> {\n const basicAuth = btoa(`${ENV.COUCHDB_USERNAME}:${ENV.COUCHDB_PASSWORD}`);\n const headers = new Headers(opts.headers || {});\n headers.set('Authorization', `Basic ${basicAuth}`);\n \n const newOpts = {\n ...opts,\n headers: headers\n };\n \n return (pouch as any).fetch(url, newOpts);\n }\n } as PouchDB.Configuration.RemoteDatabaseConfiguration;\n }\n \n // Use cookie-based auth for browser environments or when no explicit credentials\n return pouchDBincludeCredentialsConfig;\n}\n\nfunction getCouchDB(dbName: string): PouchDB.Database {\n return new pouch(\n ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + dbName,\n createPouchDBConfig()\n );\n}\n\nexport function getCourseDB(courseID: string): PouchDB.Database {\n // todo: keep a cache of opened courseDBs? need to benchmark this somehow\n return new pouch(\n ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + 'coursedb-' + courseID,\n createPouchDBConfig()\n );\n}\n\nexport async function getLatestVersion() {\n try {\n const docs = await getCouchDB('version').allDocs({\n descending: true,\n limit: 1,\n });\n if (docs && docs.rows && docs.rows[0]) {\n return docs.rows[0].id;\n } else {\n return '0.0.0';\n }\n } catch {\n return '-1';\n }\n}\n\n/**\n * Checks the remote couchdb to see if a given username is available\n * @param username The username to be checked\n */\nexport async function usernameIsAvailable(username: string): Promise<boolean> {\n log(`Checking availability of ${username}`);\n \n // Legacy XMLHttpRequest implementation (browser sync)\n // const req = new XMLHttpRequest();\n // const url = ENV.COUCHDB_SERVER_URL + 'userdb-' + hexEncode(username);\n // req.open('HEAD', url, false);\n // req.send();\n // return req.status === 404;\n \n try {\n const url = ENV.COUCHDB_SERVER_URL + 'userdb-' + hexEncode(username);\n const response = await fetch(url, { method: 'HEAD' });\n return response.status === 404;\n } catch (error) {\n log(`Error checking username availability: ${error}`);\n return false;\n }\n}\n\nexport function updateGuestAccountExpirationDate(guestDB: PouchDB.Database<object>) {\n const currentTime = moment.utc();\n const expirationDate: string = currentTime.add(2, 'months').toISOString();\n\n void guestDB\n .get(expiryDocID)\n .then((doc) => {\n return guestDB.put({\n _id: expiryDocID,\n _rev: doc._rev,\n date: expirationDate,\n });\n })\n .catch(() => {\n return guestDB.put({\n _id: expiryDocID,\n date: expirationDate,\n });\n });\n}\n\nexport function getCourseDocs<T extends SkuilderCourseData>(\n courseID: string,\n docIDs: string[],\n options: PouchDB.Core.AllDocsOptions = {}\n) {\n return getCourseDB(courseID).allDocs<T>({\n ...options,\n keys: docIDs,\n });\n}\n\nexport function getCourseDoc<T extends SkuilderCourseData>(\n courseID: string,\n docID: PouchDB.Core.DocumentId,\n options: PouchDB.Core.GetOptions = {}\n): Promise<T> {\n return getCourseDB(courseID).get<T>(docID, options);\n}\n\n/**\n * Returns *all* cards from the parameter courses, in\n * 'qualified' card format (\"courseid-cardid\")\n *\n * @param courseIDs A list of all course_ids to get cards from\n */\nexport async function getRandomCards(courseIDs: string[]) {\n if (courseIDs.length === 0) {\n throw new Error(`getRandomCards:\\n\\tAttempted to get all cards from no courses!`);\n } else {\n const courseResults = await Promise.all(\n courseIDs.map((course) => {\n return getCourseDB(course).find({\n selector: {\n docType: DocType.CARD,\n },\n limit: 1000,\n });\n })\n );\n\n const ret: string[] = [];\n courseResults.forEach((courseCards, index) => {\n courseCards.docs.forEach((doc) => {\n ret.push(`${courseIDs[index]}-${doc._id}`);\n });\n });\n\n return ret;\n }\n}\n\nexport const REVIEW_TIME_FORMAT: string = 'YYYY-MM-DD--kk:mm:ss-SSS';\n\nexport function getCouchUserDB(username: string): PouchDB.Database {\n const guestAccount: boolean = false;\n // console.log(`Getting user db: ${username}`);\n\n const hexName = hexEncode(username);\n const dbName = `userdb-${hexName}`;\n log(`Fetching user database: ${dbName} (${username})`);\n\n // odd construction here the result of a bug in the\n // interaction between pouch, pouch-auth.\n // see: https://github.com/pouchdb-community/pouchdb-authentication/issues/239\n const ret = new pouch(\n ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + dbName,\n createPouchDBConfig()\n );\n if (guestAccount) {\n updateGuestAccountExpirationDate(ret);\n }\n\n return ret;\n}\n\nexport function scheduleCardReview(review: {\n user: string;\n course_id: string;\n card_id: PouchDB.Core.DocumentId;\n time: Moment;\n scheduledFor: ScheduledCard['scheduledFor'];\n schedulingAgentId: ScheduledCard['schedulingAgentId'];\n}) {\n const now = moment.utc();\n logger.info(`Scheduling for review in: ${review.time.diff(now, 'h') / 24} days`);\n void getCouchUserDB(review.user).put<ScheduledCard>({\n _id: DocTypePrefixes[DocType.SCHEDULED_CARD] + review.time.format(REVIEW_TIME_FORMAT),\n cardId: review.card_id,\n reviewTime: review.time.toISOString(),\n courseId: review.course_id,\n scheduledAt: now.toISOString(),\n scheduledFor: review.scheduledFor,\n schedulingAgentId: review.schedulingAgentId,\n });\n}\n\nexport function filterAllDocsByPrefix<T>(\n db: PouchDB.Database,\n prefix: string,\n opts?: PouchDB.Core.AllDocsOptions\n) {\n // see couchdb docs 6.2.2:\n // Guide to Views -> Views Collation -> String Ranges\n const options: PouchDB.Core.AllDocsWithinRangeOptions = {\n startkey: prefix,\n endkey: prefix + '\\ufff0',\n include_docs: true,\n };\n\n if (opts) {\n Object.assign(options, opts);\n }\n return db.allDocs<T>(options);\n}\n\nexport function getStartAndEndKeys(key: string): {\n startkey: string;\n endkey: string;\n} {\n return {\n startkey: key,\n endkey: key + '\\ufff0',\n };\n}\n\n//////////////////////\n// Package exports\n//////////////////////\n\nexport * from '../../core/interfaces/contentSource';\nexport * from './adminDB';\nexport * from './classroomDB';\nexport * from './courseAPI';\nexport * from './courseDB';\nexport * from './CourseSyncService';\nexport * from './CouchDBSyncStrategy';\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAAM,cAAsB;AAG5B,MAAa,cAAgC,IAAIA,sBAD1B,UAAU,gBACqC;AAGtE,MAAM,kCAAqF,EACzF,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AC,IAAmB;EAClD,KAAK,gBAAgB,QAAQ,kBAAkB,OAAO,KAAK,OAAO,mBAAmB;EACrF,QAAQ,OAAO;EACf,YAAY,OAAO,KAAK,aAAa;EACrC,UAAU,OAAO;EACjB,aAAa,IAAI,aAAa;EAC9B,cAAc,OAAO;EACrB,mBAAmB,OAAO;EAC3B,CAAC;;AAGJ,SAAgB,sBACd,IACA,QACA,MACA;CAGA,MAAM,UAAkD;EACtD,UAAU;EACV,QAAQ,SAAS;EACjB,cAAc;EACf;AAED,KAAI,KACF,QAAO,OAAO,SAAS,KAAK;AAE9B,QAAO,GAAG,QAAW,QAAQ;;AAG/B,SAAgB,mBAAmB,KAGjC;AACA,QAAO;EACL,UAAU;EACV,QAAQ,MAAM;EACf"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["pouch"],"sources":["../../../src/impl/couch/index.ts"],"sourcesContent":["import { ENV } from '@db/factory';\nimport {\n DocType,\n DocTypePrefixes,\n GuestUsername,\n log,\n SkuilderCourseData,\n} from '../../core/types/types-legacy';\nimport fetch from 'cross-fetch';\n// import { getCurrentUser } from '../../stores/useAuthStore';\nimport moment, { Moment } from 'moment';\nimport { logger } from '@db/util/logger';\n\nimport pouch from './pouchdb-setup';\nimport { hexEncode } from '../common/userDBKeys';\n\nimport { ScheduledCard } from '@db/core/types/user';\n\nconst expiryDocID: string = 'GuestAccountExpirationDate';\n\nconst GUEST_LOCAL_DB = `userdb-${GuestUsername}`;\nexport const localUserDB: PouchDB.Database = new pouch(GUEST_LOCAL_DB);\n\nexport { hexEncode };\nconst pouchDBincludeCredentialsConfig: PouchDB.Configuration.RemoteDatabaseConfiguration = {\n fetch(url: string | Request, opts: RequestInit): Promise<Response> {\n opts.credentials = 'include';\n\n return (pouch as any).fetch(url, opts);\n },\n} as PouchDB.Configuration.RemoteDatabaseConfiguration;\n\n/**\n * Creates PouchDB configuration with appropriate authentication method\n * - Uses HTTP Basic Auth when credentials are available (Node.js/MCP)\n * - Falls back to cookie auth for browser environments\n */\nexport function createPouchDBConfig(): PouchDB.Configuration.RemoteDatabaseConfiguration {\n // Check if running in Node.js with explicit credentials\n const hasExplicitCredentials = ENV.COUCHDB_USERNAME && ENV.COUCHDB_PASSWORD;\n const isNodeEnvironment = typeof window === 'undefined';\n \n if (hasExplicitCredentials && isNodeEnvironment) {\n // Use HTTP Basic Auth for Node.js environments (MCP server)\n return {\n fetch(url: string | Request, opts: RequestInit = {}): Promise<Response> {\n const basicAuth = btoa(`${ENV.COUCHDB_USERNAME}:${ENV.COUCHDB_PASSWORD}`);\n const headers = new Headers(opts.headers || {});\n headers.set('Authorization', `Basic ${basicAuth}`);\n \n const newOpts = {\n ...opts,\n headers: headers\n };\n \n return (pouch as any).fetch(url, newOpts);\n }\n } as PouchDB.Configuration.RemoteDatabaseConfiguration;\n }\n \n // Use cookie-based auth for browser environments or when no explicit credentials\n return pouchDBincludeCredentialsConfig;\n}\n\nfunction getCouchDB(dbName: string): PouchDB.Database {\n return new pouch(\n ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + dbName,\n createPouchDBConfig()\n );\n}\n\nconst courseDBHandles = new Map<string, PouchDB.Database>();\n\n/**\n * The remote course DB, one handle per URL for the page's lifetime.\n *\n * `skip_setup`: a fresh handle otherwise checks the DB exists (and would try to\n * create it) before its first request: one extra round trip per handle. Course\n * DBs are only created server-side (express), never through this handle.\n */\nexport function getCourseDB(courseID: string): PouchDB.Database {\n const url = ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + 'coursedb-' + courseID;\n let db = courseDBHandles.get(url);\n if (!db) {\n db = new pouch(url, { ...createPouchDBConfig(), skip_setup: true });\n courseDBHandles.set(url, db);\n }\n return db;\n}\n\nexport async function getLatestVersion() {\n try {\n const docs = await getCouchDB('version').allDocs({\n descending: true,\n limit: 1,\n });\n if (docs && docs.rows && docs.rows[0]) {\n return docs.rows[0].id;\n } else {\n return '0.0.0';\n }\n } catch {\n return '-1';\n }\n}\n\n/**\n * Checks the remote couchdb to see if a given username is available\n * @param username The username to be checked\n */\nexport async function usernameIsAvailable(username: string): Promise<boolean> {\n log(`Checking availability of ${username}`);\n \n // Legacy XMLHttpRequest implementation (browser sync)\n // const req = new XMLHttpRequest();\n // const url = ENV.COUCHDB_SERVER_URL + 'userdb-' + hexEncode(username);\n // req.open('HEAD', url, false);\n // req.send();\n // return req.status === 404;\n \n try {\n const url = ENV.COUCHDB_SERVER_URL + 'userdb-' + hexEncode(username);\n const response = await fetch(url, { method: 'HEAD' });\n return response.status === 404;\n } catch (error) {\n log(`Error checking username availability: ${error}`);\n return false;\n }\n}\n\nexport function updateGuestAccountExpirationDate(guestDB: PouchDB.Database<object>) {\n const currentTime = moment.utc();\n const expirationDate: string = currentTime.add(2, 'months').toISOString();\n\n void guestDB\n .get(expiryDocID)\n .then((doc) => {\n return guestDB.put({\n _id: expiryDocID,\n _rev: doc._rev,\n date: expirationDate,\n });\n })\n .catch(() => {\n return guestDB.put({\n _id: expiryDocID,\n date: expirationDate,\n });\n });\n}\n\nexport function getCourseDocs<T extends SkuilderCourseData>(\n courseID: string,\n docIDs: string[],\n options: PouchDB.Core.AllDocsOptions = {}\n) {\n return getCourseDB(courseID).allDocs<T>({\n ...options,\n keys: docIDs,\n });\n}\n\nexport function getCourseDoc<T extends SkuilderCourseData>(\n courseID: string,\n docID: PouchDB.Core.DocumentId,\n options: PouchDB.Core.GetOptions = {}\n): Promise<T> {\n return getCourseDB(courseID).get<T>(docID, options);\n}\n\n/**\n * Returns *all* cards from the parameter courses, in\n * 'qualified' card format (\"courseid-cardid\")\n *\n * @param courseIDs A list of all course_ids to get cards from\n */\nexport async function getRandomCards(courseIDs: string[]) {\n if (courseIDs.length === 0) {\n throw new Error(`getRandomCards:\\n\\tAttempted to get all cards from no courses!`);\n } else {\n const courseResults = await Promise.all(\n courseIDs.map((course) => {\n return getCourseDB(course).find({\n selector: {\n docType: DocType.CARD,\n },\n limit: 1000,\n });\n })\n );\n\n const ret: string[] = [];\n courseResults.forEach((courseCards, index) => {\n courseCards.docs.forEach((doc) => {\n ret.push(`${courseIDs[index]}-${doc._id}`);\n });\n });\n\n return ret;\n }\n}\n\nexport const REVIEW_TIME_FORMAT: string = 'YYYY-MM-DD--kk:mm:ss-SSS';\n\nexport function getCouchUserDB(username: string): PouchDB.Database {\n const guestAccount: boolean = false;\n // console.log(`Getting user db: ${username}`);\n\n const hexName = hexEncode(username);\n const dbName = `userdb-${hexName}`;\n log(`Fetching user database: ${dbName} (${username})`);\n\n // odd construction here the result of a bug in the\n // interaction between pouch, pouch-auth.\n // see: https://github.com/pouchdb-community/pouchdb-authentication/issues/239\n const ret = new pouch(\n ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + dbName,\n createPouchDBConfig()\n );\n if (guestAccount) {\n updateGuestAccountExpirationDate(ret);\n }\n\n return ret;\n}\n\nexport function scheduleCardReview(review: {\n user: string;\n course_id: string;\n card_id: PouchDB.Core.DocumentId;\n time: Moment;\n scheduledFor: ScheduledCard['scheduledFor'];\n schedulingAgentId: ScheduledCard['schedulingAgentId'];\n}) {\n const now = moment.utc();\n logger.info(`Scheduling for review in: ${review.time.diff(now, 'h') / 24} days`);\n void getCouchUserDB(review.user).put<ScheduledCard>({\n _id: DocTypePrefixes[DocType.SCHEDULED_CARD] + review.time.format(REVIEW_TIME_FORMAT),\n cardId: review.card_id,\n reviewTime: review.time.toISOString(),\n courseId: review.course_id,\n scheduledAt: now.toISOString(),\n scheduledFor: review.scheduledFor,\n schedulingAgentId: review.schedulingAgentId,\n });\n}\n\nexport function filterAllDocsByPrefix<T>(\n db: PouchDB.Database,\n prefix: string,\n opts?: PouchDB.Core.AllDocsOptions\n) {\n // see couchdb docs 6.2.2:\n // Guide to Views -> Views Collation -> String Ranges\n const options: PouchDB.Core.AllDocsWithinRangeOptions = {\n startkey: prefix,\n endkey: prefix + '\\ufff0',\n include_docs: true,\n };\n\n if (opts) {\n Object.assign(options, opts);\n }\n return db.allDocs<T>(options);\n}\n\nexport function getStartAndEndKeys(key: string): {\n startkey: string;\n endkey: string;\n} {\n return {\n startkey: key,\n endkey: key + '\\ufff0',\n };\n}\n\n//////////////////////\n// Package exports\n//////////////////////\n\nexport * from '../../core/interfaces/contentSource';\nexport * from './adminDB';\nexport * from './classroomDB';\nexport * from './courseAPI';\nexport * from './courseDB';\nexport * from './CourseSyncService';\nexport * from './CouchDBSyncStrategy';\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAAM,cAAsB;AAG5B,MAAa,cAAgC,IAAIA,sBAD1B,UAAU,gBACqC;AAGtE,MAAM,kCAAqF,EACzF,MAAM,KAAuB,MAAsC;AACjE,MAAK,cAAc;AAEnB,QAAQA,sBAAc,MAAM,KAAK,KAAK;GAEzC;;;;;;AAOD,SAAgB,sBAAyE;AAKvF,KAH+B,IAAI,oBAAoB,IAAI,oBACjC,OAAO,WAAW,YAI1C,QAAO,EACL,MAAM,KAAuB,OAAoB,EAAE,EAAqB;EACtE,MAAM,YAAY,KAAK,GAAG,IAAI,iBAAiB,GAAG,IAAI,mBAAmB;EACzE,MAAM,UAAU,IAAI,QAAQ,KAAK,WAAW,EAAE,CAAC;AAC/C,UAAQ,IAAI,iBAAiB,SAAS,YAAY;EAElD,MAAM,UAAU;GACd,GAAG;GACM;GACV;AAED,SAAQA,sBAAc,MAAM,KAAK,QAAQ;IAE5C;AAIH,QAAO;;AAGT,SAAS,WAAW,QAAkC;AACpD,QAAO,IAAIA,sBACT,IAAI,0BAA0B,QAAQ,IAAI,qBAAqB,QAC/D,qBAAqB,CACtB;;AAGH,MAAM,kCAAkB,IAAI,KAA+B;;;;;;;;AAS3D,SAAgB,YAAY,UAAoC;CAC9D,MAAM,MAAM,IAAI,0BAA0B,QAAQ,IAAI,qBAAqB,cAAc;CACzF,IAAI,KAAK,gBAAgB,IAAI,IAAI;AACjC,KAAI,CAAC,IAAI;AACP,OAAK,IAAIA,sBAAM,KAAK;GAAE,GA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IAC9B,UAAU,EACR,SAAS,QAAQ,MAClB;IACD,OAAO;IACR,CAAC;IACF,CACH;EAED,MAAM,MAAgB,EAAE;AACxB,gBAAc,SAAS,aAAa,UAAU;AAC5C,eAAY,KAAK,SAAS,QAAQ;AAChC,QAAI,KAAK,GAAG,UAAU,OAAO,GAAG,IAAI,MAAM;KAC1C;IACF;AAEF,SAAO;;;AAIX,MAAa,qBAA6B;AAE1C,SAAgB,eAAe,UAAoC;CAKjE,MAAM,SAAS,UADC,UAAU,SAAS;AAEnC,KAAI,2BAA2B,OAAO,IAAI,SAAS,GAAG;AAatD,QARY,IAAIA,sBACd,IAAI,0BAA0B,QAAQ,IAAI,qBAAqB,QAC/D,qBAAqB,CACtB;;AAQH,SAAgB,mBAAmB,QAOhC;CACD,MAAM,MAAM,OAAO,KAAK;AACxB,QAAO,KAAK,6BAA6B,OAAO,KAAK,KAAK,KAAK,IAAI,GAAG,GAAG,OAAO;AAC3E,gBAAe,OAAO,KAAK,CAAC,IAAmB;EAClD,KAAK,gBAAgB,QAAQ,kBAAkB,OAAO,KAAK,OAAO,mBAAmB;EACrF,QAAQ,OAAO;EACf,YAAY,OAAO,KAAK,aAAa;EACrC,UAAU,OAAO;EACjB,aAAa,IAAI,aAAa;EAC9B,cAAc,OAAO;EACrB,mBAAmB,OAAO;EAC3B,CAAC;;AAGJ,SAAgB,sBACd,IACA,QACA,MACA;CAGA,MAAM,UAAkD;EACtD,UAAU;EACV,QAAQ,SAAS;EACjB,cAAc;EACf;AAED,KAAI,KACF,QAAO,OAAO,SAAS,KAAK;AAE9B,QAAO,GAAG,QAAW,QAAQ;;AAG/B,SAAgB,mBAAmB,KAGjC;AACA,QAAO;EACL,UAAU;EACV,QAAQ,MAAM;EACf"}
|
|
@@ -5097,6 +5097,18 @@ Currently logged-in as ${this._username}.`
|
|
|
5097
5097
|
update(id, update) {
|
|
5098
5098
|
return this.updateQueue.update(id, update);
|
|
5099
5099
|
}
|
|
5100
|
+
/**
|
|
5101
|
+
* Create a default doc after a 404. Concurrent first reads (e.g. two
|
|
5102
|
+
* components on a brand-new user) both see the 404 and both create; the
|
|
5103
|
+
* loser's conflict just means the doc now exists, which is what it wanted.
|
|
5104
|
+
*/
|
|
5105
|
+
async putDefaultUnlessCreated(doc) {
|
|
5106
|
+
try {
|
|
5107
|
+
await this.localDB.put(doc);
|
|
5108
|
+
} catch (e) {
|
|
5109
|
+
if (e.status !== 409) throw e;
|
|
5110
|
+
}
|
|
5111
|
+
}
|
|
5100
5112
|
async getCourseRegistrationsDoc() {
|
|
5101
5113
|
logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);
|
|
5102
5114
|
let ret;
|
|
@@ -5113,7 +5125,7 @@ Currently logged-in as ${this._username}.`
|
|
|
5113
5125
|
`Cannot read course registrations for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to create an empty registration doc \u2014 that would report an existing user as unregistered, and then lose to their real document once sync resumes.`
|
|
5114
5126
|
);
|
|
5115
5127
|
}
|
|
5116
|
-
await this.
|
|
5128
|
+
await this.putDefaultUnlessCreated({
|
|
5117
5129
|
_id: _BaseUser.DOC_IDS.COURSE_REGISTRATIONS,
|
|
5118
5130
|
courses: [],
|
|
5119
5131
|
studyWeight: {}
|
|
@@ -5360,7 +5372,7 @@ Currently logged-in as ${this._username}.`
|
|
|
5360
5372
|
`Cannot read config for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to write a default config over what may be an existing one.`
|
|
5361
5373
|
);
|
|
5362
5374
|
}
|
|
5363
|
-
await this.
|
|
5375
|
+
await this.putDefaultUnlessCreated(defaultConfig);
|
|
5364
5376
|
return this.getConfig();
|
|
5365
5377
|
} else {
|
|
5366
5378
|
logger.error(`Error setting user default config:`, e);
|
|
@@ -5976,36 +5988,38 @@ var init_common = __esm({
|
|
|
5976
5988
|
|
|
5977
5989
|
// src/impl/couch/courseAPI.ts
|
|
5978
5990
|
async function getCredentialledCourseConfig(courseID) {
|
|
5979
|
-
|
|
5991
|
+
const hit = courseConfigCache.get(courseID);
|
|
5992
|
+
if (hit && Date.now() - hit.at < COURSE_CONFIG_TTL_MS) {
|
|
5993
|
+
return structuredClone(await hit.config);
|
|
5994
|
+
}
|
|
5995
|
+
const config = (async () => {
|
|
5980
5996
|
const db = getCourseDB(courseID);
|
|
5981
5997
|
const ret = await db.get("CourseConfig");
|
|
5982
5998
|
ret.courseID = courseID;
|
|
5983
|
-
logger.
|
|
5999
|
+
logger.debug(`Fetched course config for ${courseID}`);
|
|
5984
6000
|
return ret;
|
|
6001
|
+
})();
|
|
6002
|
+
courseConfigCache.set(courseID, { at: Date.now(), config });
|
|
6003
|
+
try {
|
|
6004
|
+
return structuredClone(await config);
|
|
5985
6005
|
} catch (e) {
|
|
6006
|
+
courseConfigCache.delete(courseID);
|
|
5986
6007
|
logger.error(`Error fetching config for ${courseID}:`, e);
|
|
5987
6008
|
throw e;
|
|
5988
6009
|
}
|
|
5989
6010
|
}
|
|
5990
|
-
|
|
5991
|
-
const dbName = `coursedb-${courseID}`;
|
|
5992
|
-
return new pouchdb_setup_default(
|
|
5993
|
-
ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + dbName,
|
|
5994
|
-
createPouchDBConfig()
|
|
5995
|
-
);
|
|
5996
|
-
}
|
|
5997
|
-
var import_common8, import_common9, import_common10, import_uuid;
|
|
6011
|
+
var import_common8, import_common9, import_common10, import_uuid, COURSE_CONFIG_TTL_MS, courseConfigCache;
|
|
5998
6012
|
var init_courseAPI = __esm({
|
|
5999
6013
|
"src/impl/couch/courseAPI.ts"() {
|
|
6000
6014
|
"use strict";
|
|
6001
|
-
init_pouchdb_setup();
|
|
6002
6015
|
init_couch();
|
|
6003
|
-
init_factory();
|
|
6004
6016
|
import_common8 = require("@vue-skuilder/common");
|
|
6005
6017
|
import_common9 = require("@vue-skuilder/common");
|
|
6006
6018
|
import_common10 = require("@vue-skuilder/common");
|
|
6007
6019
|
init_logger();
|
|
6008
6020
|
import_uuid = require("uuid");
|
|
6021
|
+
COURSE_CONFIG_TTL_MS = 5 * 60 * 1e3;
|
|
6022
|
+
courseConfigCache = /* @__PURE__ */ new Map();
|
|
6009
6023
|
}
|
|
6010
6024
|
});
|
|
6011
6025
|
|
|
@@ -6045,7 +6059,16 @@ function createPouchDBConfig() {
|
|
|
6045
6059
|
}
|
|
6046
6060
|
return pouchDBincludeCredentialsConfig;
|
|
6047
6061
|
}
|
|
6048
|
-
|
|
6062
|
+
function getCourseDB(courseID) {
|
|
6063
|
+
const url = ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + "coursedb-" + courseID;
|
|
6064
|
+
let db = courseDBHandles.get(url);
|
|
6065
|
+
if (!db) {
|
|
6066
|
+
db = new pouchdb_setup_default(url, { ...createPouchDBConfig(), skip_setup: true });
|
|
6067
|
+
courseDBHandles.set(url, db);
|
|
6068
|
+
}
|
|
6069
|
+
return db;
|
|
6070
|
+
}
|
|
6071
|
+
var import_cross_fetch, import_moment7, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, courseDBHandles;
|
|
6049
6072
|
var init_couch = __esm({
|
|
6050
6073
|
"src/impl/couch/index.ts"() {
|
|
6051
6074
|
"use strict";
|
|
@@ -6069,6 +6092,7 @@ var init_couch = __esm({
|
|
|
6069
6092
|
return pouchdb_setup_default.fetch(url, opts);
|
|
6070
6093
|
}
|
|
6071
6094
|
};
|
|
6095
|
+
courseDBHandles = /* @__PURE__ */ new Map();
|
|
6072
6096
|
}
|
|
6073
6097
|
});
|
|
6074
6098
|
|