import assert from "node:assert/strict" import { test } from "node:test" import { createRequire } from "node:module" import { build } from "esbuild" async function loadModule(path, http = {}) { const key = `learningTest${Math.random().toString(36).slice(2)}` globalThis[key] = http const result = await build({ entryPoints: [path], bundle: true, write: false, platform: "node", format: "esm", define: { "import.meta.env": "{}" }, plugins: [{ name: "http-fixture", setup(builder) { builder.onResolve({ filter: /(^|\/)http$/ }, () => ({ path: "http", namespace: "fixture" })) builder.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({ contents: `export default globalThis[${JSON.stringify(key)}]` })) } }], }) const module = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString("base64")}`) return module } test("chapter lesson pagination uses the public collection key", async () => { const calls = [] const api = await loadModule("src/api/learningHierarchy.api.ts", { get: async (path, options) => { calls.push([path, options.params]) const offset = options.params.offset return { data: { data: { lessons: Array.from({ length: offset === 0 ? 200 : 1 }, (_, i) => ({ id: offset + i + 1 })), total_count: 201 } } } } }) assert.equal((await api.listLearningItems("/chapters/7/lessons", "lessons")).length, 201) assert.deepEqual(calls.map((call) => call[1].offset), [0, 200]) assert.ok(calls.every((call) => call[0] === "/chapters/7/lessons")) }) test("quiz publication updates both statuses without replacing questions", async () => { const calls = [] const api = await loadModule("src/api/learningHierarchy.api.ts", { put: async (...args) => calls.push(args) }) await api.updateChapterQuiz(9, { publish_status: "PUBLISHED" }) assert.deepEqual(calls, [["/quizzes/9/full", { practice: { publish_status: "PUBLISHED" }, question_set: { status: "PUBLISHED" } }]]) }) test("quiz creation uses a QUIZ set and cleans it up if chapter linking fails", async () => { const calls = [] const failure = new Error("chapter unavailable") const api = await loadModule("src/api/learningHierarchy.api.ts", { post: async (path, body) => { calls.push([path, body]) if (path === "/question-sets") return { data: { data: { id: 12 } } } throw failure }, delete: async (path) => calls.push([path]), }) await assert.rejects(api.createChapterQuiz(7, "Review"), failure) assert.deepEqual(calls, [ ["/question-sets", { title: "Review", set_type: "QUIZ", status: "DRAFT" }], ["/chapters/7/quizzes", { title: "Review", question_set_id: 12, publish_status: "DRAFT" }], ["/question-sets/12"], ]) }) test("public CHAPTER parents survive practice normalization", async () => { const parents = await loadModule("src/lib/practiceParents.ts") assert.deepEqual(parents.normalizePracticeParents({ parents: [{ parent_kind: "CHAPTER", parent_id: 7 }] }), [{ parent_kind: "CHAPTER", parent_id: 7 }]) assert.equal(parents.formatPracticeParentLabel({ parent_kind: "CHAPTER", parent_id: 7 }), "Chapter #7") }) test("admin quiz questions consume the data array from the question-set API", async () => { const rows = [{ id: 31, question_text: "Review question" }] const api = await loadModule("src/api/learningHierarchy.api.ts", { get: async (path) => { assert.equal(path, "/question-sets/12/questions") return { data: { data: rows } } } }) assert.deepEqual(await api.getQuizQuestions(12), rows) }) test("user learning activity preserves the course chapter lesson tree", async () => { const users = await loadModule("src/api/users.api.ts") const activity = users.normalizeUserLearningActivity({ user_id: 42, learning: { progress: { courses: [{ id: 3, name: "Course", chapters: [{ id: 7, course_id: 3, name: "Chapter", lessons: [{ id: 11, chapter_id: 7, title: "Lesson" }] }] }] }, completions: { user_id: 42, courses: [{ id: 3 }] }, } }) const chapter = activity.learning.progress.courses[0].chapters[0] assert.equal(chapter.course_id, 3) assert.equal(chapter.lessons[0].chapter_id, 7) assert.equal(chapter.lessons[0].title, "Lesson") assert.equal(activity.learning.completions.courses.length, 1) assert.equal("modules" in chapter, false) }) test("offset pagination follows totals even when the server caps page size", async () => { const { fetchAllOffsetPages } = await loadModule("src/lib/fetchAllOffsetPages.ts") const offsets = [] const rows = await fetchAllOffsetPages(async (offset) => { offsets.push(offset) return { items: [offset + 1], total_count: 3 } }, 100) assert.deepEqual(rows, [1, 2, 3]) assert.deepEqual(offsets, [0, 1, 2]) }) test("offset pagination stops on empty pages and rejects invalid batch sizes", async () => { const { fetchAllOffsetPages } = await loadModule("src/lib/fetchAllOffsetPages.ts") let calls = 0 assert.deepEqual(await fetchAllOffsetPages(async () => { calls++ return { items: [], total_count: 100 } }), []) assert.equal(calls, 1) for (const size of [0, -1, 1.5, NaN, Infinity]) { await assert.rejects(fetchAllOffsetPages(async () => { assert.fail("invalid sizes must fail before fetching") }, size), RangeError) } }) test("practice fetching continues without a total and preserves filters", async () => { for (const isExamPrep of [false, true]) { const calls = [] const { fetchAllPractices } = await loadModule("src/lib/fetchAllPractices.ts", { get: async (path, { params }) => { calls.push(params) assert.equal(path, "/practices") return { data: { data: { practices: Array.from({ length: params.offset === 0 ? 100 : 1 }, (_, i) => ({ id: params.offset + i + 1 })) } } } }, }) const practices = await fetchAllPractices(true, { isExamPrep }) assert.equal(practices.length, 101) assert.deepEqual(calls, [{ limit: 100, offset: 0, unlinked_only: true }, { limit: 100, offset: 100, unlinked_only: true }]) } }) test("list envelopes preserve legacy casing and unknown totals", async () => { const { offsetPageFromListEnvelope } = await loadModule("src/lib/fetchAllOffsetPages.ts") assert.deepEqual(offsetPageFromListEnvelope({ data: { Data: { Practices: [{ id: 1 }], TotalCount: "2" } } }, "practices"), { items: [{ id: 1 }], total_count: 2 }) assert.deepEqual(offsetPageFromListEnvelope({ data: { data: { practices: [] } } }, "practices"), { items: [], total_count: undefined }) }) test("create response IDs support legacy envelopes and reject invalid identifiers", async () => { const { readCreatedEntityId } = await loadModule("src/lib/apiResponse.ts") for (const body of [{ data: { id: 7 } }, { data: { course: { id: "7" } } }, { data: { data: { id: 7 } } }, { course: { id: 7 } }, { id: 7 }]) { assert.equal(readCreatedEntityId(body, "course"), 7) } for (const body of [null, {}, { data: { id: 0 } }, { data: { id: -1 } }, { id: "invalid" }]) { assert.equal(readCreatedEntityId(body, "course"), null) } assert.equal(readCreatedEntityId({ data: { category: { id: 9 } } }, "category"), 9) }) test("subscription plans retain Education and historical categories", async () => { const { parseSubscriptionPlansList } = await loadModule("src/api/subscription-plans.api.ts") const categories = ["EDUCATION", "LEARN_ENGLISH", "IELTS", "DUOLINGO"] const plans = parseSubscriptionPlansList({ data: categories.map((category, i) => ({ id: i + 1, category })) }) assert.deepEqual(plans.map((plan) => plan.category), categories) assert.deepEqual(parseSubscriptionPlansList({ data: [{ id: 1, category: "unsupported" }] }), []) }) test("extracted hooks share the same theme and revenue contexts as their components", async () => { const result = await build({ stdin: { contents: ` import { createElement } from "react" import { renderToStaticMarkup } from "react-dom/server" import { ThemeProvider } from "./src/contexts/ThemeContext" import { useTheme } from "./src/contexts/ThemeContext.shared" import { SensitiveValue } from "./src/components/ui/sensitive-value" import { SensitiveRevealContext } from "./src/components/ui/sensitive-value.shared" function ThemeProbe() { return createElement("span", null, useTheme().theme) } export function renderTheme() { return renderToStaticMarkup(createElement(ThemeProvider, null, createElement(ThemeProbe))) } export function renderRevenue() { return renderToStaticMarkup(createElement(SensitiveRevealContext.Provider, { value: { revealed: true, toggle() {} } }, createElement(SensitiveValue, { showToggle: false }, "42"))) } `, resolveDir: process.cwd(), loader: "ts", }, bundle: true, write: false, platform: "node", format: "cjs", tsconfig: "tsconfig.app.json", }) const module = { exports: {} } new Function("require", "module", "exports", result.outputFiles[0].text)(createRequire(import.meta.url), module, module.exports) assert.equal(module.exports.renderTheme(), "light") assert.match(module.exports.renderRevenue(), /aria-hidden="false"/) }) test("makeup profiles preserve missing, custom, and historical data without inventing preferences", async () => { const profile = await loadModule("src/lib/userProfileFieldDisplay.ts") assert.equal(profile.displayUserLearningGoal("PERSONAL_MAKEUP"), "Develop personal makeup skills") assert.equal(profile.displayUserOccupation("BEAUTY_STUDENT"), "Beauty and makeup student") assert.equal(profile.displayUserLanguageChallenge("BLENDING"), "Blending and application") assert.equal(profile.displayUserLanguageGoal("MAKEUP_FOUNDATIONS"), "Master makeup foundations") assert.equal(profile.displayUserLearningGoal(""), "Not provided") assert.equal(profile.displayUserLanguageChallenge("unknown"), "Not provided") assert.equal(profile.displayUserLearningGoal("Custom artistry goal"), "Custom artistry goal") assert.ok(profile.PROFILE_FILTER_LEARNING_GOALS.every(option => !["EVERYDAY_CONVERSATION", "EXAM_PREP"].includes(option.code))) assert.deepEqual(profile.mergeAnalyticsRowsByDisplayLabel([{label:"",count:3},{label:"PERSONAL_MAKEUP",count:2}], profile.displayUserLearningGoal), [{label:"Not provided",count:3},{label:"Develop personal makeup skills",count:2}]) }) test("new makeup subscriptions default to the supported backend category", async () => { const form = await loadModule("src/pages/settings/components/CreateSubscriptionPlanDialog.shared.ts") assert.equal(form.EMPTY_SUBSCRIPTION_PLAN_DRAFT.category, "EDUCATION") }) test("retired Audio Conversation is excluded while historical reads remain available", async () => { const retired = {id: 10, key: "audio_conversation_type", display_name: "Audio Conversation", status: "INACTIVE"} const current = {id: 11, key: "makeup_knowledge_check", display_name: "Makeup knowledge check", status: "ACTIVE"} const api = await loadModule("src/api/questionTypeDefinitions.api.ts", {get: async (path) => ({data:{data: path.endsWith("/10") ? retired : {definitions:[retired,current],total_count:2}}})}) const result = await api.getQuestionTypeDefinitions() assert.deepEqual(result.definitions.map(def => def.key), ["makeup_knowledge_check"]) assert.equal(result.total_count,1) assert.equal((await api.getQuestionTypeDefinitionById(10)).key,"audio_conversation_type") })