@eliceio/cdk-cli 1.6.0 → 1.7.0

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 (63) hide show
  1. package/es/commands/create/scaffold.d.ts +1 -1
  2. package/es/commands/create/scaffold.js +1 -1
  3. package/es/commands/dev/index.d.ts +1 -1
  4. package/es/commands/dev/index.js +1 -1
  5. package/es/core/quiz-check.js +5 -5
  6. package/es/dev/host-page.js +19 -3
  7. package/es/dev/kv-public-mock.d.ts +101 -0
  8. package/es/dev/kv-public-mock.js +489 -0
  9. package/es/dev/mock-api.d.ts +28 -6
  10. package/es/dev/mock-api.js +57 -59
  11. package/es/dev/mock-http.d.ts +28 -0
  12. package/es/dev/mock-http.js +53 -0
  13. package/es/dev/server.js +8 -3
  14. package/package.json +8 -7
  15. package/skills/_shared/references/02-design-the-material.md +1 -1
  16. package/skills/_shared/references/06-using-the-quiz-template.md +1 -0
  17. package/templates/_shared/lib/cdk-mock.d.ts +37 -0
  18. package/templates/_shared/lib/cdk-mock.js +89 -1
  19. package/templates/_shared/lib/elice-content.d.ts +5 -0
  20. package/templates/_shared/lib/elice-content.js +7 -0
  21. package/templates/board/README.md +118 -0
  22. package/templates/board/commentary.txt +6 -0
  23. package/templates/board/core/board.d.ts +176 -0
  24. package/templates/board/core/board.js +732 -0
  25. package/templates/board/core/dom.d.ts +13 -0
  26. package/templates/board/core/dom.js +83 -0
  27. package/templates/board/core/model.d.ts +58 -0
  28. package/templates/board/core/model.js +217 -0
  29. package/templates/board/core/settings.d.ts +44 -0
  30. package/templates/board/core/settings.js +131 -0
  31. package/templates/board/edit.html +23 -0
  32. package/templates/board/gitignore +4 -0
  33. package/templates/board/index.html +22 -0
  34. package/templates/board/instructor.html +23 -0
  35. package/templates/board/metadata.json +9 -0
  36. package/templates/board/package.json +13 -0
  37. package/templates/board/screens/board.js +318 -0
  38. package/templates/board/screens/edit.js +631 -0
  39. package/templates/board/screens/instructor.js +16 -0
  40. package/templates/board/screens/learn.js +14 -0
  41. package/templates/board/template.json +14 -0
  42. package/templates/board/ui/background.css +8 -0
  43. package/templates/board/ui/board-bg.webp +0 -0
  44. package/templates/board/ui/board.css +1124 -0
  45. package/templates/board/ui/card.js +141 -0
  46. package/templates/board/ui/composer.js +329 -0
  47. package/templates/board/ui/dropdown.js +185 -0
  48. package/templates/board/ui/icons.js +36 -0
  49. package/templates/board/ui/learn.css +141 -0
  50. package/templates/board/ui/menu.js +104 -0
  51. package/templates/board/ui/texts.d.ts +3 -0
  52. package/templates/board/ui/texts.js +162 -0
  53. package/templates/quiz/README.md +16 -6
  54. package/templates/quiz/core/draft.d.ts +32 -0
  55. package/templates/quiz/core/draft.js +224 -0
  56. package/templates/quiz/core/model.d.ts +5 -8
  57. package/templates/quiz/core/model.js +11 -13
  58. package/templates/quiz/screens/edit.js +8 -18
  59. package/templates/quiz/screens/learn.js +62 -13
  60. package/templates/quiz/styles.css +3 -6
  61. package/templates/quiz/template.json +1 -1
  62. package/templates/quiz/ui/templates/page.js +1 -14
  63. package/templates/quiz/ui/texts.js +1 -5
@@ -0,0 +1,732 @@
1
+ // 보드 모델: 모든 사람의 kv `public` 줄을 모아 보드(글 · 하트 · 댓글 · 교육자 표시)로. 화면(screens/board.js · edit.js)이 씁니다.
2
+ //
3
+ // 서버에 보드 표는 없습니다. 저마다 자기 kv의 맨 위 key `public` 줄(16 KB까지)에만 쓰고, 이 모듈이 모두의 줄을 읽어 합칩니다.
4
+ // SDK 공개 API만 씁니다: sdk.kvstore(get · post · delete · readPublic · subscribe), sdk.viewer · scope · isDraft ·
5
+ // initialized · material. 연결 · 다시 연결 · 롱폴은 sdk.kvstore.subscribe가 맡고, 이 모듈은 알림을 받아 다시 읽기만 합니다.
6
+ //
7
+ // `public` 줄 안의 모양 (이 키를 바꾸면 이미 쓴 보드를 읽지 못합니다):
8
+ // posts.{id} { text, image_url?, data?, created_at, updated_at? } 누구나 자기 줄에
9
+ // likes.{postId} { created_at } 누른 사람 자기 줄에
10
+ // comments.{id} { post, text, created_at }
11
+ // hidden.{id} · approved.{id} · pinned.{id} (참) · closed (true) 교육자 줄에 있을 때만 뜻이 있음
12
+ // role 쓴 사람 역할 (서버가 알려 주지 않아 첫 쓰기 전에 씀). 교육자 표시를 믿을지 정할 때만 쓰고 화면에 보이지 않음
13
+ // 그 밖의 key(옛 코드가 쓴 이름 등)는 읽지도 새로 쓰지도 않습니다 (보드는 쓴 사람 이름 · 시각을 보이지 않음)
14
+ //
15
+ // 숨김 · 승인 · 닫기는 화면 수준입니다: 모든 줄이 모든 브라우저에 내려가고, 학생도 API로 자기 줄에 직접 쓸 수 있습니다.
16
+ //
17
+ // 어디에 쓰이는지는 sdk.kvstore가 정합니다: 학습 페이지 · edit 토큰(편집 화면, 편집기 미리보기의 교육자 화면)은 서버,
18
+ // 그 밖의 편집기 미리보기는 이 브라우저 메모리(readPublic이 account 0 하나만 줌, 서버에 안 보냄).
19
+
20
+ //
21
+ // ==================== 상수 · 오류 ====================
22
+ //
23
+
24
+ /** 첫 changed 알림 뒤 이만큼 모았다가 바뀐 줄을 한 번에 읽음 (ms) */
25
+ export const BOARD_BATCH_DELAY = 500;
26
+ /** readPublic({ accountIds }) 한 번에 읽는 사람 수 (서버 최대) */
27
+ export const BOARD_BATCH_MAX = 100;
28
+ /** 읽기에 실패하면 이만큼 기다렸다 전부 다시 읽음 (ms) */
29
+ export const BOARD_RESYNC_DELAY = 3000;
30
+ /** 서버가 받는 `public` 줄 최대 크기 (JSON 바이트) */
31
+ export const BOARD_PUBLIC_MAX_BYTES = 16 * 1024;
32
+
33
+ const PUBLIC_KEY = 'public';
34
+ const ROLES = ['student', 'instructor', 'tutor'];
35
+ /** kv key 이름: 영문 · 숫자 · _ · 한글 (- . 없음) */
36
+ const NAME_PATTERN = /^[0-9A-Za-z_가-힣]{1,64}$/;
37
+
38
+ /**
39
+ * 보드가 던지는 오류. code는 SDK 오류 코드와 같은 문자열(invalid_param · permission_denied · read_only_mode ·
40
+ * not_initialized)이거나 보드만의 코드(board.closed · board.too_large)입니다. 서버 요청 실패는 SDK가 던진 EliceCDKError 그대로.
41
+ */
42
+ export class BoardError extends Error {
43
+ /**
44
+ * @param {string} code
45
+ * @param {string} message
46
+ * @param {unknown} [cause]
47
+ */
48
+ constructor(code, message, cause) {
49
+ super(`[board] ${code} - ${message}`);
50
+ this.name = 'BoardError';
51
+ this.code = code;
52
+ if (cause !== undefined) this.cause = cause;
53
+ }
54
+ }
55
+
56
+ const invalid = message => new BoardError('invalid_param', message);
57
+
58
+ function assertId(id, name = 'id') {
59
+ if (typeof id !== 'string' || !NAME_PATTERN.test(id)) {
60
+ throw invalid(
61
+ `Invalid \`${name}\` "${String(id)}": use letters, digits, "_" or Korean, at most 64.`
62
+ );
63
+ }
64
+ }
65
+
66
+ function assertText(text) {
67
+ if (typeof text !== 'string' || text.trim() === '')
68
+ throw invalid('`text` must be a non-empty string.');
69
+ }
70
+
71
+ function assertImageUrl(url) {
72
+ if (url == null) return;
73
+ if (typeof url !== 'string' || !/^https?:\/\//.test(url))
74
+ throw invalid('`imageUrl` must be an http(s) URL.');
75
+ }
76
+
77
+ function assertData(data) {
78
+ if (data === undefined) return;
79
+ let json;
80
+ try {
81
+ json = JSON.stringify(data);
82
+ } catch {
83
+ json = undefined;
84
+ }
85
+ if (!data || typeof data !== 'object' || Array.isArray(data) || json === undefined) {
86
+ throw invalid('`data` must be a JSON object.');
87
+ }
88
+ }
89
+
90
+ /** JSON 바이트 수 */
91
+ export function jsonBytes(value) {
92
+ return new TextEncoder().encode(JSON.stringify(value) ?? '').length;
93
+ }
94
+
95
+ /** 쓰기 실패를 화면이 받을 오류로: 공개 줄이 꽉 참(storage_limit_exceeded) → board.too_large, 그 밖은 그대로 */
96
+ function toBoardError(err) {
97
+ if (err?.code === 'storage_limit_exceeded') {
98
+ return new BoardError('board.too_large', err.message ?? 'The board data is too large.', err);
99
+ }
100
+ return err;
101
+ }
102
+
103
+ //
104
+ // ==================== 보기 (순수 함수) ====================
105
+ //
106
+
107
+ const isRecord = value => !!value && typeof value === 'object' && !Array.isArray(value);
108
+ const entriesOf = value => (isRecord(value) ? Object.entries(value) : []);
109
+
110
+ /** readPublic 줄 하나를 보드 줄로. 역할은 value.role(없으면 student). 이름은 읽지 않음 */
111
+ export function toRow(row) {
112
+ const value = isRecord(row.value) ? row.value : {};
113
+ return {
114
+ accountId: row.accountId,
115
+ role: ROLES.includes(value.role) ? value.role : 'student',
116
+ value,
117
+ updatedAt: row.updatedAt || null,
118
+ };
119
+ }
120
+
121
+ /** 오래된 것부터; 같으면 계정 · id 순 (모두에게 같은 순서) */
122
+ function compare(a, b) {
123
+ if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;
124
+ if (a.author.accountId !== b.author.accountId) return a.author.accountId - b.author.accountId;
125
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
126
+ }
127
+
128
+ /**
129
+ * 모든 줄을 이 사람이 보는 보드로 합칩니다 (connection 빼고).
130
+ * - 교육자 줄의 hidden · approved · pinned · closed만 셈 (학생 줄의 같은 key는 무시)
131
+ * - requireApproval이면 승인 안 된 학생 글은 pending: 쓴 사람 · 교육자만 봄. 교육자 글은 기다리지 않음
132
+ * - 숨긴 글 · 댓글은 교육자만 봄. 보이지 않는 글의 하트 · 댓글은 같이 빠짐
133
+ * - 모양이 틀린 항목(객체 아님, text · created_at 없음)은 건너뜀
134
+ * @param {Iterable<import('./board.js').BoardRow>} rows
135
+ * @param {import('./board.js').BoardViewContext} context
136
+ */
137
+ export function buildBoardView(rows, context) {
138
+ const all = [...rows];
139
+ const isInstructor = context.role === 'instructor';
140
+ const hidden = new Set();
141
+ const approved = new Set();
142
+ const pinned = new Set();
143
+ let closed = false;
144
+ for (const row of all) {
145
+ if (row.role !== 'instructor') continue;
146
+ for (const [id, flag] of entriesOf(row.value.hidden)) if (flag) hidden.add(id);
147
+ for (const [id, flag] of entriesOf(row.value.approved)) if (flag) approved.add(id);
148
+ for (const [id, flag] of entriesOf(row.value.pinned)) if (flag) pinned.add(id);
149
+ if (row.value.closed === true) closed = true;
150
+ }
151
+
152
+ // 쓴 사람은 이름 없이 줄(account id) · 역할 · 내 것인지만. 화면은 이름 · 시각을 보이지 않는다
153
+ const authorOf = row => ({
154
+ accountId: row.accountId,
155
+ role: row.role,
156
+ isMe: context.accountId != null && row.accountId === context.accountId,
157
+ });
158
+
159
+ const posts = [];
160
+ const likes = new Map();
161
+ const comments = new Map();
162
+ for (const row of all) {
163
+ const author = authorOf(row);
164
+ for (const [id, post] of entriesOf(row.value.posts)) {
165
+ if (!isRecord(post) || typeof post.text !== 'string' || typeof post.created_at !== 'string')
166
+ continue;
167
+ const status = hidden.has(id)
168
+ ? 'hidden'
169
+ : context.requireApproval && row.role !== 'instructor' && !approved.has(id)
170
+ ? 'pending'
171
+ : 'visible';
172
+ if (!isInstructor && (status === 'hidden' || (status === 'pending' && !author.isMe)))
173
+ continue;
174
+ posts.push({
175
+ id,
176
+ text: post.text,
177
+ imageUrl: typeof post.image_url === 'string' ? post.image_url : null,
178
+ data: isRecord(post.data) ? post.data : {},
179
+ createdAt: post.created_at,
180
+ author,
181
+ status,
182
+ pinned: pinned.has(id),
183
+ likeCount: 0,
184
+ likedByMe: false,
185
+ comments: [],
186
+ });
187
+ }
188
+ for (const [postId, like] of entriesOf(row.value.likes)) {
189
+ if (!like) continue;
190
+ const entry = likes.get(postId) ?? { count: 0, mine: false };
191
+ entry.count += 1;
192
+ entry.mine ||= author.isMe;
193
+ likes.set(postId, entry);
194
+ }
195
+ for (const [id, comment] of entriesOf(row.value.comments)) {
196
+ if (
197
+ !isRecord(comment) ||
198
+ typeof comment.post !== 'string' ||
199
+ typeof comment.text !== 'string' ||
200
+ typeof comment.created_at !== 'string'
201
+ ) {
202
+ continue;
203
+ }
204
+ const status = hidden.has(id) ? 'hidden' : 'visible';
205
+ if (status === 'hidden' && !isInstructor) continue;
206
+ const list = comments.get(comment.post) ?? [];
207
+ list.push({
208
+ id,
209
+ postId: comment.post,
210
+ text: comment.text,
211
+ createdAt: comment.created_at,
212
+ author,
213
+ status,
214
+ });
215
+ comments.set(comment.post, list);
216
+ }
217
+ }
218
+
219
+ for (const post of posts) {
220
+ const like = likes.get(post.id);
221
+ post.likeCount = like?.count ?? 0;
222
+ post.likedByMe = like?.mine ?? false;
223
+ post.comments = (comments.get(post.id) ?? []).sort(compare);
224
+ }
225
+ posts.sort(compare);
226
+
227
+ return {
228
+ posts,
229
+ closed,
230
+ requireApproval: context.requireApproval,
231
+ canWrite: context.role !== 'tutor' && (isInstructor || !closed),
232
+ canModerate: isInstructor,
233
+ };
234
+ }
235
+
236
+ const cloneJson = value => (value === undefined ? value : JSON.parse(JSON.stringify(value)));
237
+
238
+ /**
239
+ * 서버가 kv 쓰기를 적용하듯 줄을 고친 새 객체. path는 public 아래 key(예: ['posts', 'p1']), next가 undefined면 지움.
240
+ * 없는 부모는 객체로 만듦. value는 바꾸지 않음
241
+ * @param {Record<string, unknown>} value
242
+ * @param {readonly string[]} path
243
+ * @param {unknown} next
244
+ */
245
+ export function applyWrite(value, path, next) {
246
+ const root = cloneJson(value);
247
+ let parent = root;
248
+ for (const part of path.slice(0, -1)) {
249
+ if (!isRecord(parent[part])) {
250
+ if (next === undefined) return root;
251
+ parent[part] = {};
252
+ }
253
+ parent = parent[part];
254
+ }
255
+ const last = path[path.length - 1];
256
+ if (next === undefined) delete parent[last];
257
+ else parent[last] = cloneJson(next);
258
+ return root;
259
+ }
260
+
261
+ /** key 순서와 상관없는 JSON (내 줄 찾기 비교용) */
262
+ function canonical(value) {
263
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
264
+ if (isRecord(value)) {
265
+ return `{${Object.keys(value)
266
+ .sort()
267
+ .map(k => `${JSON.stringify(k)}:${canonical(value[k])}`)
268
+ .join(',')}}`;
269
+ }
270
+ return JSON.stringify(value) ?? 'null';
271
+ }
272
+
273
+ //
274
+ // ==================== 저장소 ====================
275
+ //
276
+
277
+ /**
278
+ * 한 자료의 모든 `public` 줄을 들고 보드로 만듭니다.
279
+ *
280
+ * 읽기: 처음 · 다시 연결될 때마다(sync) · 롱폴이 바뀜을 알릴 때 전부(readPublic()), changed 알림 뒤에는 바뀐 사람만
281
+ * (readPublic({ accountIds }), BOARD_BATCH_DELAY 모아서). 응답 순서가 뒤바뀔 수 있어 사람마다 마지막 요청 번호를 두고, 옛 응답이
282
+ * 새 것을 덮지 않게 합니다. 내 쓰기는 바로 반영하고 내 줄의 changed 알림은 무시합니다.
283
+ *
284
+ * 내 account id는 공개 SDK에 없어서, 내 줄(kvstore.get('public'))과 값이 같은 readPublic 줄 하나로 알아냅니다
285
+ * (글 · 하트 id가 랜덤이라 남과 겹치지 않음. 같은 줄이 둘 이상이면 모르는 채로 둠).
286
+ */
287
+ class BoardStore {
288
+ constructor(sdk) {
289
+ this.sdk = sdk;
290
+ this.listeners = new Set();
291
+ /** @type {Map<number, any>} */
292
+ this.rows = new Map();
293
+ /** 사람마다 그 줄을 덮은 마지막 요청(또는 내 쓰기) 번호 */
294
+ this.issued = new Map();
295
+ /** 마지막 전부 읽기 번호: 모든 사람을 덮음 */
296
+ this.issuedAll = 0;
297
+ this.counter = 0;
298
+ this.loaded = false;
299
+ this.currentView = null;
300
+ /** kvstore.subscribe의 마지막 연결 상태, 구독 전이면 null */
301
+ this.state = null;
302
+ this.stopRealtime = null;
303
+ this.pending = new Set();
304
+ this.batchTimer = null;
305
+ this.resyncTimer = null;
306
+ /** 내 account id, 모르면 null */
307
+ this.me = null;
308
+ /** 내 `public` 값 (모르면 null) */
309
+ this.own = null;
310
+ /** @type {Promise<void> | null} */
311
+ this.ownLoading = null;
312
+ }
313
+
314
+ /** 보는 사람 역할. 편집기 미리보기 · edit 토큰(과정 관리자만 받음)은 토큰의 viewer와 상관없이 교육자 */
315
+ get role() {
316
+ return this.sdk.isDraft || this.sdk.scope === 'edit'
317
+ ? 'instructor'
318
+ : (this.sdk.viewer ?? 'student');
319
+ }
320
+
321
+ get view() {
322
+ return this.currentView;
323
+ }
324
+
325
+ assertReady() {
326
+ if (!this.sdk.initialized) {
327
+ throw new BoardError('not_initialized', 'Call sdk.init() before using the board.');
328
+ }
329
+ }
330
+
331
+ // ---------- 읽기 ----------
332
+
333
+ subscribe(listener) {
334
+ if (typeof listener !== 'function') throw invalid('The listener must be a function.');
335
+ this.assertReady();
336
+ this.listeners.add(listener);
337
+ if (this.listeners.size === 1) {
338
+ this.stopRealtime = this.sdk.kvstore.subscribe(event => this.onRealtime(event));
339
+ }
340
+ const view = this.currentView;
341
+ if (view) {
342
+ queueMicrotask(() => {
343
+ if (this.listeners.has(listener) && this.currentView === view) listener(view);
344
+ });
345
+ }
346
+ let subscribed = true;
347
+ return () => {
348
+ if (!subscribed) return;
349
+ subscribed = false;
350
+ this.listeners.delete(listener);
351
+ if (this.listeners.size === 0) this.close();
352
+ };
353
+ }
354
+
355
+ async refresh() {
356
+ this.assertReady();
357
+ await this.readAll();
358
+ return this.publish();
359
+ }
360
+
361
+ close() {
362
+ this.stopRealtime?.();
363
+ this.stopRealtime = null;
364
+ this.state = null;
365
+ this.pending.clear();
366
+ clearTimeout(this.batchTimer);
367
+ clearTimeout(this.resyncTimer);
368
+ this.batchTimer = null;
369
+ this.resyncTimer = null;
370
+ }
371
+
372
+ onRealtime(event) {
373
+ if (event.type === 'connection') {
374
+ this.state = event.state;
375
+ if (this.loaded) this.publish();
376
+ return;
377
+ }
378
+ if (event.type === 'sync') {
379
+ void this.readAll().then(
380
+ () => this.publish(),
381
+ () => this.scheduleResync()
382
+ );
383
+ return;
384
+ }
385
+ if (event.type !== 'changed' || event.accountId === this.me || !this.stopRealtime) return;
386
+ this.pending.add(event.accountId);
387
+ this.batchTimer ??= setTimeout(
388
+ () => {
389
+ this.batchTimer = null;
390
+ void this.readPending();
391
+ },
392
+ BOARD_BATCH_DELAY
393
+ );
394
+ }
395
+
396
+ scheduleResync() {
397
+ if (this.resyncTimer != null || !this.stopRealtime) return;
398
+ this.resyncTimer = setTimeout(
399
+ () => {
400
+ this.resyncTimer = null;
401
+ if (this.stopRealtime) this.onRealtime({ type: 'sync' });
402
+ },
403
+ BOARD_RESYNC_DELAY
404
+ );
405
+ }
406
+
407
+ async readPending() {
408
+ const ids = [...this.pending];
409
+ this.pending.clear();
410
+ for (let i = 0; i < ids.length; i += BOARD_BATCH_MAX) {
411
+ try {
412
+ await this.read(ids.slice(i, i + BOARD_BATCH_MAX));
413
+ } catch {
414
+ // 이 사람들만 말고 조금 뒤 전부 다시 읽는다
415
+ this.scheduleResync();
416
+ return;
417
+ }
418
+ }
419
+ this.publish();
420
+ }
421
+
422
+ async readAll() {
423
+ await this.loadOwn();
424
+ await this.read(null);
425
+ }
426
+
427
+ async read(accountIds) {
428
+ const number = ++this.counter;
429
+ if (accountIds) for (const id of accountIds) this.issued.set(id, number);
430
+ else this.issuedAll = number;
431
+
432
+ const rows = (await this.sdk.kvstore.readPublic(accountIds ? { accountIds } : undefined)).map(
433
+ toRow
434
+ );
435
+
436
+ const isLatest = id => number >= Math.max(this.issued.get(id) ?? 0, this.issuedAll);
437
+ const seen = new Set();
438
+ for (const row of rows) {
439
+ seen.add(row.accountId);
440
+ if (isLatest(row.accountId)) this.rows.set(row.accountId, row);
441
+ }
442
+ // 응답에 없는 사람은 줄이 (더) 없음
443
+ for (const id of accountIds ?? [...this.rows.keys()]) {
444
+ if (!seen.has(id) && isLatest(id)) this.rows.delete(id);
445
+ }
446
+ if (!accountIds) this.loaded = true;
447
+ this.findMe();
448
+ if (this.me != null && isLatest(this.me)) this.own = this.rows.get(this.me)?.value ?? null;
449
+ }
450
+
451
+ /** 내 `public` 값을 한 번 읽는다 (실패하면 모르는 채로) */
452
+ loadOwn() {
453
+ this.ownLoading ??= (async () => {
454
+ try {
455
+ const value = await this.sdk.kvstore.get({ key: PUBLIC_KEY });
456
+ if (this.own == null && isRecord(value)) this.own = value;
457
+ } catch {
458
+ // 내 줄을 몰라도 보드는 보인다 ("내 글" 표시만 없음)
459
+ }
460
+ })();
461
+ return this.ownLoading;
462
+ }
463
+
464
+ /** 내 값과 같은 줄이 하나면 그 사람이 나 */
465
+ findMe() {
466
+ if (this.me != null || this.own == null) return;
467
+ const mine = canonical(this.own);
468
+ const matches = [...this.rows.values()].filter(row => canonical(row.value) === mine);
469
+ if (matches.length === 1) this.me = matches[0].accountId;
470
+ }
471
+
472
+ // ---------- 쓰기 ----------
473
+
474
+ /** 학생이 닫힌 보드에 쓰려 하면 board.closed */
475
+ assertOpen() {
476
+ if (this.role !== 'instructor' && this.viewOf().closed) {
477
+ throw new BoardError('board.closed', 'The board is closed.');
478
+ }
479
+ }
480
+
481
+ /** 내 줄의 public.{path} 값 (예: ['posts', id]), 없으면 undefined */
482
+ async readOwn(path) {
483
+ if (!this.loaded) await this.refresh();
484
+ let value = this.own ?? undefined;
485
+ for (const part of path) value = isRecord(value) ? value[part] : undefined;
486
+ return value;
487
+ }
488
+
489
+ /**
490
+ * 내 줄의 public.{path}에 next를 씁니다 (undefined면 지움). 그다음 바로 화면에 보입니다.
491
+ * 서버가 쓴 사람의 역할을 알려 주지 않으므로 바뀌기 전에 역할(public.role)을 없거나 다를 때만 씁니다.
492
+ */
493
+ async write(path, next) {
494
+ this.assertReady();
495
+ const role = this.role;
496
+ if (role === 'tutor')
497
+ throw new BoardError('read_only_mode', 'A tutor cannot write to the board.');
498
+ await this.loadOwn();
499
+ const own = this.own ?? {};
500
+ const needsRole = own.role !== role;
501
+ const value = applyWrite({ ...own, ...(needsRole ? { role } : {}) }, path, next);
502
+ if (jsonBytes(value) > BOARD_PUBLIC_MAX_BYTES) {
503
+ throw new BoardError(
504
+ 'board.too_large',
505
+ `Your board data would exceed ${BOARD_PUBLIC_MAX_BYTES} bytes. Delete some posts or comments first.`
506
+ );
507
+ }
508
+
509
+ const { kvstore } = this.sdk;
510
+ const key = [PUBLIC_KEY, ...path].join('.');
511
+ try {
512
+ if (needsRole) await kvstore.post({ key: `${PUBLIC_KEY}.role`, value: role });
513
+ if (next === undefined) await kvstore.delete(key);
514
+ else await kvstore.post({ key, value: next });
515
+ } catch (err) {
516
+ throw toBoardError(err);
517
+ }
518
+ this.own = value;
519
+
520
+ if (this.me == null || !this.loaded) {
521
+ // 내 줄이 어느 사람인지 모르거나 아직 안 읽었으면, 지역 반영 대신 다시 읽는다 (그때 내 줄을 찾음)
522
+ await this.refresh().catch(() => undefined);
523
+ return;
524
+ }
525
+ this.issued.set(this.me, ++this.counter);
526
+ this.rows.set(
527
+ this.me,
528
+ toRow({ accountId: this.me, value, updatedAt: new Date().toISOString() })
529
+ );
530
+ this.publish();
531
+ }
532
+
533
+ // ---------- 보기 ----------
534
+
535
+ viewOf() {
536
+ const settings = this.sdk.material?.settings?.board ?? {};
537
+ return {
538
+ ...buildBoardView(this.rows.values(), {
539
+ accountId: this.me,
540
+ role: this.role,
541
+ requireApproval: settings.require_approval === true,
542
+ }),
543
+ connection: this.state ?? 'offline',
544
+ me: { role: this.role },
545
+ };
546
+ }
547
+
548
+ publish() {
549
+ const view = this.viewOf();
550
+ this.currentView = view;
551
+ for (const listener of [...this.listeners]) {
552
+ try {
553
+ listener(view);
554
+ } catch (err) {
555
+ setTimeout(() => {
556
+ throw err;
557
+ });
558
+ }
559
+ }
560
+ return view;
561
+ }
562
+ }
563
+
564
+ //
565
+ // ==================== createBoard ====================
566
+ //
567
+
568
+ /** SDK마다 보드 하나: 같은 sdk면 줄 · 연결을 같이 씀 */
569
+ const boards = new WeakMap();
570
+
571
+ /** 글 · 댓글 id: 사람끼리 안 겹치는 랜덤, kv key 이름(- 없음) */
572
+ function generateId(prefix) {
573
+ const random =
574
+ typeof globalThis.crypto?.randomUUID === 'function'
575
+ ? globalThis.crypto.randomUUID().replace(/-/g, '')
576
+ : Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16)).join('');
577
+ return `${prefix}${random.slice(0, 20)}`;
578
+ }
579
+
580
+ /**
581
+ * 자료의 보드. 같은 sdk면 같은 객체를 돌려줍니다. sdk는 아직 init 중이어도 되고, 호출할 때 확인합니다.
582
+ * settings.board.require_approval: 학생 글은 승인 뒤 공개.
583
+ * @param {import('./board.js').BoardSdk} sdk
584
+ * @returns {import('./board.js').Board}
585
+ */
586
+ export function createBoard(sdk) {
587
+ if (!sdk || typeof sdk !== 'object') throw invalid('Pass an EliceCDK instance.');
588
+ const existing = boards.get(sdk);
589
+ if (existing) return existing;
590
+ const kv = sdk?.kvstore;
591
+ if (typeof kv?.readPublic !== 'function' || typeof kv?.subscribe !== 'function') {
592
+ throw invalid('Pass an EliceCDK instance whose kvstore has readPublic and subscribe.');
593
+ }
594
+
595
+ const store = new BoardStore(sdk);
596
+ const moderator = () => {
597
+ store.assertReady();
598
+ if (store.role !== 'instructor') {
599
+ throw new BoardError('permission_denied', 'Only instructors can moderate the board.');
600
+ }
601
+ return store;
602
+ };
603
+ const writer = () => {
604
+ store.assertReady();
605
+ store.assertOpen();
606
+ return store;
607
+ };
608
+ const now = () => new Date().toISOString();
609
+
610
+ const board = {
611
+ get view() {
612
+ return store.view;
613
+ },
614
+ subscribe: listener => store.subscribe(listener),
615
+ refresh: async () => store.refresh(),
616
+
617
+ addPost: async params => {
618
+ const target = writer();
619
+ assertText(params?.text);
620
+ assertImageUrl(params.imageUrl);
621
+ assertData(params.data);
622
+ const id = generateId('p');
623
+ await target.write(['posts', id], {
624
+ text: params.text,
625
+ ...(params.imageUrl ? { image_url: params.imageUrl } : {}),
626
+ ...(params.data ? { data: params.data } : {}),
627
+ created_at: now(),
628
+ });
629
+ return id;
630
+ },
631
+
632
+ updatePost: async params => {
633
+ const target = writer();
634
+ assertId(params?.id);
635
+ if (params.text !== undefined) assertText(params.text);
636
+ assertImageUrl(params.imageUrl);
637
+ assertData(params.data);
638
+ const current = await target.readOwn(['posts', params.id]);
639
+ if (!isRecord(current)) {
640
+ throw invalid(
641
+ `No post of yours with id "${params.id}": only your own posts can be updated.`
642
+ );
643
+ }
644
+ const { image_url: imageUrl, data, ...rest } = current;
645
+ const nextImage = params.imageUrl === undefined ? imageUrl : params.imageUrl;
646
+ const nextData = params.data === undefined ? data : params.data;
647
+ await target.write(['posts', params.id], {
648
+ ...rest,
649
+ ...(params.text !== undefined ? { text: params.text } : {}),
650
+ ...(nextImage ? { image_url: nextImage } : {}),
651
+ ...(nextData ? { data: nextData } : {}),
652
+ updated_at: now(),
653
+ });
654
+ },
655
+
656
+ removePost: async params => {
657
+ store.assertReady();
658
+ assertId(params?.id);
659
+ await store.write(['posts', params.id], undefined);
660
+ },
661
+
662
+ like: async params => {
663
+ const target = writer();
664
+ assertId(params?.postId, 'postId');
665
+ await target.write(['likes', params.postId], { created_at: now() });
666
+ },
667
+
668
+ unlike: async params => {
669
+ const target = writer();
670
+ assertId(params?.postId, 'postId');
671
+ await target.write(['likes', params.postId], undefined);
672
+ },
673
+
674
+ addComment: async params => {
675
+ const target = writer();
676
+ assertId(params?.postId, 'postId');
677
+ assertText(params.text);
678
+ const id = generateId('c');
679
+ await target.write(['comments', id], {
680
+ post: params.postId,
681
+ text: params.text,
682
+ created_at: now(),
683
+ });
684
+ return id;
685
+ },
686
+
687
+ removeComment: async params => {
688
+ store.assertReady();
689
+ assertId(params?.id);
690
+ await store.write(['comments', params.id], undefined);
691
+ },
692
+
693
+ hide: async params => {
694
+ const target = moderator();
695
+ assertId(params?.id);
696
+ await target.write(['hidden', params.id], true);
697
+ },
698
+
699
+ unhide: async params => {
700
+ const target = moderator();
701
+ assertId(params?.id);
702
+ await target.write(['hidden', params.id], undefined);
703
+ },
704
+
705
+ approve: async params => {
706
+ const target = moderator();
707
+ assertId(params?.id);
708
+ await target.write(['approved', params.id], true);
709
+ },
710
+
711
+ pin: async params => {
712
+ const target = moderator();
713
+ assertId(params?.id);
714
+ await target.write(['pinned', params.id], true);
715
+ },
716
+
717
+ unpin: async params => {
718
+ const target = moderator();
719
+ assertId(params?.id);
720
+ await target.write(['pinned', params.id], undefined);
721
+ },
722
+
723
+ setClosed: async params => {
724
+ const target = moderator();
725
+ if (typeof params?.closed !== 'boolean') throw invalid('`closed` must be a boolean.');
726
+ await target.write(['closed'], params.closed ? true : undefined);
727
+ },
728
+ };
729
+
730
+ boards.set(sdk, board);
731
+ return board;
732
+ }