@eliceio/cdk-cli 0.0.0-stage → 0.1.0-alpha.1
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/README.md +511 -2
- package/es/bin/index.d.ts +2 -0
- package/es/bin/index.js +10 -0
- package/es/cli.d.ts +5 -0
- package/es/cli.js +171 -0
- package/es/commands/build/index.d.ts +27 -0
- package/es/commands/build/index.js +154 -0
- package/es/commands/check/index.d.ts +9 -0
- package/es/commands/check/index.js +31 -0
- package/es/commands/create/index.d.ts +8 -0
- package/es/commands/create/index.js +22 -0
- package/es/commands/create/scaffold.d.ts +24 -0
- package/es/commands/create/scaffold.js +82 -0
- package/es/commands/dev/index.d.ts +6 -0
- package/es/commands/dev/index.js +40 -0
- package/es/commands/doctor/index.d.ts +33 -0
- package/es/commands/doctor/index.js +230 -0
- package/es/core/collect.d.ts +21 -0
- package/es/core/collect.js +89 -0
- package/es/core/config.d.ts +55 -0
- package/es/core/config.js +109 -0
- package/es/core/manifest.d.ts +15 -0
- package/es/core/manifest.js +43 -0
- package/es/core/minify.d.ts +18 -0
- package/es/core/minify.js +93 -0
- package/es/core/prepare.d.ts +12 -0
- package/es/core/prepare.js +86 -0
- package/es/core/protocol.d.ts +2 -0
- package/es/core/protocol.js +4 -0
- package/es/core/zip.d.ts +4 -0
- package/es/core/zip.js +17 -0
- package/es/dev/grading.d.ts +15 -0
- package/es/dev/grading.js +37 -0
- package/es/dev/host-page.d.ts +7 -0
- package/es/dev/host-page.js +240 -0
- package/es/dev/inject.d.ts +8 -0
- package/es/dev/inject.js +38 -0
- package/es/dev/mock-api.d.ts +65 -0
- package/es/dev/mock-api.js +269 -0
- package/es/dev/server.d.ts +24 -0
- package/es/dev/server.js +294 -0
- package/es/engines/static/index.d.ts +3 -0
- package/es/engines/static/index.js +11 -0
- package/es/engines/types.d.ts +12 -0
- package/es/engines/vite/index.d.ts +2 -0
- package/es/engines/vite/index.js +4 -0
- package/es/index.d.ts +2 -0
- package/es/index.js +2 -0
- package/es/rules/check.d.ts +2 -0
- package/es/rules/check.js +209 -0
- package/es/rules/index.d.ts +8 -0
- package/es/rules/index.js +7 -0
- package/es/rules/manifest.d.ts +39 -0
- package/es/rules/manifest.js +168 -0
- package/es/rules/node.d.ts +11 -0
- package/es/rules/node.js +87 -0
- package/es/rules/path.d.ts +7 -0
- package/es/rules/path.js +35 -0
- package/es/rules/refs.d.ts +19 -0
- package/es/rules/refs.js +111 -0
- package/es/rules/skip.d.ts +12 -0
- package/es/rules/skip.js +55 -0
- package/es/rules/spec.d.ts +3 -0
- package/es/rules/spec.js +6 -0
- package/es/rules/types.d.ts +138 -0
- package/es/rules/unused.d.ts +7 -0
- package/es/rules/unused.js +21 -0
- package/es/rules/zip.d.ts +13 -0
- package/es/rules/zip.js +45 -0
- package/es/rules.json.js +3 -0
- package/es/types.d.ts +4 -0
- package/es/version.d.ts +1 -0
- package/es/version.js +3 -0
- package/package.json +48 -3
- package/rules.json +555 -0
- package/templates/_shared/lib/cdk-mock.d.ts +94 -0
- package/templates/_shared/lib/cdk-mock.js +429 -0
- package/templates/_shared/lib/cdk.js +3 -0
- package/templates/_shared/lib/elice-content.css +252 -0
- package/templates/_shared/lib/elice-content.d.ts +121 -0
- package/templates/_shared/lib/elice-content.js +541 -0
- package/templates/_shared/lib/elice-tokens.css +446 -0
- package/templates/blank/README.md +64 -0
- package/templates/blank/content.json +4 -0
- package/templates/blank/edit.html +15 -0
- package/templates/blank/elice.config.json +12 -0
- package/templates/blank/gitignore +3 -0
- package/templates/blank/index.html +15 -0
- package/templates/blank/instructor.html +15 -0
- package/templates/blank/screens/edit.js +21 -0
- package/templates/blank/screens/instructor.js +9 -0
- package/templates/blank/screens/learn.js +19 -0
- package/templates/blank/styles.css +1 -0
- package/templates/quiz/README.md +108 -0
- package/templates/quiz/content.json +81 -0
- package/templates/quiz/core/behaviors.d.ts +59 -0
- package/templates/quiz/core/behaviors.js +309 -0
- package/templates/quiz/core/dom.d.ts +13 -0
- package/templates/quiz/core/dom.js +83 -0
- package/templates/quiz/core/editor.d.ts +48 -0
- package/templates/quiz/core/editor.js +206 -0
- package/templates/quiz/core/markdown.d.ts +2 -0
- package/templates/quiz/core/markdown.js +84 -0
- package/templates/quiz/core/model.d.ts +20 -0
- package/templates/quiz/core/model.js +203 -0
- package/templates/quiz/edit.html +17 -0
- package/templates/quiz/elice.config.json +14 -0
- package/templates/quiz/gitignore +3 -0
- package/templates/quiz/grading.json +13 -0
- package/templates/quiz/index.html +17 -0
- package/templates/quiz/instructor.html +17 -0
- package/templates/quiz/screens/edit.js +139 -0
- package/templates/quiz/screens/instructor.js +27 -0
- package/templates/quiz/screens/learn.js +50 -0
- package/templates/quiz/styles.css +510 -0
- package/templates/quiz/ui/templates/choice.js +22 -0
- package/templates/quiz/ui/templates/edit.d.ts +14 -0
- package/templates/quiz/ui/templates/edit.js +187 -0
- package/templates/quiz/ui/templates/group.js +47 -0
- package/templates/quiz/ui/templates/index.d.ts +5 -0
- package/templates/quiz/ui/templates/index.js +17 -0
- package/templates/quiz/ui/templates/order.js +35 -0
- package/templates/quiz/ui/templates/page.js +29 -0
- package/templates/quiz/ui/templates/question.js +28 -0
- package/templates/quiz/ui/templates/text.js +16 -0
- package/templates/quiz/ui/texts.d.ts +3 -0
- package/templates/quiz/ui/texts.js +128 -0
- package/templates/quiz/ui/theme.css +50 -0
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @eliceio/cdk 1.x(EliceCDK)와 같은 공개 인터페이스를 가진 mock · 템플릿이 제공 (고치지 마세요)
|
|
3
|
+
*
|
|
4
|
+
* 서버 없이 화면을 시험할 때 키트가 대신 씁니다. 실제 SDK와 다른 점:
|
|
5
|
+
* - 채점: 프로젝트의 grading.json(유형 · 정답 · 채점 기준, 유형이 없으면 elice.config.json gradingTypes의 첫 유형)으로 로컬 채점 (없으면 제출하면 100점)
|
|
6
|
+
* - 저장: 설정 화면이 저장한 내용과 제출 기록을 브라우저에 남겨 다른 화면에서도 보임
|
|
7
|
+
* (sandbox라 저장소가 막히면 이 페이지 안에서만)
|
|
8
|
+
* - 보는 사람: 주소에 #viewer=student | instructor | tutor (mock 전용, 기본 student)
|
|
9
|
+
* #preview=1 · #edit=1은 실제 SDK처럼 토큰 없는 draft (viewer는 instructor)
|
|
10
|
+
* - 수업 페이지 이동: 아무 데도 가지 않고, 이전·다음 페이지는 없음(false)
|
|
11
|
+
* - 시나리오: 주소에 ?mock=session_expired | rate_limited | request_failed | external_service_error
|
|
12
|
+
* | slow | content_not_ready | unauthorized
|
|
13
|
+
*
|
|
14
|
+
* 실제 SDK: @eliceio/cdk 1.x (eliceio-cdk-v2 feat/PLAT-4973-monorepo) 기준
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const ErrorCode = Object.freeze({
|
|
18
|
+
Init: 'init',
|
|
19
|
+
InvalidParam: 'invalid_param',
|
|
20
|
+
InvalidToken: 'invalid_token',
|
|
21
|
+
NotInitialized: 'not_initialized',
|
|
22
|
+
Unauthorized: 'unauthorized',
|
|
23
|
+
SessionExpired: 'session_expired',
|
|
24
|
+
PermissionDenied: 'permission_denied',
|
|
25
|
+
ReadOnlyMode: 'read_only_mode',
|
|
26
|
+
ScreenNotSupported: 'screen_not_supported',
|
|
27
|
+
ContentNotReady: 'content_not_ready',
|
|
28
|
+
InvalidInput: 'invalid_input',
|
|
29
|
+
RateLimited: 'rate_limited',
|
|
30
|
+
ExternalServiceError: 'external_service_error',
|
|
31
|
+
NavigationTimeout: 'navigation_timeout',
|
|
32
|
+
RequestFailed: 'request_failed',
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
export class EliceCDKError extends Error {
|
|
36
|
+
static code = ErrorCode;
|
|
37
|
+
constructor(code, message, cause) {
|
|
38
|
+
super(`[@eliceio/cdk mock] ${code} - ${message}`, { cause });
|
|
39
|
+
this.code = code;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const VIEWERS = Object.freeze(['student', 'instructor', 'tutor']);
|
|
44
|
+
const MAX_ANSWER_BYTES = 64 * 1024;
|
|
45
|
+
const STORE_PREFIX = 'elice-content-mock:';
|
|
46
|
+
const MESSAGE_SOURCE = 'eliceio-content-sdk';
|
|
47
|
+
const SETTINGS_MESSAGE_TYPE = 'settings-change';
|
|
48
|
+
/** 템플릿의 metadata.json 진입 파일 (elice.config.json `screens`가 있으면 그것) */
|
|
49
|
+
const DEFAULT_ENTRIES = Object.freeze({
|
|
50
|
+
learn: 'index.html',
|
|
51
|
+
instructor: 'instructor.html',
|
|
52
|
+
edit: 'edit.html',
|
|
53
|
+
});
|
|
54
|
+
/** rubric(AI) 채점 흉내 점수 */
|
|
55
|
+
const RUBRIC_MOCK_SCORE = 80;
|
|
56
|
+
|
|
57
|
+
/** sandbox(출처 없음)에서는 localStorage가 예외를 내므로 메모리로 대신한다 */
|
|
58
|
+
function createStore() {
|
|
59
|
+
const memory = new Map();
|
|
60
|
+
let storage = null;
|
|
61
|
+
try {
|
|
62
|
+
// ecdk-ignore-next-line api.storage (막히면 아래 catch에서 메모리로)
|
|
63
|
+
storage = globalThis.localStorage ?? null;
|
|
64
|
+
storage?.getItem('x');
|
|
65
|
+
} catch {
|
|
66
|
+
storage = null;
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
persistent: storage !== null,
|
|
70
|
+
get(key, fallback) {
|
|
71
|
+
try {
|
|
72
|
+
const raw = storage ? storage.getItem(STORE_PREFIX + key) : memory.get(key);
|
|
73
|
+
return raw === null || raw === undefined ? fallback : JSON.parse(raw);
|
|
74
|
+
} catch {
|
|
75
|
+
return fallback;
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
set(key, value) {
|
|
79
|
+
const raw = JSON.stringify(value);
|
|
80
|
+
if (storage) storage.setItem(STORE_PREFIX + key, raw);
|
|
81
|
+
else memory.set(key, raw);
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function parseHash(hash) {
|
|
87
|
+
const params = new URLSearchParams(hash.replace(/^#/, ''));
|
|
88
|
+
return {
|
|
89
|
+
token: params.get('token'),
|
|
90
|
+
preview: params.get('preview'),
|
|
91
|
+
edit: params.get('edit'),
|
|
92
|
+
viewer: params.get('viewer'),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const normalize = (v) =>
|
|
97
|
+
typeof v === 'string'
|
|
98
|
+
? v.trim().toLowerCase()
|
|
99
|
+
: Array.isArray(v)
|
|
100
|
+
? v.map(normalize).sort()
|
|
101
|
+
: v && typeof v === 'object'
|
|
102
|
+
? Object.fromEntries(
|
|
103
|
+
Object.keys(v)
|
|
104
|
+
.sort()
|
|
105
|
+
.map((k) => [k, normalize(v[k])]),
|
|
106
|
+
)
|
|
107
|
+
: v;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* elice-material `grading` 흉내: on_access · on_submit · pattern(exact | regex) · rubric · manual · none.
|
|
111
|
+
* 실제 서버처럼 요청 안에서 바로 채점한 `{ isCorrect, score }`만 돌려준다.
|
|
112
|
+
* pattern exact는 서버처럼 답 전체를 한 번에 비교한다 (부분 점수 없음).
|
|
113
|
+
* rubric(AI 채점)은 바로 80점으로 흉내 내고, manual · none · on_access는 점수가 없다(null).
|
|
114
|
+
*/
|
|
115
|
+
export function gradeLocally(grading, answer) {
|
|
116
|
+
const type = grading?.type ?? 'on_submit';
|
|
117
|
+
if (type === 'on_submit') return { isCorrect: true, score: 100 };
|
|
118
|
+
if (type === 'pattern') {
|
|
119
|
+
let ok;
|
|
120
|
+
if (grading.match === 'regex') ok = new RegExp(String(grading.answer_key)).test(String(answer));
|
|
121
|
+
else ok = JSON.stringify(normalize(answer)) === JSON.stringify(normalize(grading.answer_key));
|
|
122
|
+
return { isCorrect: ok, score: ok ? 100 : 0 };
|
|
123
|
+
}
|
|
124
|
+
if (type === 'rubric') return { isCorrect: true, score: RUBRIC_MOCK_SCORE };
|
|
125
|
+
return { isCorrect: null, score: null };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @typedef {object} MockOptions
|
|
132
|
+
* @property {() => void} [onSessionExpired]
|
|
133
|
+
* @property {string} [scenario] ?mock= 대신 직접 지정
|
|
134
|
+
* @property {object} [grading] elice.config.json 대신 직접 지정
|
|
135
|
+
* @property {Record<string, unknown>} [settings] 처음 저장된 내용
|
|
136
|
+
* @property {(url: string) => Promise<unknown>} [loadJson] 테스트용
|
|
137
|
+
* @property {number} [delayMs] 응답 지연 (scenario=slow면 1500)
|
|
138
|
+
*/
|
|
139
|
+
|
|
140
|
+
export class MockEliceCDK {
|
|
141
|
+
initialized = false;
|
|
142
|
+
isMock = true;
|
|
143
|
+
|
|
144
|
+
#options;
|
|
145
|
+
#store = createStore();
|
|
146
|
+
#scope = null;
|
|
147
|
+
#viewer = null;
|
|
148
|
+
#screen = null;
|
|
149
|
+
#entries = DEFAULT_ENTRIES;
|
|
150
|
+
#grading = null;
|
|
151
|
+
#account = null;
|
|
152
|
+
#metadata = null;
|
|
153
|
+
#isDraft = false;
|
|
154
|
+
#isSessionExpired = false;
|
|
155
|
+
#scenario = null;
|
|
156
|
+
/** draft의 제출은 실제 SDK처럼 메모리에만 */
|
|
157
|
+
#draftSubmissions = [];
|
|
158
|
+
#navigation;
|
|
159
|
+
|
|
160
|
+
/** @param {MockOptions} [options] */
|
|
161
|
+
constructor(options = {}) {
|
|
162
|
+
this.#options = options;
|
|
163
|
+
const assertNavigable = () => {
|
|
164
|
+
this.#assertReady();
|
|
165
|
+
this.#assertScreen('learn', 'instructor');
|
|
166
|
+
};
|
|
167
|
+
this.#navigation = Object.freeze({
|
|
168
|
+
previous: () => assertNavigable(),
|
|
169
|
+
next: () => assertNavigable(),
|
|
170
|
+
navigate: (_lecturePageId) => assertNavigable(),
|
|
171
|
+
getHasPrevious: async () => {
|
|
172
|
+
assertNavigable();
|
|
173
|
+
return false;
|
|
174
|
+
},
|
|
175
|
+
getHasNext: async () => {
|
|
176
|
+
assertNavigable();
|
|
177
|
+
return false;
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
get account() {
|
|
183
|
+
return this.#account;
|
|
184
|
+
}
|
|
185
|
+
get scope() {
|
|
186
|
+
return this.#scope;
|
|
187
|
+
}
|
|
188
|
+
get viewer() {
|
|
189
|
+
return this.#viewer;
|
|
190
|
+
}
|
|
191
|
+
get screen() {
|
|
192
|
+
return this.#screen;
|
|
193
|
+
}
|
|
194
|
+
get metadata() {
|
|
195
|
+
return this.#metadata;
|
|
196
|
+
}
|
|
197
|
+
get locale() {
|
|
198
|
+
return 'ko';
|
|
199
|
+
}
|
|
200
|
+
get isDraft() {
|
|
201
|
+
return this.#isDraft;
|
|
202
|
+
}
|
|
203
|
+
get isSessionExpired() {
|
|
204
|
+
return this.#isSessionExpired;
|
|
205
|
+
}
|
|
206
|
+
/** 수업 페이지 이동. mock은 이동하지 않고 이전·다음 페이지가 없다고 답한다 */
|
|
207
|
+
get navigation() {
|
|
208
|
+
return this.#navigation;
|
|
209
|
+
}
|
|
210
|
+
get material() {
|
|
211
|
+
if (!this.initialized) return null;
|
|
212
|
+
return {
|
|
213
|
+
description: { type: 'text', text: '' },
|
|
214
|
+
entries: this.#entries,
|
|
215
|
+
settings: this.#store.get('settings', {}),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
get result() {
|
|
219
|
+
if (!this.initialized || this.#isDraft) return null;
|
|
220
|
+
return this.#store.get('result', null);
|
|
221
|
+
}
|
|
222
|
+
/** mock 전용: 저장소가 브라우저에 남는지 (sandbox면 false) */
|
|
223
|
+
get persistent() {
|
|
224
|
+
return this.#store.persistent;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async init(initOptions = {}) {
|
|
228
|
+
this.initialized = false;
|
|
229
|
+
const hash = initOptions.hash ?? globalThis.location?.hash ?? '';
|
|
230
|
+
const params = parseHash(hash);
|
|
231
|
+
const search = new URLSearchParams(globalThis.location?.search ?? '');
|
|
232
|
+
this.#scenario = this.#options.scenario ?? search.get('mock');
|
|
233
|
+
await this.#delay();
|
|
234
|
+
if (this.#scenario === 'content_not_ready')
|
|
235
|
+
throw new EliceCDKError(ErrorCode.ContentNotReady, 'No saved version (mock).');
|
|
236
|
+
if (this.#scenario === 'unauthorized')
|
|
237
|
+
throw new EliceCDKError(ErrorCode.Unauthorized, 'Invalid token (mock).');
|
|
238
|
+
|
|
239
|
+
const isDraft = params.token == null && (params.preview === '1' || params.edit === '1');
|
|
240
|
+
// 실제 SDK: draft는 instructor가 본다. 토큰이 있는 경우를 흉내 낼 때만 #viewer=로 고른다
|
|
241
|
+
const viewer = isDraft ? 'instructor' : (params.viewer ?? 'student');
|
|
242
|
+
if (!VIEWERS.includes(viewer))
|
|
243
|
+
throw new EliceCDKError(ErrorCode.InvalidParam, `Unknown viewer: ${viewer}`);
|
|
244
|
+
|
|
245
|
+
if (this.#options.settings && Object.keys(this.#store.get('settings', {})).length === 0)
|
|
246
|
+
this.#store.set('settings', this.#options.settings);
|
|
247
|
+
const config = this.#options.grading ? null : await this.#loadConfig();
|
|
248
|
+
this.#grading = this.#options.grading ?? config ?? null;
|
|
249
|
+
this.#entries = config?.screens ?? DEFAULT_ENTRIES;
|
|
250
|
+
|
|
251
|
+
this.#isDraft = isDraft;
|
|
252
|
+
this.#isSessionExpired = false;
|
|
253
|
+
this.#draftSubmissions = [];
|
|
254
|
+
this.#viewer = viewer;
|
|
255
|
+
this.#scope = params.edit === '1' ? 'edit' : 'learn';
|
|
256
|
+
// 실제 SDK와 같은 규칙: edit scope면 edit, 교육자이고 교육자 진입 파일이 있으면 instructor, 그 밖은 learn.
|
|
257
|
+
// draft는 fragment가 화면을 알려 준다 (#edit=1이면 edit, 아니면 learn)
|
|
258
|
+
this.#screen =
|
|
259
|
+
this.#scope === 'edit'
|
|
260
|
+
? 'edit'
|
|
261
|
+
: !isDraft && viewer === 'instructor' && this.#entries.instructor
|
|
262
|
+
? 'instructor'
|
|
263
|
+
: 'learn';
|
|
264
|
+
this.#account = {
|
|
265
|
+
anonymousId: isDraft ? 'preview' : 'mock-student',
|
|
266
|
+
fullname: viewer === 'tutor' ? '김하늘 (mock)' : null,
|
|
267
|
+
};
|
|
268
|
+
this.#metadata = {
|
|
269
|
+
materialId: '00000000-0000-0000-0000-000000000000',
|
|
270
|
+
lecturePageId: null,
|
|
271
|
+
courseId: null,
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
this.initialized = true;
|
|
275
|
+
// "들어오면 완료": 학생이 처음 열면 서버가 100점으로 기록한다
|
|
276
|
+
if (
|
|
277
|
+
this.#grading?.type === 'on_access' &&
|
|
278
|
+
viewer === 'student' &&
|
|
279
|
+
!isDraft &&
|
|
280
|
+
this.#store.get('result', null) === null
|
|
281
|
+
)
|
|
282
|
+
this.#store.set('result', {
|
|
283
|
+
score: 100,
|
|
284
|
+
submitCount: 0,
|
|
285
|
+
completedAt: new Date().toISOString(),
|
|
286
|
+
});
|
|
287
|
+
if (this.#scenario === 'session_expired') {
|
|
288
|
+
setTimeout(() => {
|
|
289
|
+
this.#isSessionExpired = true;
|
|
290
|
+
this.#options.onSessionExpired?.();
|
|
291
|
+
}, 0);
|
|
292
|
+
}
|
|
293
|
+
return this;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 실제 SDK처럼 요청 안에서 채점한 `{ isCorrect, score }`를 돌려준다.
|
|
298
|
+
* student만 기록하고, instructor는 채점만, draft는 메모리에만 남긴다.
|
|
299
|
+
*/
|
|
300
|
+
async submit(answer) {
|
|
301
|
+
this.#assertReady();
|
|
302
|
+
this.#assertScreen('learn', 'instructor');
|
|
303
|
+
if (this.#viewer === 'tutor')
|
|
304
|
+
throw new EliceCDKError(ErrorCode.ReadOnlyMode, 'Submissions are not allowed for a tutor.');
|
|
305
|
+
if (this.#scenario === 'rate_limited')
|
|
306
|
+
throw new EliceCDKError(ErrorCode.RateLimited, 'Too many submissions (mock).');
|
|
307
|
+
if (this.#scenario === 'request_failed')
|
|
308
|
+
throw new EliceCDKError(ErrorCode.RequestFailed, 'Network error (mock).');
|
|
309
|
+
if (this.#scenario === 'external_service_error')
|
|
310
|
+
throw new EliceCDKError(ErrorCode.ExternalServiceError, 'Grading failed (mock).');
|
|
311
|
+
if (new TextEncoder().encode(JSON.stringify(answer ?? null)).byteLength > MAX_ANSWER_BYTES)
|
|
312
|
+
throw new EliceCDKError(ErrorCode.InvalidInput, 'Answer is over 64KB.');
|
|
313
|
+
await this.#delay();
|
|
314
|
+
|
|
315
|
+
const res = gradeLocally(this.#grading, answer);
|
|
316
|
+
if (this.#isDraft) this.#draftSubmissions.unshift(this.#submission(answer, res, 'preview'));
|
|
317
|
+
else if (this.#viewer === 'student') this.#record(res, answer);
|
|
318
|
+
return res;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async history(options = {}) {
|
|
322
|
+
this.#assertReady();
|
|
323
|
+
await this.#delay();
|
|
324
|
+
const { offset = 0, limit = 20 } = options;
|
|
325
|
+
const submissions = this.#isDraft
|
|
326
|
+
? this.#draftSubmissions
|
|
327
|
+
: this.#store.get('submissions', []);
|
|
328
|
+
return submissions.slice(offset, offset + limit);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* 설정 화면(screen edit)에서만. 실제 SDK처럼 편집 페이지(부모 창)에 postMessage로 넘기고,
|
|
333
|
+
* mock은 브라우저에도 남겨 다른 화면의 `material.settings`로 보이게 한다.
|
|
334
|
+
*/
|
|
335
|
+
saveSettings(settings) {
|
|
336
|
+
this.#assertReady();
|
|
337
|
+
this.#assertScreen('edit');
|
|
338
|
+
this.#store.set('settings', settings);
|
|
339
|
+
const parent = globalThis.parent;
|
|
340
|
+
if (parent && parent !== globalThis && typeof parent.postMessage === 'function') {
|
|
341
|
+
// sandbox(출처 null)라 부모 출처를 알 수 없어 실제 SDK도 '*'로 보낸다. 편집 페이지가 event.source로 확인
|
|
342
|
+
// ecdk-ignore-next-line sec.postmessage-wildcard
|
|
343
|
+
parent.postMessage(
|
|
344
|
+
{
|
|
345
|
+
source: MESSAGE_SOURCE,
|
|
346
|
+
type: SETTINGS_MESSAGE_TYPE,
|
|
347
|
+
materialId: this.#metadata.materialId,
|
|
348
|
+
payload: { settings },
|
|
349
|
+
},
|
|
350
|
+
'*',
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** 실제 SDK: 토큰 자동 갱신을 멈춘다. mock은 갱신이 없어 아무것도 하지 않는다 */
|
|
356
|
+
dispose() {}
|
|
357
|
+
|
|
358
|
+
/** mock 전용: 저장한 내용·제출·결과 지우기 */
|
|
359
|
+
reset() {
|
|
360
|
+
this.#store.set('settings', {});
|
|
361
|
+
this.#store.set('submissions', []);
|
|
362
|
+
this.#store.set('result', null);
|
|
363
|
+
this.#draftSubmissions = [];
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
#assertReady() {
|
|
367
|
+
if (!this.initialized) throw new EliceCDKError(ErrorCode.NotInitialized, 'Call init() first.');
|
|
368
|
+
if (this.#isSessionExpired)
|
|
369
|
+
throw new EliceCDKError(ErrorCode.SessionExpired, 'Session expired (mock).');
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
#assertScreen(...screens) {
|
|
373
|
+
if (!screens.includes(this.#screen))
|
|
374
|
+
throw new EliceCDKError(
|
|
375
|
+
ErrorCode.ScreenNotSupported,
|
|
376
|
+
`This call is only available on the ${screens.join(' or ')} screen.`,
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
#submission(answer, res, prefix) {
|
|
381
|
+
return {
|
|
382
|
+
id: `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
383
|
+
materialVersionId: prefix,
|
|
384
|
+
accountId: 0,
|
|
385
|
+
createdAt: new Date().toISOString(),
|
|
386
|
+
answer,
|
|
387
|
+
isCorrect: res.isCorrect,
|
|
388
|
+
score: res.score,
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 서버의 result 흉내: score는 가장 최근 채점 값 (점수 없는 채점은 그대로), completedAt은 지워지지 않음 */
|
|
393
|
+
#record(res, answer) {
|
|
394
|
+
const submissions = this.#store.get('submissions', []);
|
|
395
|
+
submissions.unshift(this.#submission(answer, res, 'mock'));
|
|
396
|
+
this.#store.set('submissions', submissions);
|
|
397
|
+
const prev = this.#store.get('result', null);
|
|
398
|
+
const score = res.score ?? prev?.score ?? null;
|
|
399
|
+
const completed = res.score === 100 || this.#grading?.type === 'none';
|
|
400
|
+
this.#store.set('result', {
|
|
401
|
+
score,
|
|
402
|
+
submitCount: (prev?.submitCount ?? 0) + 1,
|
|
403
|
+
completedAt: prev?.completedAt ?? (completed ? new Date().toISOString() : null),
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async #loadConfig() {
|
|
408
|
+
const loadJson =
|
|
409
|
+
this.#options.loadJson ?? ((url) => fetch(url).then((r) => (r.ok ? r.json() : null)));
|
|
410
|
+
// ecdk dev의 콘텐츠 주소를 직접 열었을 때: 설정 파일은 zip처럼 빠져 있으니 dev가 주는 로컬 채점 설정을 쓴다
|
|
411
|
+
const devGrading = globalThis.__ECDK_DEV__?.grading;
|
|
412
|
+
if (typeof devGrading === 'string') return loadJson(devGrading).catch(() => null);
|
|
413
|
+
// 프로젝트 폴더를 그대로 열면 elice.config.json · grading.json이 있다 (zip에서는 빠짐). 로컬 채점용으로 일부러 읽는다.
|
|
414
|
+
// 지원 유형은 elice.config.json gradingTypes, 흉내 낼 유형 · 정답은 grading.json (유형이 없으면 지원 유형의 첫 번째)
|
|
415
|
+
// ecdk-ignore-next-line project.answer-import
|
|
416
|
+
const config = await loadJson('elice.config.json').catch(() => null);
|
|
417
|
+
const supported = Array.isArray(config?.gradingTypes) ? config.gradingTypes : [];
|
|
418
|
+
if (supported.length === 0) return null;
|
|
419
|
+
// ecdk-ignore-next-line project.answer-import
|
|
420
|
+
const data = await loadJson('grading.json').catch(() => null);
|
|
421
|
+
const grading = data && typeof data === 'object' ? data : {};
|
|
422
|
+
return { ...grading, type: supported.includes(grading.type) ? grading.type : supported[0] };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async #delay() {
|
|
426
|
+
const ms = this.#options.delayMs ?? (this.#scenario === 'slow' ? 1500 : 0);
|
|
427
|
+
if (ms > 0) await sleep(ms);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/* @eliceio/cdk 1.0.0-alpha.1 — UMD. Copied at build time by scripts/copy-cdk.mjs; do not edit. */
|
|
2
|
+
// ecdk-ignore-next-line api.parent-access sec.postmessage-wildcard
|
|
3
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).elice=e.elice||{})}(this,function(e){"use strict";function t(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function n(e,t,n,i,s){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?s.call(e,n):s?s.value=n:t.set(e,n),n}"function"==typeof SuppressedError&&SuppressedError;var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},s={exports:{}};!function(e){!function(t){var n=function(e,t,i){if(!c(t)||l(t)||d(t)||h(t)||a(t))return t;var s,r=0,o=0;if(u(t))for(s=[],o=t.length;r<o;r++)s.push(n(e,t[r],i));else for(var f in s={},t)Object.prototype.hasOwnProperty.call(t,f)&&(s[e(f,i)]=n(e,t[f],i));return s},i=function(e){return f(e)?e:(e=e.replace(/[\-_\s]+(.)?/g,function(e,t){return t?t.toUpperCase():""})).substr(0,1).toLowerCase()+e.substr(1)},s=function(e){var t=i(e);return t.substr(0,1).toUpperCase()+t.substr(1)},r=function(e,t){return function(e,t){var n=(t=t||{}).separator||"_",i=t.split||/(?=[A-Z])/;return e.split(i).join(n)}(e,t).toLowerCase()},o=Object.prototype.toString,a=function(e){return"function"==typeof e},c=function(e){return e===Object(e)},u=function(e){return"[object Array]"==o.call(e)},l=function(e){return"[object Date]"==o.call(e)},d=function(e){return"[object RegExp]"==o.call(e)},h=function(e){return"[object Boolean]"==o.call(e)},f=function(e){return(e-=0)==e},p=function(e,t){var n=t&&"process"in t?t.process:t;return"function"!=typeof n?e:function(t,i){return n(t,e,i)}},m={camelize:i,decamelize:r,pascalize:s,depascalize:r,camelizeKeys:function(e,t){return n(p(i,t),e)},decamelizeKeys:function(e,t){return n(p(r,t),e,t)},pascalizeKeys:function(e,t){return n(p(s,t),e)},depascalizeKeys:function(){return this.decamelizeKeys.apply(this,arguments)}};e.exports?e.exports=m:t.humps=m}(i)}(s);var r=s.exports;const o=e=>r.camelizeKeys(e,(e,t)=>/^\w{2}-\w{2,3}$/.test(e)?e:t(e)),a="http://localhost".replace(/\/+$/,"");class c{constructor(e={}){this.configuration=e}set config(e){this.configuration=e}get basePath(){return null!=this.configuration.basePath?this.configuration.basePath:a}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||p}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const e=this.configuration.apiKey;if(e)return"function"==typeof e?e:()=>e}get accessToken(){const e=this.configuration.accessToken;if(e)return"function"==typeof e?e:async()=>e}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}}const u=new c;class l{constructor(e=u){this.configuration=e,this.fetchApi=async(e,t)=>{let n,i={url:e,init:t};for(const e of this.middleware)e.pre&&(i=await e.pre(Object.assign({fetch:this.fetchApi},i))||i);try{n=await(this.configuration.fetchApi||fetch)(i.url,i.init)}catch(e){for(const t of this.middleware)t.onError&&(n=await t.onError({fetch:this.fetchApi,url:i.url,init:i.init,error:e,response:n?n.clone():void 0})||n);if(void 0===n)throw e}for(const e of this.middleware)e.post&&(n=await e.post({fetch:this.fetchApi,url:i.url,init:i.init,response:n.clone()})||n);return n},this.middleware=e.middleware}withMiddleware(...e){const t=this.clone();return t.middleware=t.middleware.concat(...e),t}withPreMiddleware(...e){const t=e.map(e=>({pre:e}));return this.withMiddleware(...t)}withPostMiddleware(...e){const t=e.map(e=>({post:e}));return this.withMiddleware(...t)}async request(e,t){const{url:n,init:i}=await this.createFetchParams(e,t),s=await this.fetchApi(n,i);if(s&&s.status>=200&&s.status<300)return s;const r=await s.json().then(e=>o(e)).catch(()=>({}));throw new h(Object.assign(Object.assign({},function(e){var t,n,i;const s=null===(t=null==e?void 0:e.meta)||void 0===t?void 0:t.error;if(s)return{code:s.code,message:s.message,detail:null!==(n=s.details)&&void 0!==n?n:[]};return{code:null==e?void 0:e.code,message:null==e?void 0:e.message,detail:null!==(i=null==e?void 0:e.detail)&&void 0!==i?i:e}}(r)),{status:s.status}))}async createFetchParams(e,t){let n=this.configuration.basePath+e.path;void 0!==e.query&&0!==Object.keys(e.query).length&&(n+="?"+this.configuration.queryParamsStringify(e.query));const i=Object.assign({},this.configuration.headers,e.headers);Object.keys(i).forEach(e=>void 0===i[e]?delete i[e]:{});const s="function"==typeof t?t:async()=>t,o={method:e.method,headers:i,body:e.body,credentials:this.configuration.credentials},a=Object.assign(Object.assign({},o),await s({init:o,context:e}));var c,u;return{url:n,init:Object.assign(Object.assign({},a),{body:(u=a.body,"undefined"!=typeof FormData&&u instanceof FormData||a.body instanceof URLSearchParams||d(a.body)?a.body:JSON.stringify((c=a.body,r.decamelizeKeys(c,(e,t)=>/^\w{2}-\w{2,3}$/.test(e)?e:t(e)))))})}}clone(){const e=new(0,this.constructor)(this.configuration);return e.middleware=this.middleware.slice(),e}}function d(e){return"undefined"!=typeof Blob&&e instanceof Blob}class h extends Error{constructor(e){super(`[${e.code||"unknown"}] ${e.message||"N/A"}`),this.cause=e,this.name="EliceResponseError"}}class f extends Error{constructor(e,t){super(t),this.field=e,this.name="RequiredError"}}function p(e,t=""){return Object.keys(e).map(n=>m(n,e[n],t)).filter(e=>e.length>0).join("&")}function m(e,t,n=""){const i=n+(n.length?`[${e}]`:e);if(t instanceof Array){const e=t.map(e=>encodeURIComponent(String(e))).join(`&${encodeURIComponent(i)}=`);return`${encodeURIComponent(i)}=${e}`}if(t instanceof Set){return m(e,Array.from(t),n)}return t instanceof Date?`${encodeURIComponent(i)}=${encodeURIComponent(t.toISOString())}`:t instanceof Object?p(t,i):`${encodeURIComponent(i)}=${encodeURIComponent(String(t))}`}class w{constructor(e,t=e=>e){this.raw=e,this.transformer=t}async value(){return o(this.transformer(await this.raw.json()))}}async function g(e){const{data:t}=await e.value();return t}function v(e,t=""){return`/materials/{material_id}${t}`.replace("{material_id}",encodeURIComponent(String(e)))}class y extends l{async withBearer(e={}){if(this.configuration&&this.configuration.accessToken){const t=this.configuration.accessToken,n=await t("HTTPBearer",[]);n&&(e.Authorization=`Bearer ${n}`)}return e}async authTokenRefreshRaw(e){const t=await this.request({path:"/auth/token/refresh",method:"POST",headers:await this.withBearer(),query:{}},e);return new w(t)}async authTokenRefresh(e){return g(await this.authTokenRefreshRaw(e))}async materialGetRaw(e,t){const n=await this.request({path:v(e.materialId),method:"GET",headers:await this.withBearer(),query:{}},t);return new w(n)}async materialGet(e,t){return g(await this.materialGetRaw(e,t))}async materialMeGetRaw(e,t){const n=await this.request({path:v(e.materialId,"/me"),method:"GET",headers:await this.withBearer(),query:{}},t);return new w(n)}async materialMeGet(e,t){return g(await this.materialMeGetRaw(e,t))}async submissionCreateRaw(e,t){if(null===e.submissionCreateRequest||void 0===e.submissionCreateRequest)throw new f("submissionCreateRequest","Required parameter requestParameters.submissionCreateRequest was null or undefined when calling submissionCreate.");const n={"Content-Type":"application/json"},i=await this.request({path:v(e.materialId,"/submissions"),method:"POST",headers:await this.withBearer(n),query:{},body:e.submissionCreateRequest},t);return new w(i)}async submissionCreate(e,t){return g(await this.submissionCreateRaw(e,t))}async submissionMeListRaw(e,t){const n={};void 0!==e.offset&&(n.offset=e.offset),void 0!==e.limit&&(n.limit=e.limit);const i=await this.request({path:v(e.materialId,"/submissions/me"),method:"GET",headers:await this.withBearer(),query:n},t);return new w(i)}async submissionMeList(e,t){return g(await this.submissionMeListRaw(e,t))}}var b;const _="preview";class z{constructor(e="learn",t="instructor",n={}){this.scope=e,this.viewer=t,this.settings=n,b.set(this,[])}async authTokenRefresh(){return{accessToken:"",expiresAt:new Date(Date.now()+72e5).toISOString()}}async materialGet(e){return{id:e.materialId,lecturePageId:0,courseId:0,description:{type:"text",text:""},currentVersion:{id:_,contentUrls:{},metadata:{entries:{}},fileTree:[],settings:this.settings}}}async materialMeGet(e){return{scope:this.scope,viewer:this.viewer,user:{anonymousId:"preview",fullname:null},result:null}}async submissionCreate(e){const n={isCorrect:!0,score:100};return t(this,b,"f").unshift(Object.assign({id:`preview-${t(this,b,"f").length+1}`,materialVersionId:_,accountId:0,createdAt:(new Date).toISOString(),answer:e.submissionCreateRequest.answer},n)),n}async submissionMeList(e){const{offset:n=0,limit:i=20}=e;return t(this,b,"f").slice(n,n+i)}}b=new WeakMap;function P(e,t){return"bigint"==typeof t?t.toString():t}class k{constructor(e){this._getter=e,this._value=void 0}get value(){const e=this._getter;return void 0!==e&&(this._value=e(),this._getter=void 0),this._value}}function O(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}const E="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function S(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function T(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function I(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function C(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function R(e){return"string"==typeof e?e:e?.message}function M(e,t,n){var i;for(let s=t;s<e.length;s++)(i=e[s]).schema??(i.schema=n)}function x(e,t,n){var i;const s=e.inst?._zod?.traits;s?.has("$ZodType")&&(s.has("$ZodCheck")?(i=e).schema??(i.schema=e.inst):e.schema=e.inst);const r=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,o=e.message?e.message:R(e.inst?._zod.def?.error?.(e))??R(r?.(e))??R(t?.error?.(e))??R(n.customError?.(e))??R(n.localeError?.(e))??"Invalid input",a={};for(const t of Object.keys(e))"inst"!==t&&"schema"!==t&&"continue"!==t&&"input"!==t&&"__proto__"!==t&&(a[t]=e[t]);return a.path??(a.path=[]),a.message=o,t?.reportInput&&(a.input=e.input),a}function $(e,t,n,i=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:i,value:n}),n}function A(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return null==this?n:$(this,t,n.bind(this))},set(e){$(this,t,e)}})}let N,L=!1;const q={configurable:!0,get(){L=!0}};function U(e,t,n){const i=Object.getPrototypeOf(e._zod);t in i&&N!==e._zod?N=void 0:(N=e._zod,Object.defineProperty(i,t,{configurable:!0,get(){Object.defineProperty(this,t,q);const e=L;L=!1;try{const i=n(this);return L?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i}),L=L||e,i}catch(n){throw delete this[t],L=L||e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function D(e,t,n,i){const s=function(e,t){const n=Object.getPrototypeOf(e);return t in n?void 0:n}(e,t);s&&Object.defineProperty(s,t,{configurable:!0,get(){const e={configurable:!0,writable:!0,enumerable:i,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:i,value:e})}})}var W;const Z={value:void 0,enumerable:!1};let K="captureStackTrace"in Error?Error:null;function G(e,t,n,i){function s(e){this.def=e,this.constr=l,this.traits=new Set}s.prototype={};const r=n,o=r&&new WeakSet;function a(n,i){if(n._zod){if(n._zod.traits.has(e))return}else{Z.value=new s(i);try{Object.defineProperty(n,"_zod",Z)}finally{Z.value=void 0}}if(n._zod.traits.add(e),t(n,i),o){const e=Object.getPrototypeOf(n),t=n._zod.constr.prototype;let i=e;for(;i&&i!==t;)i=Object.getPrototypeOf(i);const s=i??e;o.has(s)||(o.add(s),function(e,t){for(const n in t){const i=Object.getOwnPropertyDescriptor(t,n);i.get?Object.defineProperty(e,n,{...i,enumerable:!1}):A(e,n,i.value)}}(s,r))}const a=l.prototype;for(const e in a)Object.prototype.hasOwnProperty.call(a,e)&&(e in n||(n[e]=a[e].bind(n)))}const c=i?.Parent??Object;class u extends c{}function l(e){const t=i?.Parent?function(e){const t=K;if(t){const n=t.stackTraceLimit;if("number"==typeof n){try{t.stackTraceLimit=0}catch{return K=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}(u):this;a(t,e);const n=t._zod.deferred;if(n){for(const e of n)e();t._zod.deferred=void 0}const s=globalThis.__zod_globalConfig?.postProcessor;return s&&s(t),t}return Object.defineProperty(u,"name",{value:e}),Object.defineProperty(l,"init",{value:a}),Object.defineProperty(l,Symbol.hasInstance,{value:t=>!!(i?.Parent&&t instanceof i.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(l,"name",{value:e}),l}class F extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(W=globalThis).__zod_globalConfig??(W.__zod_globalConfig={});const B=globalThis.__zod_globalConfig;function V(e){return B}const J={get:function(){const e=this._zod;return e.message??(e.message=JSON.stringify(e.def,P,2)),e.message},set:function(e){this._zod.message=e},enumerable:!0,configurable:!0},H={value:void 0,enumerable:!1},Y=new WeakSet([Object.prototype,Error.prototype]),X=G("$ZodError",(e,t)=>{e.name="$ZodError",H.value=t,Object.defineProperty(e,"issues",H),H.value=void 0,Object.defineProperty(e,"message",J);const n=Object.getPrototypeOf(e);Y.has(n)||(Y.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){const e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},void 0,{Parent:Error}),Q=(e=>{const t=(n,i,s,r)=>{const o=s?{...s,async:!1}:{async:!1},a=n._zod.run({value:i,issues:[]},o);if(a instanceof Promise)throw new F;if(a.issues.length){const n=new(r?.Err??e)(a.issues.map(e=>x(e,o,V())));throw E(n,r?.callee??t),n}return a.value};return t})(X),ee=e=>{const t=async(n,i,s,r)=>{const o=s?{...s,async:!0}:{async:!0};let a=n._zod.run({value:i,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const n=new(r?.Err??e)(a.issues.map(e=>x(e,o,V())));throw E(n,r?.callee??t),n}return a.value};return t},te=ee(X),ne=(e=>(t,n,i)=>{const s=i?{...i,async:!1}:{async:!1},r=t._zod.run({value:n,issues:[]},s);if(r instanceof Promise)throw new F;return r.issues.length?ie(e,r.issues,s):{success:!0,data:r.value}})(X);function ie(e,t,n){let i;return{success:!1,get error(){return i||(i=new e(t.map(e=>x(e,n,V()))),t=void 0,n=void 0),i},set error(e){i=e,t=void 0,n=void 0}}}const se=(e=>async(t,n,i)=>{const s=i?{...i,async:!0}:{async:!0};let r=t._zod.run({value:n,issues:[]},s);return r instanceof Promise&&(r=await r),r.issues.length?ie(e,r.issues,s):{success:!0,data:r.value}})(X),re=/^[\s\S]{0,}$/,oe=G("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ae=G("$ZodCheckStringFormat",(e,t)=>{var n,i;oe.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),ce={major:4,minor:6,patch:7},ue=G("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ce;const i=e._zod.def.checks,s=e._zod.traits.has("$ZodCheck")?[e,...i??[]]:i?.length?[...i]:[];for(const t of s)for(const n of t._zod.onattach)n(e);if(0===s.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(t,n,i)=>{if(t.memo)return t;let s,r=I(t);for(const o of n){if(o._zod.def.when){if(C(t))continue;if(!o._zod.def.when(t))continue}else if(r)continue;const n=t.issues.length,a=o._zod.check(t);if(a instanceof Promise&&!1===i?.async)throw new F;if(s||a instanceof Promise)s=(s??Promise.resolve()).then(async()=>{await a;t.issues.length!==n&&(M(t.issues,n,e),r||(r=I(t,n)))});else{if(t.issues.length===n)continue;M(t.issues,n,e),r||(r=I(t,n))}}return s?s.then(()=>t):t},n=(n,i,r)=>{if(I(n))return n.aborted=!0,n;const o=t(i,s,r);if(o instanceof Promise){if(!1===r.async)throw new F;return o.then(t=>e._zod.parse(t,r))}return e._zod.parse(o,r)};e._zod.run=(i,r)=>{if(r.skipChecks)return e._zod.parse(i,r);if("backward"===r.direction){const t=e._zod.parse({value:i.value,issues:[]},{...r,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,r)):n(t,i,r)}const o=e._zod.parse(i,r);if(o instanceof Promise){if(!1===r.async)throw new F;return o.then(e=>t(e,s,r))}return t(o,s,r)}}},{get"~standard"(){return function(e,t,n){return $(e,t,n,!1)}(this,"~standard",(e=this,{validate:t=>{const n={async:!1};try{const i=e._zod.run({value:t,issues:[]},n);if(!(i instanceof Promise))return le(i,n)}catch(e){}return async function(e,t){const n={async:!0};return le(await e._zod.run({value:t,issues:[]},n),n)}(e,t)},vendor:"zod",version:1}));var e},set"~standard"(e){$(this,"~standard",e)}}),le=(e,t)=>e.issues.length?{issues:e.issues.map(e=>x(e,t,V()))}:{value:e.value};const de=G("$ZodString",(e,t)=>{ue.init(e,t),e._zod.pattern=t.pattern??re,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),he=G("$ZodStringFormat",(e,t)=>{ae.init(e,t),de.init(e,t)});const fe=G("$ZodJWT",(e,t)=>{he.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[i]=n;if(!i)return!1;const s=JSON.parse(atob(i));return!("typ"in s&&"JWT"!==s?.typ||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});function pe(e,t,n,i,s,r){const o=n in i,a="optional"===r;if(o||!a||"optional"!==s){if(e.issues.length){if(void 0!==s&&a&&!o)return;t.issues.push(...(c=n,u=e.issues,u.map(e=>{var t;return(t=e).path??(t.path=[]),e.path.unshift(c),e})))}var c,u;o||void 0!==s?void 0===e.value?(o||"defaulted"===s&&!a)&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}}const me=[];function we(e){const t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),i=n.length?n:me,s=i.length?[...t,...i]:t;for(const t of s)if(!e.shape?.[t]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(t)}": expected a Zod schema`);const r=(o=e.shape,Object.keys(o).filter(e=>void 0!==o[e]._zod.optin&&"optional"===o[e]._zod.optout));var o;return{...e,allKeys:s,symbolKeys:i,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}const ge=G("$ZodObject",(e,t)=>{ue.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape"),i=n?.get?n.get.raw:t.shape??{};if(i){const e=()=>{const n={...i};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=i,Object.defineProperty(t,"shape",{get:e})}const s=new k(()=>we(t));U(e,"propValues",e=>{const t=e.def.shape,n={};for(const e in t){const i=t[e]._zod;if(i.values){Object.prototype.hasOwnProperty.call(n,e)||O(n,e,new Set);for(const t of i.values)n[e].add(t);void 0!==i.optin&&n[e].add(void 0)}}return n});const r=S,o=t.catchall;let a;const c=B.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{a??(a=s.value);const i=t.value;if(!r(i))return t.issues.push({expected:"object",code:"invalid_type",input:i,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};const u=[],l=a.shape,d=n?.abortEarly;let h=t.issues.length;for(const e of a.allKeys){if(d&&t.issues.length!==h){if(I(t,h))break;h=t.issues.length}if("__proto__"===e)continue;const s=l[e],r=s._zod.optin,o=s._zod.optout,a=s._zod.run({value:i[e],issues:[]},n);a instanceof Promise?u.push(a.then(n=>pe(n,t,e,i,r,o))):pe(a,t,e,i,r,o)}return o?function(e,t,n,i,s,r,o){const a=[],c=s.keySet,u=s.catchall._zod,l=u.def.type,d=u.optin,h=u.optout;let f=0;for(const s in t){if(o&&n.issues.length!==f){if(I(n,f))break;f=n.issues.length}if(c.has(s))continue;if("__proto__"===s){"never"===l&&a.push(s);continue}if("never"===l){a.push(s);continue}const r=u.run({value:t[s],issues:[]},i);r instanceof Promise?e.push(r.then(e=>pe(e,n,s,t,d,h))):pe(r,n,s,t,d,h)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:r,continue:!0}),e.length?Promise.all(e).then(()=>n):n}(u,i,t,n,s.value,e,!0===d):u.length?Promise.all(u).then(()=>t):t}}),ve=G("$ZodLiteral",(e,t)=>{ue.init(e,t);const n=new Set(t.values);e._zod.values=n,U(e,"pattern",e=>{const t=e.def.values;return new RegExp(t.length?`^(${t.map(e=>"string"==typeof e?T(e):e?T(e.toString()):String(e)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(i,s)=>{const r=i.value;return n.has(r)||i.issues.push({code:"invalid_value",values:t.values,input:r,inst:e}),i}});function ye(e,t){return e.value=t.issues.length?void 0:t.value,e}const be=G("$ZodOptional",(e,t)=>{ue.init(e,t),U(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),e._zod.optout="optional",U(e,"values",e=>{const t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),U(e,"pattern",e=>{const t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${function(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(void 0===e.value){if("defaulted"!==t.innerType._zod.optin)return e;const i=t.innerType._zod.run({value:e.value,issues:[]},n);return i instanceof Promise?i.then(t=>ye(e,t)):ye(e,i)}return t.innerType._zod.run(e,n)}}),_e=G("$ZodCustom",(e,t)=>{oe.init(e,t),ue.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const i=n.value,s=t.fn(i);if(s instanceof Promise)return s.then(t=>ze(t,n,i,e));ze(s,n,i,e)}});function ze(e,t,n,i){if(!e){const e={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(e.params=i._zod.def.params),t.issues.push(function(...e){const[t,n,i]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:i}:{...t}}(e))}}const Pe=G("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");ue.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){$(this,"with",e)},parse(e,t){return Q(this,e,t,{callee:this.parse})},parseAsync(e,t){return te(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return ne(this,e,t)},safeParseAsync(e,t){return se(this,e,t)},check(...e){const t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return function(e,t,n){const i=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(i._zod.parent=e),i}(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return 0===t.length?e(this):e(this,...t)}}),ke=G("ZodMiniString",(e,t)=>{de.init(e,t),Pe.init(e,t)}),Oe=G("ZodMiniStringFormat",(e,t)=>{he.init(e,t),ke.init(e,t)}),Ee=G("ZodMiniJWT",(e,t)=>{fe.init(e,t),Oe.init(e,t)});const Se=G("ZodMiniObject",(e,t)=>{ge.init(e,t),Pe.init(e,t),D(e,"shape",e=>e._zod.def.shape,!1)});const Te=G("ZodMiniLiteral",(e,t)=>{ve.init(e,t),Pe.init(e,t)});function je(e,t){return new Te({type:"literal",values:Array.isArray(e)?e:[e],...j(t)})}const Ie=G("ZodMiniOptional",(e,t)=>{be.init(e,t),Pe.init(e,t)});function Ce(e){return new Ie({type:"optional",innerType:e})}const Re=G("ZodMiniCustom",(e,t)=>{_e.init(e,t),Pe.init(e,t)});const Me=function(e,t){const n={type:"object",shape:e??{},...j(t)};return new Se(n)}({token:Ce((xe="access token(`token`) is not a JWT",function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...j(t)})}(Ee,xe))),preview:Ce(je("1")),edit:Ce(je("1"))}).check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...j(n)})}(Re,e,t)}(e=>null!=e.token||"1"===e.preview||"1"===e.edit,{message:"access token(`token`) is not provided"}));var xe;const $e=/\/materials\/([0-9a-f-]{36})\//i;var Ae;e.ErrorCode=void 0,(Ae=e.ErrorCode||(e.ErrorCode={})).Init="init",Ae.InvalidParam="invalid_param",Ae.InvalidToken="invalid_token",Ae.NotInitialized="not_initialized",Ae.Unauthorized="unauthorized",Ae.SessionExpired="session_expired",Ae.PermissionDenied="permission_denied",Ae.ReadOnlyMode="read_only_mode",Ae.ScreenNotSupported="screen_not_supported",Ae.ContentNotReady="content_not_ready",Ae.InvalidInput="invalid_input",Ae.RateLimited="rate_limited",Ae.ExternalServiceError="external_service_error",Ae.NavigationTimeout="navigation_timeout",Ae.RequestFailed="request_failed";const Ne=Object.assign(class e extends Error{constructor(t,n,i){var s;const r=i?i instanceof Error?i:new Error(i):void 0;super(`[@eliceio/cdk] ${t} - ${n}${r?`\n${null!==(s=r.stack)&&void 0!==s?s:""}`:""}`),this.code=t,this.cause=r,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}},{code:e.ErrorCode}),Le="undefined"==typeof window,qe="eliceio-content-sdk";function Ue(){if(Le||window.parent===window)return null;const e=window.parent;return{post(t){e.postMessage(t,"*")},subscribe(t){function n(n){n.source===e&&function(e){if("object"!=typeof e||null===e)return!1;const{source:t,type:n}=e;return t===qe&&"string"==typeof n}(n.data)&&t(n.data)}return window.addEventListener("message",n),()=>{window.removeEventListener("message",n)}}}}function De(e){let t="";return t=(e=>{try{let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";return decodeURIComponent((e=>e.split("").map(e=>{let t=e.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t=`0${t}`),`%${t}`}).join(""))(atob(t)))}catch(e){throw new Ne(Ne.code.InvalidToken,"Fail to decode base64 format.",e)}})(e.split(".")[1]),t=(e=>{try{return JSON.parse(e)}catch(e){throw new Ne(Ne.code.InvalidToken,"Fail to parse JSON format.",e)}})(t),o(t)}var We,Ze,Ke;const Ge=Object.freeze({previous:"navigate-prev",next:"navigate-next",navigate:"navigate",stateSync:"navigate-state-sync"}),Fe="navigate-state";class Be{constructor(e){We.add(this),this.ctx=e}async getHasPrevious(){return(await t(this,We,"m",Ke).call(this)).hasPreviousLecturePage}async getHasNext(){return(await t(this,We,"m",Ke).call(this)).hasNextLecturePage}previous(){t(this,We,"m",Ze).call(this,Ge.previous)}next(){t(this,We,"m",Ze).call(this,Ge.next)}navigate(e){t(this,We,"m",Ze).call(this,Ge.navigate,{lecturePageId:e})}}var Ve,Je,He,Ye,Xe,Qe,et,tt,nt,it,st,rt,ot,at,ct,ut,lt,dt,ht,ft,pt,mt,wt,gt,vt,yt,bt,_t,zt;We=new WeakSet,Ze=function(e,t,n){const i=this.ctx.assertNavigable();if(this.ctx.isDraft()||null==this.ctx.channel)return!1;const s={source:qe,type:e,materialId:i};return void 0!==t&&(s.payload=t),void 0!==n&&(s.requestId=n),this.ctx.channel.post(s),!0},Ke=function(){var e;const n="undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,i=this.ctx.channel,s=null!==(e=this.ctx.stateTimeoutMs)&&void 0!==e?e:1e3;return new Promise((e,r)=>{let o=()=>{},a=null;const c=()=>{o(),null!==a&&clearTimeout(a)};let u;null!=i&&(o=i.subscribe(t=>{var i;if(t.type!==Fe||t.requestId!==n)return;c();const s=null!==(i=t.payload)&&void 0!==i?i:{};e({hasPreviousLecturePage:!0===s.hasPreviousLecturePage,hasNextLecturePage:!0===s.hasNextLecturePage})}));try{u=t(this,We,"m",Ze).call(this,Ge.stateSync,void 0,n)}catch(e){return c(),void r(e)}if(!u)return c(),void e({hasPreviousLecturePage:!1,hasNextLecturePage:!1});a=setTimeout(()=>{c(),r(new Ne(Ne.code.NavigationTimeout,"The learning page did not answer the navigation state request."))},s)})};const Pt=Object.freeze({AUTH_PERMISSION_DENIED:e.ErrorCode.PermissionDenied,AUTHENTICATION_INVALID:e.ErrorCode.Unauthorized,EXTERNAL_SERVICE_ERROR:e.ErrorCode.ExternalServiceError,INVALID_INPUT:e.ErrorCode.InvalidInput,MATERIAL_CONTENT_NOT_READY:e.ErrorCode.ContentNotReady,MATERIAL_READ_ONLY_MODE:e.ErrorCode.ReadOnlyMode,MATERIAL_TOO_MANY_SUBMISSIONS:e.ErrorCode.RateLimited});function kt(e,t){var n,i,s;if(e instanceof h){const r=null!==(i=Pt[null!==(n=e.cause.code)&&void 0!==n?n:""])&&void 0!==i?i:Ne.code.RequestFailed;return new Ne(r,null!==(s=e.cause.message)&&void 0!==s?s:t,e)}return new Ne(Ne.code.RequestFailed,t,e)}function Ot(e){return e instanceof h&&401===e.cause.status}Je=new WeakMap,He=new WeakMap,Ye=new WeakMap,Xe=new WeakMap,Qe=new WeakMap,et=new WeakMap,tt=new WeakMap,nt=new WeakMap,it=new WeakMap,st=new WeakMap,rt=new WeakMap,ot=new WeakMap,at=new WeakMap,ct=new WeakMap,ut=new WeakMap,lt=new WeakMap,Ve=new WeakSet,dt=function(){if(!this.initialized||!t(this,st,"f"))throw new Ne(Ne.code.NotInitialized,"The SDK is not initialized. Please call the init function first.");if(t(this,Qe,"f"))throw new Ne(Ne.code.SessionExpired,"The session has expired. Please reload the material.");return t(this,st,"f").materialId},ht=function(...e){if(null==t(this,nt,"f")||!e.includes(t(this,nt,"f")))throw new Ne(Ne.code.ScreenNotSupported,`This call is only available on the ${e.join(" or ")} screen.`)},ft=function(){var e,n,i;if(t(this,at,"f"))return{materials:new z(null!==(e=t(this,et,"f"))&&void 0!==e?e:"learn","instructor")};const s=new c({basePath:null!==(i=null===(n=this.options)||void 0===n?void 0:n.baseUrl)&&void 0!==i?i:"https://api-material.elice.io",accessToken:()=>{var e;return null!==(e=t(this,He,"f"))&&void 0!==e?e:""}});return{materials:new y(s)}},pt=async function(e){const i=null!=e?e:Le?"":window.location.hash,s=/(^|[#&])(token|preview|edit)=/.test(i);if(void 0===e&&!s&&t(this,ct,"f"))return t(this,ct,"f");const r=new URLSearchParams(i.replace(/^#/,"")),{data:o,error:a}=await Me.safeParseAsync(Object.fromEntries(r.entries()));if(a)throw new AggregateError(a.issues.map(e=>new Ne(Ne.code.InvalidParam,e.message)),"Failed to resolve fragment params during initialization.");return n(this,ct,o,"f"),o},mt=function(){if(Le||!window.location.hash.includes("token="))return;const e=new URLSearchParams(window.location.hash.replace(/^#/,""));e.delete("token");const t=e.toString(),{pathname:n,search:i}=window.location;window.history.replaceState(window.history.state,"",`${n}${i}${t?`#${t}`:""}`)},wt=function(e,i){var s,r,o,a,c,u;n(this,at,null==e.token,"f"),n(this,Qe,!1,"f"),t(this,Ve,"m",vt).call(this,null!==(s=e.token)&&void 0!==s?s:null);const l=t(this,He,"f")?De(t(this,He,"f")):null,d=null!==(o=null!==(r=function(e){const t=$e.exec(e);return t?t[1].toLowerCase():null}(null!=i?i:Le?"":window.location.pathname))&&void 0!==r?r:null==l?void 0:l.materialId)&&void 0!==o?o:null;if(null==d)throw new Ne(Ne.code.InvalidParam,"The material id is not found in the content URL or the access token.");return n(this,st,{materialId:d,lecturePageId:null!==(a=null==l?void 0:l.lecturePageId)&&void 0!==a?a:null,courseId:null!==(c=null==l?void 0:l.courseId)&&void 0!==c?c:null},"f"),n(this,ot,null!==(u=null==l?void 0:l.locale)&&void 0!==u?u:"ko","f"),t(this,at,"f")&&(n(this,et,"1"===e.edit?"edit":"learn","f"),n(this,nt,"1"===e.edit?"edit":"learn","f")),d},gt=async function(e){const[i,s]=await Promise.all([this.internal_apis.materials.materialGet({materialId:e}),this.internal_apis.materials.materialMeGet({materialId:e})]);var r,o,a;n(this,rt,{description:i.description,entries:i.currentVersion.metadata.entries,settings:i.currentVersion.settings},"f"),n(this,Je,s.user,"f"),n(this,it,s.result,"f"),n(this,tt,s.viewer,"f"),t(this,at,"f")||(n(this,et,s.scope,"f"),n(this,nt,(r=s.scope,o=s.viewer,a=t(this,rt,"f").entries,"edit"===r?"edit":"instructor"===o&&a.instructor?"instructor":"learn"),"f"))},vt=function(e){var t;n(this,He,e,"f");const i=e?null===(t=De(e))||void 0===t?void 0:t.exp:void 0;n(this,Ye,i?1e3*i:null,"f")},yt=function(e){if(t(this,Ve,"m",bt).call(this),t(this,at,"f")||null==t(this,Ye,"f")||Le)return;const i=null!=e?e:Math.max(0,t(this,Ye,"f")-3e5-Date.now());n(this,Xe,setTimeout(()=>{t(this,Ve,"m",_t).call(this)},i),"f")},bt=function(){null!=t(this,Xe,"f")&&(clearTimeout(t(this,Xe,"f")),n(this,Xe,null,"f"))},_t=async function(){try{const{accessToken:e}=await this.internal_apis.materials.authTokenRefresh();t(this,Ve,"m",vt).call(this,e),t(this,Ve,"m",yt).call(this)}catch(e){if(function(e){if(!Ot(e))return!1;const t=e.cause.detail;return Array.isArray(t)&&t.some(e=>{var t;return"session_expired"===(null===(t=null==e?void 0:e.ctx)||void 0===t?void 0:t.reason)})}(e)||Ot(e))return void t(this,Ve,"m",zt).call(this);t(this,Ve,"m",yt).call(this,3e4)}},zt=function(){var e,i;t(this,Ve,"m",bt).call(this),n(this,Qe,!0,"f"),null===(i=(e=this.options).onSessionExpired)||void 0===i||i.call(e)},e.EliceCDK=class{constructor(e={}){Ve.add(this),this.options=e,this.initialized=!1,Je.set(this,null),He.set(this,null),Ye.set(this,null),Xe.set(this,null),Qe.set(this,!1),et.set(this,null),tt.set(this,null),nt.set(this,null),it.set(this,null),st.set(this,null),rt.set(this,null),ot.set(this,"ko"),at.set(this,!1),ct.set(this,null),ut.set(this,void 0),lt.set(this,void 0),this.internal_apis=t(this,Ve,"m",ft).call(this),n(this,ut,Ue(),"f"),n(this,lt,new Be({channel:t(this,ut,"f"),isDraft:()=>t(this,at,"f"),assertNavigable:()=>{const e=t(this,Ve,"m",dt).call(this);return t(this,Ve,"m",ht).call(this,"learn","instructor"),e}}),"f")}get account(){return t(this,Je,"f")}get scope(){return t(this,et,"f")}get viewer(){return t(this,tt,"f")}get screen(){return t(this,nt,"f")}get result(){return t(this,it,"f")}get metadata(){return t(this,st,"f")}get material(){return t(this,rt,"f")}get locale(){return t(this,ot,"f")}get isDraft(){return t(this,at,"f")}get isSessionExpired(){return t(this,Qe,"f")}get navigation(){return t(this,lt,"f")}async init(e={}){this.initialized=!1,t(this,Ve,"m",bt).call(this);const n=await t(this,Ve,"m",pt).call(this,e.hash);void 0===e.hash&&t(this,Ve,"m",mt).call(this);try{const i=t(this,Ve,"m",wt).call(this,n,e.pathname);this.internal_apis=t(this,Ve,"m",ft).call(this),await t(this,Ve,"m",gt).call(this,i),this.initialized=!0,t(this,Ve,"m",yt).call(this)}catch(e){if(e instanceof Ne)throw e;throw kt(e,"Failed to initialize elice content sdk.")}return this}async submit(e){const n=t(this,Ve,"m",dt).call(this);t(this,Ve,"m",ht).call(this,"learn","instructor");try{return await this.internal_apis.materials.submissionCreate({materialId:n,submissionCreateRequest:{answer:e}})}catch(e){throw kt(e,"Failed to submit the answer.")}}async history(e={}){const n=t(this,Ve,"m",dt).call(this);try{return await this.internal_apis.materials.submissionMeList(Object.assign({materialId:n},e))}catch(e){throw kt(e,"Failed to load submissions.")}}saveSettings(e){var i;const s=t(this,Ve,"m",dt).call(this);t(this,Ve,"m",ht).call(this,"edit");const r={source:qe,type:"settings-change",materialId:s,payload:{settings:e}};t(this,rt,"f")&&n(this,rt,Object.assign(Object.assign({},t(this,rt,"f")),{settings:e}),"f"),null===(i=t(this,ut,"f"))||void 0===i||i.post(r)}dispose(){t(this,Ve,"m",bt).call(this)}},e.EliceCDKError=Ne,e.EliceCDKNavigation=Be,e.NAVIGATION_MESSAGE_TYPE=Ge,e.NAVIGATION_STATE_MESSAGE_TYPE=Fe});
|