@vue-skuilder/db 0.2.25 → 0.2.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/{SyncStrategy-CCU1H81I.d.cts → SyncStrategy-BXliog1m.d.cts} +14 -1
  2. package/dist/{SyncStrategy-CCU1H81I.d.ts → SyncStrategy-BXliog1m.d.ts} +14 -1
  3. package/dist/{contentSource-CrRnbjBx.d.cts → contentSource-D3c1fMAk.d.cts} +11 -0
  4. package/dist/{contentSource-kD35o65m.d.ts → contentSource-LPf044hY.d.ts} +11 -0
  5. package/dist/core/index.d.cts +3 -3
  6. package/dist/core/index.d.ts +3 -3
  7. package/dist/core/index.js +55 -13
  8. package/dist/core/index.js.map +1 -1
  9. package/dist/core/index.mjs +55 -13
  10. package/dist/core/index.mjs.map +1 -1
  11. package/dist/{dataLayerProvider-IecbidDO.d.cts → dataLayerProvider-CeLiFbHv.d.cts} +1 -1
  12. package/dist/{dataLayerProvider-CtzddVdy.d.ts → dataLayerProvider-DaAootVV.d.ts} +1 -1
  13. package/dist/impl/couch/index.d.cts +4 -3
  14. package/dist/impl/couch/index.d.ts +4 -3
  15. package/dist/impl/couch/index.js +71 -13
  16. package/dist/impl/couch/index.js.map +1 -1
  17. package/dist/impl/couch/index.mjs +71 -13
  18. package/dist/impl/couch/index.mjs.map +1 -1
  19. package/dist/impl/static/index.d.cts +3 -3
  20. package/dist/impl/static/index.d.ts +3 -3
  21. package/dist/impl/static/index.js +55 -13
  22. package/dist/impl/static/index.js.map +1 -1
  23. package/dist/impl/static/index.mjs +55 -13
  24. package/dist/impl/static/index.mjs.map +1 -1
  25. package/dist/index.d.cts +3 -3
  26. package/dist/index.d.ts +3 -3
  27. package/dist/index.js +72 -14
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +72 -14
  30. package/dist/index.mjs.map +1 -1
  31. package/package.json +3 -3
  32. package/src/core/interfaces/userDB.ts +10 -0
  33. package/src/core/navigators/generators/prescribed.ts +43 -14
  34. package/src/impl/common/BaseUserDB.ts +40 -0
  35. package/src/impl/common/SyncStrategy.ts +11 -1
  36. package/src/impl/common/index.ts +1 -0
  37. package/src/impl/common/types.ts +5 -0
  38. package/src/impl/couch/CouchDBSyncStrategy.ts +25 -1
  39. package/src/study/SessionController.ts +6 -2
  40. package/tests/core/navigators/prescribedIntroExposure.test.ts +29 -0
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "0.2.25",
7
+ "version": "0.2.27",
8
8
  "description": "Database layer for vue-skuilder",
9
9
  "main": "dist/index.js",
10
10
  "module": "dist/index.mjs",
@@ -48,7 +48,7 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "@nilock2/pouchdb-authentication": "^1.0.2",
51
- "@vue-skuilder/common": "0.2.25",
51
+ "@vue-skuilder/common": "0.2.27",
52
52
  "cross-fetch": "^4.1.0",
53
53
  "moment": "^2.29.4",
54
54
  "pouchdb": "^9.0.0",
@@ -63,5 +63,5 @@
63
63
  "vite": "^8.0.0",
64
64
  "vitest": "^4.1.0"
65
65
  },
66
- "stableVersion": "0.2.25"
66
+ "stableVersion": "0.2.27"
67
67
  }
@@ -257,6 +257,16 @@ export interface UserDBAuthenticator {
257
257
  logout(): Promise<{
258
258
  ok: boolean;
259
259
  }>;
260
+
261
+ /**
262
+ * Adopt a session established outside this client (e.g. third-party
263
+ * sign-in completed server-side), optionally migrating guest data.
264
+ */
265
+ adoptSession(opts: { migrateGuestData: boolean }): Promise<{
266
+ ok: boolean;
267
+ error?: string;
268
+ username?: string;
269
+ }>;
260
270
  }
261
271
 
262
272
  /**
@@ -48,6 +48,16 @@ interface PrescribedGroupConfig {
48
48
  maxDirectTargetsPerRun?: number;
49
49
  maxSupportCardsPerRun?: number;
50
50
  hierarchyWalk?: HierarchyWalkConfig;
51
+ /**
52
+ * Exposure an intro target needs before it may surface. Each target is held
53
+ * back — and cards bearing its missing exposure tags are emitted as support —
54
+ * until every exposure tag it implies (its own `gpc:expose:*` tags, plus
55
+ * `gpc:expose:X` for each `gpc:intro:X`) reaches this count. Default 3: a
56
+ * letter is met incidentally inside other words before it is introduced.
57
+ * Set 0 for targets that must be introduced *before* any exposure — e.g.
58
+ * irregular words, which only ever appear in their own cards.
59
+ */
60
+ introExposeMinCount?: number;
51
61
  retireOnEncounter?: boolean;
52
62
  /**
53
63
  * Tag patterns identifying *practice* skills to drill once unlocked. For each
@@ -222,6 +232,32 @@ function formatAge(ms: number): string {
222
232
  return `${Math.round(hours / 24)}d`;
223
233
  }
224
234
 
235
+ /**
236
+ * The exposure tags an intro target still lacks before it may surface: its own
237
+ * `gpc:expose:*` tags plus `gpc:expose:X` for each `gpc:intro:X`, each needing
238
+ * `minCount` attempts. A `minCount` of 0 requires nothing — not even an entry
239
+ * in `userTagElo`.
240
+ */
241
+ export function unmetIntroExposeTags(
242
+ tags: string[],
243
+ userTagElo: Record<string, { count: number }>,
244
+ minCount: number
245
+ ): string[] {
246
+ if (minCount <= 0) return [];
247
+
248
+ const exposeTags = new Set(tags.filter((tag) => tag.startsWith('gpc:expose:')));
249
+ for (const tag of tags) {
250
+ if (!tag.startsWith('gpc:intro:')) continue;
251
+ const suffix = tag.slice('gpc:intro:'.length);
252
+ if (suffix) exposeTags.add(`gpc:expose:${suffix}`);
253
+ }
254
+
255
+ return [...exposeTags].filter((tag) => {
256
+ const tagElo = userTagElo[tag];
257
+ return !tagElo || tagElo.count < minCount;
258
+ });
259
+ }
260
+
225
261
  function pickTopByScore(cards: WeightedCard[], limit: number): WeightedCard[] {
226
262
  return [...cards]
227
263
  .sort((a, b) => b.score - a.score || a.cardId.localeCompare(b.cardId))
@@ -609,6 +645,8 @@ export default class PrescribedCardsGenerator extends ContentNavigator implement
609
645
  typeof raw.maxDirectTargetsPerRun === 'number' ? raw.maxDirectTargetsPerRun : DEFAULT_MAX_DIRECT_PER_RUN,
610
646
  maxSupportCardsPerRun:
611
647
  typeof raw.maxSupportCardsPerRun === 'number' ? raw.maxSupportCardsPerRun : DEFAULT_MAX_SUPPORT_PER_RUN,
648
+ introExposeMinCount:
649
+ typeof raw.introExposeMinCount === 'number' ? raw.introExposeMinCount : DEFAULT_MIN_COUNT,
612
650
  hierarchyWalk: {
613
651
  enabled: raw.hierarchyWalk?.enabled !== false,
614
652
  maxDepth:
@@ -715,20 +753,11 @@ export default class PrescribedCardsGenerator extends ContentNavigator implement
715
753
  group.hierarchyWalk?.maxDepth ?? DEFAULT_HIERARCHY_DEPTH
716
754
  );
717
755
 
718
- const introTags = tags.filter((tag) => tag.startsWith('gpc:intro:'));
719
- const exposeTags = new Set(tags.filter((tag) => tag.startsWith('gpc:expose:')));
720
-
721
- for (const introTag of introTags) {
722
- const suffix = introTag.slice('gpc:intro:'.length);
723
- if (suffix) {
724
- exposeTags.add(`gpc:expose:${suffix}`);
725
- }
726
- }
727
-
728
- const unmetExposeTags = [...exposeTags].filter((tag) => {
729
- const tagElo = userTagElo[tag];
730
- return !tagElo || tagElo.count < DEFAULT_MIN_COUNT;
731
- });
756
+ const unmetExposeTags = unmetIntroExposeTags(
757
+ tags,
758
+ userTagElo,
759
+ group.introExposeMinCount ?? DEFAULT_MIN_COUNT
760
+ );
732
761
 
733
762
  if (unmetExposeTags.length > 0) {
734
763
  unmetExposeTags.forEach((tag) => supportTags.add(tag));
@@ -40,6 +40,7 @@ import {
40
40
  removeScheduledCardReviewLocal,
41
41
  } from './userDBHelpers';
42
42
  import { PouchError } from '../couch/types';
43
+ import type { AdoptSessionResult } from './types';
43
44
  import UpdateQueue, { Update } from '../couch/updateQueue';
44
45
  import { UsrCrsData } from '../couch/user-course-relDB';
45
46
  import { getCredentialledCourseConfig } from '../couch/index';
@@ -250,6 +251,45 @@ Currently logged-in as ${this._username}.`
250
251
  return loginResult;
251
252
  }
252
253
 
254
+ /**
255
+ * Adopt a remote session that was established outside this client — e.g. a
256
+ * backend verified a third-party sign-in (Google) and set the session cookie
257
+ * on its response. Afterwards the user is logged in exactly as after
258
+ * login(): username switched, guest pointer cleared, init() re-run.
259
+ *
260
+ * @param opts.migrateGuestData Carry the current guest account's local data
261
+ * into the adopted account. Pass true for a freshly created account (as
262
+ * createAccount() does), false for an existing one (as login() does).
263
+ */
264
+ public async adoptSession(opts: { migrateGuestData: boolean }): Promise<AdoptSessionResult> {
265
+ if (!this.syncStrategy.canAuthenticate() || !this.syncStrategy.adoptSession) {
266
+ throw new Error('Session adoption not supported by current sync strategy');
267
+ }
268
+
269
+ // Captured from memory, not the remote: the remote session already
270
+ // belongs to the adopted user.
271
+ const guestUsername = this._username.startsWith(GuestUsername) ? this._username : undefined;
272
+ if (!guestUsername) {
273
+ throw new Error(`Cannot adopt a session while logged in.
274
+ Log out of account ${this.getUsername()} first.`);
275
+ }
276
+
277
+ const result = await this.syncStrategy.adoptSession(
278
+ opts.migrateGuestData ? guestUsername : undefined
279
+ );
280
+ if (result.ok && result.username) {
281
+ log(`Adopted session for ${result.username}`);
282
+ this._username = result.username;
283
+ try {
284
+ localStorage.removeItem('sk-guest-uuid');
285
+ } catch (e) {
286
+ logger.warn('localStorage not available (Node.js environment):', e);
287
+ }
288
+ await this.init();
289
+ }
290
+ return result;
291
+ }
292
+
253
293
  public async resetUserData(): Promise<{ status: Status; error?: string }> {
254
294
  // Only allow reset for local-only sync strategies
255
295
  if (this.syncStrategy.canAuthenticate()) {
@@ -1,6 +1,6 @@
1
1
  // packages/db/src/impl/common/SyncStrategy.ts
2
2
 
3
- import type { AccountCreationResult, AuthenticationResult } from './types';
3
+ import type { AccountCreationResult, AdoptSessionResult, AuthenticationResult } from './types';
4
4
 
5
5
  /**
6
6
  * Strategy interface for handling user data synchronization
@@ -90,6 +90,16 @@ export interface SyncStrategy {
90
90
  */
91
91
  logout?(): Promise<AuthenticationResult>;
92
92
 
93
+ /**
94
+ * Adopt a remote session established outside this client (e.g. a server that
95
+ * verified a third-party sign-in and set the session cookie), optionally
96
+ * migrating a guest account's local data into it (if supported).
97
+ * @param migrateFromGuest Guest username whose local data should be carried
98
+ * over. The caller must capture it BEFORE the session switched, since the
99
+ * remote now reports the adopted user.
100
+ */
101
+ adoptSession?(migrateFromGuest?: string): Promise<AdoptSessionResult>;
102
+
93
103
  /**
94
104
  * Get the current logged-in username
95
105
  * Returns the username if logged in, or a default guest username
@@ -4,6 +4,7 @@ export type { SyncStrategy } from './SyncStrategy';
4
4
  export { BaseSyncStrategy } from './SyncStrategy';
5
5
  export type {
6
6
  AccountCreationResult,
7
+ AdoptSessionResult,
7
8
  AuthenticationResult,
8
9
  UserSession,
9
10
  SyncConfig,
@@ -22,6 +22,11 @@ export interface AuthenticationResult {
22
22
  error?: string;
23
23
  }
24
24
 
25
+ export interface AdoptSessionResult extends AuthenticationResult {
26
+ /** The adopted session's user, when ok. */
27
+ username?: string;
28
+ }
29
+
25
30
  /**
26
31
  * User session information
27
32
  */
@@ -5,7 +5,11 @@ import { GuestUsername } from '../../core/types/types-legacy';
5
5
  import { logger } from '../../util/logger';
6
6
  import { Status } from '@vue-skuilder/common';
7
7
  import type { SyncStrategy } from '../common/SyncStrategy';
8
- import type { AccountCreationResult, AuthenticationResult } from '../common/types';
8
+ import type {
9
+ AccountCreationResult,
10
+ AdoptSessionResult,
11
+ AuthenticationResult,
12
+ } from '../common/types';
9
13
  import { getLocalUserDB, hexEncode, updateGuestAccountExpirationDate, accomodateGuest } from '../common';
10
14
  import pouch from './pouchdb-setup';
11
15
  import { createPouchDBConfig } from './index';
@@ -261,6 +265,26 @@ export class CouchDBSyncStrategy implements SyncStrategy {
261
265
  }
262
266
  }
263
267
 
268
+ async adoptSession(migrateFromGuest?: string): Promise<AdoptSessionResult> {
269
+ let username: string;
270
+ try {
271
+ username = await getLoggedInUsername();
272
+ } catch {
273
+ return { ok: false, error: 'No session to adopt' };
274
+ }
275
+
276
+ if (migrateFromGuest?.startsWith(GuestUsername)) {
277
+ logger.info(`Migrating data from funnel account ${migrateFromGuest} to ${username}`);
278
+ const migrationResult = await this.migrateFunnelData(migrateFromGuest, username);
279
+ if (!migrationResult.success) {
280
+ logger.warn(`Migration failed: ${migrationResult.error}`);
281
+ // Continue anyway - don't block the login
282
+ }
283
+ }
284
+
285
+ return { ok: true, username };
286
+ }
287
+
264
288
  async logout(): Promise<AuthenticationResult> {
265
289
  try {
266
290
  const result = await this.getRemoteCouchRootDB().logOut();
@@ -1244,8 +1244,12 @@ export class SessionController<TView = unknown> extends Loggable {
1244
1244
  });
1245
1245
  } catch (error) {
1246
1246
  this.error(`Failed to get content from source ${i}:`, error);
1247
- // Re-throw if this is the only source - we can't proceed without any content
1248
- if (this.sources.length === 1) {
1247
+ // Re-throw if this is the only source - we can't proceed without any content.
1248
+ // Initial load only: a replan falls through to the non-fatal
1249
+ // `batches.length === 0` path below and keeps the existing queue.
1250
+ // Throwing there would escape nextCard() (via the wedge-breaker) and
1251
+ // strand the host mid-session with neither a card nor a null.
1252
+ if (this.sources.length === 1 && !replan) {
1249
1253
  throw new Error(`Cannot start session: failed to load content from source ${i}`);
1250
1254
  }
1251
1255
  }
@@ -0,0 +1,29 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { unmetIntroExposeTags } from '../../../src/core/navigators/generators/prescribed';
3
+
4
+ describe('unmetIntroExposeTags', () => {
5
+ it('implies gpc:expose:X from gpc:intro:X and requires minCount of it', () => {
6
+ const tags = ['gpc:intro:v-V', 'concept:match:simple'];
7
+ expect(unmetIntroExposeTags(tags, {}, 3)).toEqual(['gpc:expose:v-V']);
8
+ expect(unmetIntroExposeTags(tags, { 'gpc:expose:v-V': { count: 2 } }, 3)).toEqual([
9
+ 'gpc:expose:v-V',
10
+ ]);
11
+ expect(unmetIntroExposeTags(tags, { 'gpc:expose:v-V': { count: 3 } }, 3)).toEqual([]);
12
+ });
13
+
14
+ it("counts the card's own gpc:expose:* tags once alongside the implied one", () => {
15
+ const tags = ['gpc:intro:v-V', 'gpc:expose:v-V', 'gpc:expose:a-AE'];
16
+ expect(unmetIntroExposeTags(tags, { 'gpc:expose:a-AE': { count: 5 } }, 3)).toEqual([
17
+ 'gpc:expose:v-V',
18
+ ]);
19
+ });
20
+
21
+ it('minCount 0 requires nothing, even with no exposure entry at all', () => {
22
+ const tags = ['gpc:intro:WORD-was', 'concept:match:whole_word'];
23
+ expect(unmetIntroExposeTags(tags, {}, 0)).toEqual([]);
24
+ });
25
+
26
+ it('non-intro targets with no expose tags need nothing', () => {
27
+ expect(unmetIntroExposeTags(['gpc:exercise:t-T'], {}, 3)).toEqual([]);
28
+ });
29
+ });