@composable-os/pack-courses 0.1.0-beta.11 → 0.1.0-beta.14

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 (30) hide show
  1. package/dist/automations.js +1 -2
  2. package/dist/blocks/courses-builder/course-builder.js +15 -21
  3. package/dist/blocks/courses-catalogue/catalogue.js +2 -3
  4. package/dist/blocks/courses-course/course-page.d.ts +6 -1
  5. package/dist/blocks/courses-course/course-page.js +73 -9
  6. package/dist/blocks/courses-my-courses/my-courses.d.ts +14 -1
  7. package/dist/blocks/courses-my-courses/my-courses.js +9 -1
  8. package/dist/blocks/courses-native-catalogue/catalogue-screen.js +3 -6
  9. package/dist/blocks/courses-native-course/course-screen.js +2 -2
  10. package/dist/blocks/courses-native-my-courses/my-courses-screen.d.ts +14 -1
  11. package/dist/blocks/courses-native-my-courses/my-courses-screen.js +16 -3
  12. package/dist/blocks/courses-native-player/lesson-screen.d.ts +1 -0
  13. package/dist/blocks/courses-native-player/lesson-screen.js +2 -2
  14. package/dist/blocks/courses-native-subscription/subscription-screen.js +2 -2
  15. package/dist/blocks/courses-player/player.d.ts +1 -1
  16. package/dist/blocks/courses-subscribe/subscribe.d.ts +6 -1
  17. package/dist/blocks/courses-subscribe/subscribe.js +80 -9
  18. package/dist/blocks/courses-subscription/my-subscription.d.ts +6 -4
  19. package/dist/blocks/courses-subscription/my-subscription.js +14 -49
  20. package/dist/client/index.d.ts +382 -10
  21. package/dist/client/index.js +24 -36
  22. package/dist/dashboards.d.ts +2 -0
  23. package/dist/dashboards.js +3 -3
  24. package/dist/index.d.ts +82 -3
  25. package/dist/index.js +68 -3
  26. package/dist/outline.d.ts +1 -3
  27. package/dist/outline.js +25 -16
  28. package/dist/tools.d.ts +7 -1
  29. package/dist/tools.js +130 -103
  30. package/package.json +3 -3
package/dist/tools.js CHANGED
@@ -9,12 +9,14 @@
9
9
  // video and where it is shown, and the app asks `media.play` for it (ADR 0478: the signing key
10
10
  // stays in cos-app).
11
11
  import { defineTool, OpsCallError, z } from "@composable-os/sdk";
12
+ import { WEEK } from "./dashboards.js";
12
13
  import { asOutline, completion, findLesson, LESSON_KINDS, lessonVideo, nextLesson, watchedToEnd, } from "./outline.js";
13
14
  export const THEME = "courses.theme";
14
15
  export const COURSE = "courses.course";
15
16
  export const BUNDLE = "courses.bundle";
16
17
  export const ENROLMENT = "courses.enrolment";
17
18
  export const PROGRESS = "courses.progress";
19
+ export const PLAN = "courses.plan";
18
20
  const PROGRAM = "programs.program";
19
21
  const SESSION = "programs.session";
20
22
  const id = z.string().min(1).max(64);
@@ -24,15 +26,21 @@ const num = (value) => typeof value === "number" ? value : value == null || valu
24
26
  const notFound = (what, which) => new OpsCallError("not_found", `No ${what} with id ${which}`, { object: what, id: which });
25
27
  const isCustomer = (ctx) => ctx.caller?.kind === "customer";
26
28
  const isStaff = (ctx) => ctx.caller?.kind === "staff";
27
- /** Of these courses, the ones the caller holds access to: the host's answer (ADR 0477). */
29
+ /** The most ids one access.check takes. */
30
+ const ACCESS_CHECK_MAX = 100;
31
+ /**
32
+ * Of these courses, the ones the caller holds access to: the host's answer (ADR 0477), asked
33
+ * `ACCESS_CHECK_MAX` at a time.
34
+ */
28
35
  async function held(ctx, ids) {
29
36
  if (!ids.length || !isCustomer(ctx))
30
37
  return new Set();
31
- const answer = await ctx.ops.call("access.check", {
32
- object: COURSE,
33
- ids: ids.slice(0, 100),
34
- });
35
- return new Set(answer.held);
38
+ const batches = [];
39
+ for (let at = 0; at < ids.length; at += ACCESS_CHECK_MAX) {
40
+ batches.push(ids.slice(at, at + ACCESS_CHECK_MAX));
41
+ }
42
+ const answers = await Promise.all(batches.map((batch) => ctx.ops.call("access.check", { object: COURSE, ids: batch })));
43
+ return new Set(answers.flatMap((answer) => answer.held));
36
44
  }
37
45
  /** The bundle's courses, as its published version lists them. */
38
46
  const bundleCourses = (bundle) => {
@@ -44,6 +52,7 @@ const picture = z
44
52
  .passthrough()
45
53
  .nullable();
46
54
  const video = z.object({ media: z.string(), poster: z.string().optional() }).nullable();
55
+ const pictureOf = (value) => value ?? null;
47
56
  const lessonSummary = z.object({
48
57
  key: z.string(),
49
58
  title: z.string(),
@@ -73,25 +82,34 @@ function card(record) {
73
82
  theme: text(v.theme),
74
83
  level: num(v.level),
75
84
  summary: text(v.summary),
76
- cover: v.cover ?? null,
85
+ cover: pictureOf(v.cover),
77
86
  trailer: v.trailer ?? null,
78
87
  price: num(v.price),
79
88
  lessons: outline.sections.reduce((n, s) => n + (s.lessons?.length ?? 0), 0),
80
89
  };
81
90
  }
91
+ /** What everyone who may read the course reads of a lesson (`lessonSummary`). */
92
+ const summaryOfLesson = (l) => ({
93
+ key: l.key,
94
+ title: l.title,
95
+ kind: l.kind,
96
+ duration: l.duration ?? null,
97
+ preview: l.preview === true,
98
+ });
82
99
  function summaryOf(outline) {
83
100
  return outline.sections.map((section) => ({
84
101
  key: section.key,
85
102
  title: section.title,
86
- lessons: (section.lessons ?? []).map((l) => ({
87
- key: l.key,
88
- title: l.title,
89
- kind: l.kind,
90
- duration: l.duration ?? null,
91
- preview: l.preview === true,
92
- })),
103
+ lessons: (section.lessons ?? []).map(summaryOfLesson),
93
104
  }));
94
105
  }
106
+ /** A progress row's state, or null when it has none. */
107
+ const stateOf = (row) => {
108
+ const state = row?.values.state;
109
+ return state === "started" || state === "done" ? state : null;
110
+ };
111
+ /** The keys of the lessons these progress rows mark done. */
112
+ const doneKeys = (rows) => new Set([...rows].filter(([, row]) => stateOf(row) === "done").map(([key]) => key));
95
113
  /** The caller's own progress rows on a course, by lesson key. */
96
114
  async function progressRows(ctx, courseId) {
97
115
  const page = await ctx.ops.call("my.list", {
@@ -101,6 +119,20 @@ async function progressRows(ctx, courseId) {
101
119
  });
102
120
  return new Map(page.items.map((row) => [String(row.values.lessonKey), row]));
103
121
  }
122
+ /** The caller's own progress row on one lesson of a course, if they have one. */
123
+ async function progressRow(ctx, courseId, lessonKey) {
124
+ const page = await ctx.ops.call("my.list", {
125
+ object: PROGRESS,
126
+ filter: {
127
+ and: [
128
+ { field: "course", op: "eq", value: courseId },
129
+ { field: "lessonKey", op: "eq", value: lessonKey },
130
+ ],
131
+ },
132
+ limit: 1,
133
+ });
134
+ return page.items[0] ?? null;
135
+ }
104
136
  const currency = z
105
137
  .string()
106
138
  .nullable()
@@ -162,7 +194,7 @@ export const catalogue = defineTool({
162
194
  name: text(t.values.name),
163
195
  slug: text(t.values.slug),
164
196
  summary: text(t.values.summary),
165
- picture: t.values.picture ?? null,
197
+ picture: pictureOf(t.values.picture),
166
198
  })),
167
199
  courses: courses.items.map(card),
168
200
  bundles: bundles.items.map((b) => ({
@@ -170,7 +202,7 @@ export const catalogue = defineTool({
170
202
  title: text(b.values.title),
171
203
  slug: text(b.values.slug),
172
204
  summary: text(b.values.summary),
173
- cover: b.values.cover ?? null,
205
+ cover: pictureOf(b.values.cover),
174
206
  courses: bundleCourses(b),
175
207
  price: num(b.values.price),
176
208
  })),
@@ -179,7 +211,6 @@ export const catalogue = defineTool({
179
211
  },
180
212
  });
181
213
  // --- Course plans --------------------------------------------------------------------------------
182
- export const PLAN = "courses.plan";
183
214
  export const plans = defineTool({
184
215
  description: "The course plans on offer: a subscription to every published course, paid every month. Each " +
185
216
  "plan's title, description, price per month (in the major unit of `currency`) and the days of " +
@@ -244,18 +275,15 @@ export const course = defineTool({
244
275
  throw notFound(COURSE, input.slug);
245
276
  const outline = asOutline(record.values.outline);
246
277
  const holds = (await held(ctx, [record.id])).has(record.id);
247
- const rows = holds ? await progressRows(ctx, record.id) : new Map();
248
- const done = [...rows.values()]
249
- .filter((r) => r.values.state === "done")
250
- .map((r) => String(r.values.lessonKey));
278
+ const done = holds ? doneKeys(await progressRows(ctx, record.id)) : new Set();
251
279
  return {
252
280
  ...card(record),
253
281
  description: record.values.description ?? null,
254
282
  sections: summaryOf(outline),
255
283
  currency: page.currency ?? null,
256
284
  holds,
257
- done,
258
- complete: completion(outline, new Set(done)).complete,
285
+ done: [...done],
286
+ complete: completion(outline, done).complete,
259
287
  };
260
288
  },
261
289
  });
@@ -309,7 +337,7 @@ export const lesson = defineTool({
309
337
  const holds = isStaff(ctx) || (await held(ctx, [input.courseId])).has(input.courseId);
310
338
  if (!holds && found.preview !== true)
311
339
  throw notFound("lesson", input.lessonKey);
312
- const row = isCustomer(ctx) ? (await progressRows(ctx, input.courseId)).get(found.key) : null;
340
+ const row = isCustomer(ctx) ? await progressRow(ctx, input.courseId, found.key) : null;
313
341
  const v = lessonVideo(found);
314
342
  const after = nextLesson(outline, found.key);
315
343
  const { section: _section, ...plain } = found;
@@ -325,16 +353,8 @@ export const lesson = defineTool({
325
353
  }
326
354
  : null,
327
355
  position: row ? num(row.values.position) : null,
328
- state: row ? (text(row.values.state) ?? null) : null,
329
- next: after
330
- ? {
331
- key: after.key,
332
- title: after.title,
333
- kind: after.kind,
334
- duration: after.duration ?? null,
335
- preview: after.preview === true,
336
- }
337
- : null,
356
+ state: stateOf(row),
357
+ next: after ? summaryOfLesson(after) : null,
338
358
  };
339
359
  },
340
360
  });
@@ -362,18 +382,17 @@ export const progress = defineTool({
362
382
  risk: "write",
363
383
  audiences: ["customer"],
364
384
  async handler(input, ctx) {
365
- const record = await ctx.ops.call("my.get", {
366
- object: COURSE,
367
- id: input.courseId,
368
- });
385
+ const [record, rows] = await Promise.all([
386
+ ctx.ops.call("my.get", { object: COURSE, id: input.courseId }),
387
+ progressRows(ctx, input.courseId),
388
+ ]);
369
389
  const outline = asOutline(record.values.outline);
370
390
  if (!findLesson(outline, input.lessonKey))
371
391
  throw notFound("lesson", input.lessonKey);
372
- const rows = await progressRows(ctx, input.courseId);
373
392
  const existing = rows.get(input.lessonKey);
374
393
  const now = new Date().toISOString();
375
394
  const ended = input.position !== undefined && watchedToEnd(input.position, input.duration);
376
- const before = text(existing?.values.state);
395
+ const before = stateOf(existing);
377
396
  const state = input.state === "done" || ended || before === "done" ? "done" : "started";
378
397
  const values = {
379
398
  state,
@@ -390,9 +409,7 @@ export const progress = defineTool({
390
409
  values: { course: input.courseId, lessonKey: input.lessonKey, startedAt: now, ...values },
391
410
  });
392
411
  }
393
- const done = new Set([...rows.values()]
394
- .filter((r) => r.values.state === "done")
395
- .map((r) => String(r.values.lessonKey)));
412
+ const done = doneKeys(rows);
396
413
  if (state === "done")
397
414
  done.add(input.lessonKey);
398
415
  const sum = completion(outline, done);
@@ -407,6 +424,13 @@ export const progress = defineTool({
407
424
  },
408
425
  });
409
426
  // --- My courses ----------------------------------------------------------------------------------
427
+ /** Why a student holds a course, as My courses says it. */
428
+ const WHY = ["bought", "bundle", "given", "imported", "subscription"];
429
+ /** An enrolment's source, as a reason; any other (a purchase) is "bought". */
430
+ const WHY_BY_SOURCE = new Map([
431
+ ["staff", "given"],
432
+ ["import", "imported"],
433
+ ]);
410
434
  export const myCourses = defineTool({
411
435
  description: "Every course the signed-in student holds access to and why (bought, in a bundle, given by " +
412
436
  "staff, imported, or through their course subscription), with how far they are (lessons " +
@@ -415,7 +439,7 @@ export const myCourses = defineTool({
415
439
  input: z.object({}),
416
440
  output: z.object({
417
441
  courses: z.array(courseCard.extend({
418
- why: z.enum(["bought", "bundle", "given", "imported", "subscription"]),
442
+ why: z.enum(WHY),
419
443
  done: z.number(),
420
444
  counted: z.number(),
421
445
  complete: z.boolean(),
@@ -425,60 +449,56 @@ export const myCourses = defineTool({
425
449
  risk: "read",
426
450
  audiences: ["customer"],
427
451
  async handler(_input, ctx) {
428
- const enrolments = await ctx.ops.call("my.list", { object: ENROLMENT, limit: 200 });
452
+ // A course subscription covers every published course (ADR 0488): the published ones the host
453
+ // says they hold that no enrolment of theirs explains are through it.
454
+ const [enrolments, published] = await Promise.all([
455
+ ctx.ops.call("my.list", { object: ENROLMENT, limit: 200 }),
456
+ ctx.ops.call("public.list", {
457
+ object: COURSE,
458
+ sort: { field: "title", direction: "asc" },
459
+ limit: 100,
460
+ }),
461
+ ]);
462
+ // Each bundle once, as its published version lists its courses; one no longer published
463
+ // gives nothing to list.
464
+ const bundleIds = new Set(enrolments.items.map((e) => text(e.values.bundle)));
465
+ bundleIds.delete(null);
466
+ const bundles = new Map(await Promise.all([...bundleIds].map(async (bundleId) => {
467
+ const bundle = await ctx.ops
468
+ .call("public.get", { object: BUNDLE, id: bundleId })
469
+ .catch(() => null);
470
+ return [bundleId, bundle ? bundleCourses(bundle) : []];
471
+ })));
429
472
  const why = new Map();
430
473
  const completed = new Set();
431
- const bundles = new Map();
432
474
  for (const e of enrolments.items) {
433
- const reason = e.values.source === "staff"
434
- ? "given"
435
- : e.values.source === "import"
436
- ? "imported"
437
- : "bought";
438
475
  const courseId = text(e.values.course);
439
476
  const bundleId = text(e.values.bundle);
440
477
  if (courseId) {
441
478
  if (!why.has(courseId))
442
- why.set(courseId, reason);
479
+ why.set(courseId, WHY_BY_SOURCE.get(e.values.source) ?? "bought");
443
480
  if (e.values.completed === true)
444
481
  completed.add(courseId);
445
482
  }
446
- if (bundleId && !bundles.has(bundleId)) {
447
- try {
448
- const bundle = await ctx.ops.call("public.get", {
449
- object: BUNDLE,
450
- id: bundleId,
451
- });
452
- bundles.set(bundleId, bundleCourses(bundle));
453
- for (const c of bundleCourses(bundle))
454
- if (!why.has(c))
455
- why.set(c, "bundle");
456
- }
457
- catch {
458
- // A bundle no longer published gives nothing to list.
459
- }
483
+ for (const c of bundleId ? (bundles.get(bundleId) ?? []) : []) {
484
+ if (!why.has(c))
485
+ why.set(c, "bundle");
460
486
  }
461
487
  }
462
- // A course subscription covers every published course (ADR 0488): the published ones the host
463
- // says they hold that no enrolment of theirs explains are through it.
464
- const published = await ctx.ops.call("public.list", {
465
- object: COURSE,
466
- sort: { field: "title", direction: "asc" },
467
- limit: 100,
468
- });
469
488
  const others = published.items.map((c) => c.id).filter((c) => !why.has(c));
470
- for (const c of await held(ctx, others))
471
- why.set(c, "subscription");
472
- // Which of these the host says they hold now (live, in its state, inside its until).
473
- const holding = await held(ctx, [...why.keys()]);
489
+ // Which of these the host says they hold now (live, in its state, inside its until), asked once.
490
+ const holding = await held(ctx, [...why.keys(), ...others]);
491
+ for (const c of others)
492
+ if (holding.has(c))
493
+ why.set(c, "subscription");
494
+ const publishedById = new Map(published.items.map((c) => [c.id, c]));
474
495
  const out = [];
475
496
  for (const courseId of [...why.keys()].filter((c) => holding.has(c))) {
476
- const record = await ctx.ops.call("my.get", { object: COURSE, id: courseId });
497
+ // A published course is already here as the caller reads it; another is asked for.
498
+ const record = publishedById.get(courseId) ??
499
+ (await ctx.ops.call("my.get", { object: COURSE, id: courseId }));
477
500
  const outline = asOutline(record.values.outline);
478
- const rows = await progressRows(ctx, courseId);
479
- const done = new Set([...rows.values()]
480
- .filter((r) => r.values.state === "done")
481
- .map((r) => String(r.values.lessonKey)));
501
+ const done = doneKeys(await progressRows(ctx, courseId));
482
502
  const sum = completion(outline, done, completed.has(courseId));
483
503
  const first = outline.sections
484
504
  .flatMap((s) => s.lessons ?? [])
@@ -507,6 +527,13 @@ export const buy = defineTool({
507
527
  courseId: id.optional(),
508
528
  bundleId: id.optional(),
509
529
  email: z.string().trim().max(320).optional().describe("A guest's email address"),
530
+ agreements: z
531
+ .array(z.record(z.string(), z.unknown()))
532
+ .max(20)
533
+ .optional()
534
+ .describe("A guest only: their acceptances of what is due, passed on to the host as they are (each " +
535
+ "{ versionId, typedName, signature?, answers? }); the host checks and records them. A " +
536
+ "signed-in member agrees first."),
510
537
  })
511
538
  .refine((v) => Boolean(v.courseId) !== Boolean(v.bundleId), {
512
539
  message: "Name a course or a bundle, not both",
@@ -543,6 +570,7 @@ export const buy = defineTool({
543
570
  ],
544
571
  pay: "full",
545
572
  ...(input.email === undefined ? {} : { email: input.email }),
573
+ ...(input.agreements === undefined ? {} : { agreements: input.agreements }),
546
574
  });
547
575
  return {
548
576
  id: order.id,
@@ -648,7 +676,7 @@ FROM rec_x_courses_course c ${only} ORDER BY c.title`,
648
676
  params,
649
677
  });
650
678
  const weeks = await ctx.ops.call("query.sql", {
651
- sql: `SELECT date(p.done_at, '-' || ((strftime('%w', p.done_at) + 6) % 7) || ' days') AS week,
679
+ sql: `SELECT ${WEEK("p.done_at")} AS week,
652
680
  count(*) AS done
653
681
  FROM rec_x_courses_progress p WHERE p.state = 'done' AND p.done_at IS NOT NULL
654
682
  ${input.courseId ? "AND p.course = :course" : ""}
@@ -729,15 +757,18 @@ export const draft = defineTool({
729
757
  const videos = [...library.items]
730
758
  .sort((a, b) => score(b) - score(a))
731
759
  .slice(0, sectionsWanted * 3);
732
- const lessons = videos.map((v, i) => ({
733
- kind: "video",
734
- key: `lesson-${i + 1}`,
735
- title: String(v.values.name ?? `Lesson ${i + 1}`)
736
- .replace(/\.[a-z0-9]{2,4}$/i, "")
737
- .slice(0, 200),
738
- video: { media: v.id },
739
- ...(num(v.values.duration) ? { duration: Math.ceil(Number(v.values.duration) / 60) } : {}),
740
- }));
760
+ const lessons = videos.map((v, i) => {
761
+ const seconds = num(v.values.duration);
762
+ return {
763
+ kind: "video",
764
+ key: `lesson-${i + 1}`,
765
+ title: String(v.values.name ?? `Lesson ${i + 1}`)
766
+ .replace(/\.[a-z0-9]{2,4}$/i, "")
767
+ .slice(0, 200),
768
+ video: { media: v.id },
769
+ ...(seconds ? { duration: Math.ceil(seconds / 60) } : {}),
770
+ };
771
+ });
741
772
  const program = programs.items[0];
742
773
  if (program) {
743
774
  lessons.push({
@@ -749,17 +780,13 @@ export const draft = defineTool({
749
780
  session: 0,
750
781
  });
751
782
  }
783
+ // As many parts as the lessons fill, `per` lessons each; one empty part when there are none.
752
784
  const per = Math.max(1, Math.ceil(lessons.length / sectionsWanted));
753
- const sections = [];
754
- for (let s = 0; s * per < lessons.length || (s === 0 && !lessons.length); s += 1) {
755
- sections.push({
756
- key: `part-${s + 1}`,
757
- title: `Part ${s + 1}`,
758
- lessons: lessons.slice(s * per, (s + 1) * per),
759
- });
760
- if (!lessons.length)
761
- break;
762
- }
785
+ const sections = Array.from({ length: Math.max(1, Math.ceil(lessons.length / per)) }, (_, s) => ({
786
+ key: `part-${s + 1}`,
787
+ title: `Part ${s + 1}`,
788
+ lessons: lessons.slice(s * per, (s + 1) * per),
789
+ }));
763
790
  const title = input.title ?? `Draft: ${input.brief.slice(0, 60)}`;
764
791
  const created = await ctx.ops.call("record.create", {
765
792
  object: COURSE,
@@ -797,7 +824,7 @@ export const startSession = defineTool({
797
824
  id: input.courseId,
798
825
  });
799
826
  const found = findLesson(asOutline(record.values.outline), input.lessonKey);
800
- if (!found || found.kind !== "session")
827
+ if (found?.kind !== "session")
801
828
  throw notFound("lesson", input.lessonKey);
802
829
  // Without access the seam gave no program (a holders' part), so there is no session.
803
830
  if (!found.program || found.week === undefined || found.session === undefined) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@composable-os/pack-courses",
3
- "version": "0.1.0-beta.11",
3
+ "version": "0.1.0-beta.14",
4
4
  "license": "FSL-1.1-ALv2",
5
5
  "type": "module",
6
6
  "repository": {
@@ -32,7 +32,7 @@
32
32
  "description": "Video courses sold one at a time or in bundles, watched lesson by lesson on the web and in the app, with progress. Requires Programs."
33
33
  },
34
34
  "dependencies": {
35
- "@composable-os/client": "0.1.0-beta.11",
36
- "@composable-os/sdk": "0.1.0-beta.11"
35
+ "@composable-os/client": "0.1.0-beta.14",
36
+ "@composable-os/sdk": "0.1.0-beta.14"
37
37
  }
38
38
  }