@timeback/core 0.1.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.
- package/README.md +216 -0
- package/dist/client.d.ts +147 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/constants.d.ts +20 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +1053 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6932 -0
- package/dist/lib/broadcast-results.d.ts +20 -0
- package/dist/lib/broadcast-results.d.ts.map +1 -0
- package/dist/manager.d.ts +129 -0
- package/dist/manager.d.ts.map +1 -0
- package/dist/types/index.d.ts +233 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types.d.ts +10 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +56 -0
- package/dist/utils.d.ts +8 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +1541 -0
- package/package.json +44 -0
package/dist/utils.js
ADDED
|
@@ -0,0 +1,1541 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
8
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
9
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
10
|
+
for (let key of __getOwnPropNames(mod))
|
|
11
|
+
if (!__hasOwnProp.call(to, key))
|
|
12
|
+
__defProp(to, key, {
|
|
13
|
+
get: () => mod[key],
|
|
14
|
+
enumerable: true
|
|
15
|
+
});
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __export = (target, all) => {
|
|
19
|
+
for (var name in all)
|
|
20
|
+
__defProp(target, name, {
|
|
21
|
+
get: all[name],
|
|
22
|
+
enumerable: true,
|
|
23
|
+
configurable: true,
|
|
24
|
+
set: (newValue) => all[name] = () => newValue
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
28
|
+
|
|
29
|
+
// ../edubridge/dist/index.js
|
|
30
|
+
var DEFAULT_PLATFORM = "BEYOND_AI";
|
|
31
|
+
var BEYONDAI_TOKEN_URLS = {
|
|
32
|
+
staging: "https://staging-beyond-timeback-api-2-idp.auth.us-east-1.amazoncognito.com/oauth2/token",
|
|
33
|
+
production: "https://prod-beyond-timeback-api-2-idp.auth.us-east-1.amazoncognito.com/oauth2/token"
|
|
34
|
+
};
|
|
35
|
+
var BEYONDAI_API_URLS = {
|
|
36
|
+
staging: "https://api.staging.alpha-1edtech.ai",
|
|
37
|
+
production: "https://api.alpha-1edtech.ai"
|
|
38
|
+
};
|
|
39
|
+
var BEYONDAI_CALIPER_URLS = {
|
|
40
|
+
staging: "https://caliper.staging.alpha-1edtech.ai",
|
|
41
|
+
production: "https://caliper.alpha-1edtech.ai"
|
|
42
|
+
};
|
|
43
|
+
var BEYONDAI_QTI_URLS = {
|
|
44
|
+
staging: "https://qti.alpha-1edtech.ai/api",
|
|
45
|
+
production: "https://qti.alpha-1edtech.ai/api"
|
|
46
|
+
};
|
|
47
|
+
var LEARNWITHAI_TOKEN_URLS = {
|
|
48
|
+
staging: "https://platform.dev.timeback.com/auth/1.0/token",
|
|
49
|
+
production: "https://platform.timeback.com/auth/1.0/token"
|
|
50
|
+
};
|
|
51
|
+
var LEARNWITHAI_API_URLS = {
|
|
52
|
+
staging: "https://platform.dev.timeback.com",
|
|
53
|
+
production: "https://platform.timeback.com"
|
|
54
|
+
};
|
|
55
|
+
var LEARNWITHAI_CALIPER_URLS = {
|
|
56
|
+
staging: "https://platform.dev.timeback.com",
|
|
57
|
+
production: "https://platform.timeback.com"
|
|
58
|
+
};
|
|
59
|
+
var LEARNWITHAI_QTI_URLS = {
|
|
60
|
+
staging: "https://platform.dev.timeback.com",
|
|
61
|
+
production: "https://platform.timeback.com"
|
|
62
|
+
};
|
|
63
|
+
var PLATFORM_ENDPOINTS = {
|
|
64
|
+
BEYOND_AI: {
|
|
65
|
+
token: BEYONDAI_TOKEN_URLS,
|
|
66
|
+
api: BEYONDAI_API_URLS,
|
|
67
|
+
caliper: BEYONDAI_CALIPER_URLS,
|
|
68
|
+
qti: BEYONDAI_QTI_URLS
|
|
69
|
+
},
|
|
70
|
+
LEARNWITH_AI: {
|
|
71
|
+
token: LEARNWITHAI_TOKEN_URLS,
|
|
72
|
+
api: LEARNWITHAI_API_URLS,
|
|
73
|
+
caliper: LEARNWITHAI_CALIPER_URLS,
|
|
74
|
+
qti: LEARNWITHAI_QTI_URLS
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
var TypeScriptPackages = {
|
|
78
|
+
tsc: "tsc",
|
|
79
|
+
nativePreview: "@typescript/native-preview@7.0.0-dev.20251217.1"
|
|
80
|
+
};
|
|
81
|
+
var TYPESCRIPT_PACKAGE = TypeScriptPackages.nativePreview;
|
|
82
|
+
var patterns = null;
|
|
83
|
+
var debugAll = false;
|
|
84
|
+
var debugEnvSet = false;
|
|
85
|
+
function patternToRegex(pattern) {
|
|
86
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
87
|
+
const regexStr = escaped.replace(/\*/g, ".*");
|
|
88
|
+
return new RegExp(`^${regexStr}$`);
|
|
89
|
+
}
|
|
90
|
+
function parseDebugEnv() {
|
|
91
|
+
if (patterns !== null)
|
|
92
|
+
return;
|
|
93
|
+
patterns = [];
|
|
94
|
+
if (typeof process === "undefined" || !process.env?.DEBUG) {
|
|
95
|
+
debugEnvSet = false;
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
debugEnvSet = true;
|
|
99
|
+
const debugValue = process.env.DEBUG.trim();
|
|
100
|
+
if (debugValue === "1" || debugValue === "true" || debugValue === "*") {
|
|
101
|
+
debugAll = true;
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const parts = debugValue.split(",").map((p) => p.trim()).filter(Boolean);
|
|
105
|
+
for (const part of parts) {
|
|
106
|
+
if (part.startsWith("-")) {
|
|
107
|
+
patterns.push({
|
|
108
|
+
regex: patternToRegex(part.slice(1)),
|
|
109
|
+
exclude: true
|
|
110
|
+
});
|
|
111
|
+
} else {
|
|
112
|
+
patterns.push({
|
|
113
|
+
regex: patternToRegex(part),
|
|
114
|
+
exclude: false
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const hasInclude = patterns.some((p) => !p.exclude);
|
|
119
|
+
if (!hasInclude && patterns.length > 0) {
|
|
120
|
+
debugAll = true;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function shouldShowDebug(scope) {
|
|
124
|
+
parseDebugEnv();
|
|
125
|
+
if (!debugEnvSet) {
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
if (debugAll) {
|
|
129
|
+
if (scope) {
|
|
130
|
+
for (const pattern of patterns) {
|
|
131
|
+
if (pattern.exclude && pattern.regex.test(scope)) {
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
if (!scope) {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
for (const pattern of patterns) {
|
|
142
|
+
if (pattern.exclude && pattern.regex.test(scope)) {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
for (const pattern of patterns) {
|
|
147
|
+
if (!pattern.exclude && pattern.regex.test(scope)) {
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
function isBrowser() {
|
|
154
|
+
return typeof globalThis !== "undefined" && "window" in globalThis;
|
|
155
|
+
}
|
|
156
|
+
function detectEnvironment() {
|
|
157
|
+
if (isBrowser()) {
|
|
158
|
+
return "browser";
|
|
159
|
+
}
|
|
160
|
+
if (typeof process !== "undefined" && process.env) {
|
|
161
|
+
if (process.env["NODE_ENV"] === "test" || process.env["BUN_ENV"] === "test") {
|
|
162
|
+
return "test";
|
|
163
|
+
}
|
|
164
|
+
if (false) {}
|
|
165
|
+
if (process.env.CI || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI || process.env.CIRCLECI || process.env.JENKINS_URL || process.env.BUILDKITE) {
|
|
166
|
+
return "ci";
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return "terminal";
|
|
170
|
+
}
|
|
171
|
+
var nodeInspect;
|
|
172
|
+
if (!isBrowser()) {
|
|
173
|
+
try {
|
|
174
|
+
const util = await import("node:util");
|
|
175
|
+
nodeInspect = util.inspect;
|
|
176
|
+
} catch {}
|
|
177
|
+
}
|
|
178
|
+
var colors = {
|
|
179
|
+
reset: "\x1B[0m",
|
|
180
|
+
bold: "\x1B[1m",
|
|
181
|
+
dim: "\x1B[2m",
|
|
182
|
+
red: "\x1B[31m",
|
|
183
|
+
yellow: "\x1B[33m",
|
|
184
|
+
blue: "\x1B[34m",
|
|
185
|
+
cyan: "\x1B[36m"
|
|
186
|
+
};
|
|
187
|
+
function getLevelColor(level) {
|
|
188
|
+
switch (level) {
|
|
189
|
+
case "debug":
|
|
190
|
+
return colors.blue;
|
|
191
|
+
case "info":
|
|
192
|
+
return colors.cyan;
|
|
193
|
+
case "warn":
|
|
194
|
+
return colors.yellow;
|
|
195
|
+
case "error":
|
|
196
|
+
return colors.red;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function getConsoleMethod(level) {
|
|
200
|
+
switch (level) {
|
|
201
|
+
case "debug":
|
|
202
|
+
return console.debug;
|
|
203
|
+
case "info":
|
|
204
|
+
return console.info;
|
|
205
|
+
case "warn":
|
|
206
|
+
return console.warn;
|
|
207
|
+
case "error":
|
|
208
|
+
return console.error;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function formatContext(context) {
|
|
212
|
+
if (nodeInspect) {
|
|
213
|
+
return nodeInspect(context, {
|
|
214
|
+
depth: null,
|
|
215
|
+
colors: true,
|
|
216
|
+
breakLength: 80,
|
|
217
|
+
compact: false
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
return JSON.stringify(context, null, 2);
|
|
221
|
+
}
|
|
222
|
+
var terminalFormatter = (entry) => {
|
|
223
|
+
const levelColor = getLevelColor(entry.level);
|
|
224
|
+
const consoleMethod = getConsoleMethod(entry.level);
|
|
225
|
+
const levelUpper = entry.level.toUpperCase().padEnd(5);
|
|
226
|
+
const isoString = entry.timestamp.toISOString().replace(/\.\d{3}Z$/, "");
|
|
227
|
+
const timestamp = `${colors.dim}[${isoString}]${colors.reset}`;
|
|
228
|
+
const level = `${levelColor}${levelUpper}${colors.reset}`;
|
|
229
|
+
const scope = entry.scope ? `${colors.bold}[${entry.scope}]${colors.reset} ` : "";
|
|
230
|
+
const prefix = `${timestamp} ${level} ${scope}${entry.message}`;
|
|
231
|
+
if (entry.context && Object.keys(entry.context).length > 0) {
|
|
232
|
+
consoleMethod(prefix, formatContext(entry.context));
|
|
233
|
+
} else {
|
|
234
|
+
consoleMethod(prefix);
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
var LEVEL_PREFIX = {
|
|
238
|
+
debug: "[DEBUG]",
|
|
239
|
+
info: "[INFO]",
|
|
240
|
+
warn: "[WARN]",
|
|
241
|
+
error: "[ERROR]"
|
|
242
|
+
};
|
|
243
|
+
function formatContext2(context) {
|
|
244
|
+
return Object.entries(context).map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
|
|
245
|
+
}
|
|
246
|
+
function formatValue(value) {
|
|
247
|
+
if (typeof value === "string")
|
|
248
|
+
return value;
|
|
249
|
+
if (typeof value === "number")
|
|
250
|
+
return String(value);
|
|
251
|
+
if (typeof value === "boolean")
|
|
252
|
+
return String(value);
|
|
253
|
+
if (value === null)
|
|
254
|
+
return "null";
|
|
255
|
+
if (value === undefined)
|
|
256
|
+
return "undefined";
|
|
257
|
+
return JSON.stringify(value);
|
|
258
|
+
}
|
|
259
|
+
var ciFormatter = (entry) => {
|
|
260
|
+
const parts = [];
|
|
261
|
+
parts.push(entry.timestamp.toISOString());
|
|
262
|
+
parts.push(LEVEL_PREFIX[entry.level]);
|
|
263
|
+
if (entry.scope) {
|
|
264
|
+
parts.push(`[${entry.scope}]`);
|
|
265
|
+
}
|
|
266
|
+
parts.push(entry.message);
|
|
267
|
+
if (entry.context && Object.keys(entry.context).length > 0) {
|
|
268
|
+
parts.push(formatContext2(entry.context));
|
|
269
|
+
}
|
|
270
|
+
console.log(parts.join(" "));
|
|
271
|
+
};
|
|
272
|
+
var productionFormatter = (entry) => {
|
|
273
|
+
const output = {
|
|
274
|
+
timestamp: entry.timestamp.toISOString(),
|
|
275
|
+
level: entry.level,
|
|
276
|
+
...entry.scope && { scope: entry.scope },
|
|
277
|
+
msg: entry.message
|
|
278
|
+
};
|
|
279
|
+
if (entry.context && Object.keys(entry.context).length > 0) {
|
|
280
|
+
Object.assign(output, entry.context);
|
|
281
|
+
}
|
|
282
|
+
console.log(JSON.stringify(output));
|
|
283
|
+
};
|
|
284
|
+
var LEVEL_STYLES = {
|
|
285
|
+
debug: "color: gray",
|
|
286
|
+
info: "color: #0ea5e9",
|
|
287
|
+
warn: "color: #f59e0b",
|
|
288
|
+
error: "color: #ef4444; font-weight: bold"
|
|
289
|
+
};
|
|
290
|
+
var LEVEL_METHODS = {
|
|
291
|
+
debug: "log",
|
|
292
|
+
info: "info",
|
|
293
|
+
warn: "warn",
|
|
294
|
+
error: "error"
|
|
295
|
+
};
|
|
296
|
+
var browserFormatter = (entry) => {
|
|
297
|
+
const method = LEVEL_METHODS[entry.level];
|
|
298
|
+
const style = LEVEL_STYLES[entry.level];
|
|
299
|
+
const prefix = entry.scope ? `[${entry.scope}]` : "";
|
|
300
|
+
const label = `%c${prefix} ${entry.message}`;
|
|
301
|
+
if (entry.context && Object.keys(entry.context).length > 0) {
|
|
302
|
+
console[method](label, style, entry.context);
|
|
303
|
+
} else {
|
|
304
|
+
console[method](label, style);
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
var LOG_LEVELS = ["debug", "info", "warn", "error"];
|
|
308
|
+
function getFormatter(env) {
|
|
309
|
+
switch (env) {
|
|
310
|
+
case "terminal":
|
|
311
|
+
return terminalFormatter;
|
|
312
|
+
case "ci":
|
|
313
|
+
return ciFormatter;
|
|
314
|
+
case "production":
|
|
315
|
+
return productionFormatter;
|
|
316
|
+
case "browser":
|
|
317
|
+
return browserFormatter;
|
|
318
|
+
case "test":
|
|
319
|
+
return () => {};
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function getDefaultMinLevel() {
|
|
323
|
+
if (typeof process !== "undefined" && process.env?.DEBUG) {
|
|
324
|
+
return "debug";
|
|
325
|
+
}
|
|
326
|
+
return "info";
|
|
327
|
+
}
|
|
328
|
+
function shouldLog(level, minLevel) {
|
|
329
|
+
return LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(minLevel);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
class Logger {
|
|
333
|
+
scope;
|
|
334
|
+
minLevel;
|
|
335
|
+
environment;
|
|
336
|
+
formatter;
|
|
337
|
+
defaultContext;
|
|
338
|
+
constructor(options = {}) {
|
|
339
|
+
this.scope = options.scope;
|
|
340
|
+
this.minLevel = options.minLevel ?? getDefaultMinLevel();
|
|
341
|
+
this.defaultContext = options.defaultContext ?? {};
|
|
342
|
+
this.environment = options.environment ?? detectEnvironment();
|
|
343
|
+
this.formatter = getFormatter(this.environment);
|
|
344
|
+
}
|
|
345
|
+
child(scope) {
|
|
346
|
+
const childScope = this.scope ? `${this.scope}:${scope}` : scope;
|
|
347
|
+
return new Logger({
|
|
348
|
+
scope: childScope,
|
|
349
|
+
minLevel: this.minLevel,
|
|
350
|
+
environment: this.environment,
|
|
351
|
+
defaultContext: { ...this.defaultContext }
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
withContext(context) {
|
|
355
|
+
return new Logger({
|
|
356
|
+
scope: this.scope,
|
|
357
|
+
minLevel: this.minLevel,
|
|
358
|
+
environment: this.environment,
|
|
359
|
+
defaultContext: { ...this.defaultContext, ...context }
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
debug(message, context) {
|
|
363
|
+
this.log("debug", message, context);
|
|
364
|
+
}
|
|
365
|
+
info(message, context) {
|
|
366
|
+
this.log("info", message, context);
|
|
367
|
+
}
|
|
368
|
+
warn(message, context) {
|
|
369
|
+
this.log("warn", message, context);
|
|
370
|
+
}
|
|
371
|
+
error(message, context) {
|
|
372
|
+
this.log("error", message, context);
|
|
373
|
+
}
|
|
374
|
+
log(level, message, context) {
|
|
375
|
+
if (level === "debug" && !shouldShowDebug(this.scope)) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (!shouldLog(level, this.minLevel)) {
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
const entry = {
|
|
382
|
+
level,
|
|
383
|
+
message,
|
|
384
|
+
scope: this.scope,
|
|
385
|
+
context: context || Object.keys(this.defaultContext).length > 0 ? { ...this.defaultContext, ...context } : undefined,
|
|
386
|
+
timestamp: new Date
|
|
387
|
+
};
|
|
388
|
+
this.formatter(entry);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
function createLogger(options = {}) {
|
|
392
|
+
return new Logger(options);
|
|
393
|
+
}
|
|
394
|
+
function isDebug() {
|
|
395
|
+
try {
|
|
396
|
+
const debug = typeof process === "undefined" ? undefined : process.env["DEBUG"];
|
|
397
|
+
return debug === "1" || debug === "true";
|
|
398
|
+
} catch {
|
|
399
|
+
return false;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
var log = createLogger({ scope: "auth", minLevel: isDebug() ? "debug" : "warn" });
|
|
403
|
+
|
|
404
|
+
class TokenManager {
|
|
405
|
+
config;
|
|
406
|
+
accessToken = null;
|
|
407
|
+
tokenExpiry = 0;
|
|
408
|
+
pendingRequest = null;
|
|
409
|
+
fetchFn;
|
|
410
|
+
constructor(config) {
|
|
411
|
+
this.config = config;
|
|
412
|
+
this.fetchFn = config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
413
|
+
}
|
|
414
|
+
async getToken() {
|
|
415
|
+
if (this.accessToken && Date.now() < this.tokenExpiry) {
|
|
416
|
+
log.debug("Using cached token");
|
|
417
|
+
return this.accessToken;
|
|
418
|
+
}
|
|
419
|
+
if (this.pendingRequest) {
|
|
420
|
+
log.debug("Waiting for in-flight token request");
|
|
421
|
+
return this.pendingRequest;
|
|
422
|
+
}
|
|
423
|
+
this.pendingRequest = this.fetchToken();
|
|
424
|
+
try {
|
|
425
|
+
return await this.pendingRequest;
|
|
426
|
+
} finally {
|
|
427
|
+
this.pendingRequest = null;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
async fetchToken() {
|
|
431
|
+
log.debug("Fetching new access token...");
|
|
432
|
+
const { clientId, clientSecret } = this.config.credentials;
|
|
433
|
+
const credentials = btoa(`${clientId}:${clientSecret}`);
|
|
434
|
+
const start = performance.now();
|
|
435
|
+
const response = await this.fetchFn(this.config.tokenUrl, {
|
|
436
|
+
method: "POST",
|
|
437
|
+
headers: {
|
|
438
|
+
Authorization: `Basic ${credentials}`,
|
|
439
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
440
|
+
},
|
|
441
|
+
body: "grant_type=client_credentials"
|
|
442
|
+
});
|
|
443
|
+
const duration = Math.round(performance.now() - start);
|
|
444
|
+
if (!response.ok) {
|
|
445
|
+
log.error(`Token request failed: ${response.status} ${response.statusText}`);
|
|
446
|
+
throw new Error(`Failed to obtain access token: ${response.status} ${response.statusText}`);
|
|
447
|
+
}
|
|
448
|
+
const data = await response.json();
|
|
449
|
+
this.accessToken = data.access_token;
|
|
450
|
+
this.tokenExpiry = Date.now() + (data.expires_in - 60) * 1000;
|
|
451
|
+
log.debug(`Token acquired (${duration}ms, expires in ${data.expires_in}s)`);
|
|
452
|
+
return this.accessToken;
|
|
453
|
+
}
|
|
454
|
+
invalidate() {
|
|
455
|
+
log.debug("Token invalidated");
|
|
456
|
+
this.accessToken = null;
|
|
457
|
+
this.tokenExpiry = 0;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
var BEYONDAI_PATHS = {
|
|
461
|
+
caliper: {
|
|
462
|
+
send: "/caliper/event",
|
|
463
|
+
validate: "/caliper/event/validate",
|
|
464
|
+
list: "/caliper/events",
|
|
465
|
+
get: "/caliper/events/{id}",
|
|
466
|
+
jobStatus: "/jobs/{id}/status"
|
|
467
|
+
},
|
|
468
|
+
oneroster: {
|
|
469
|
+
rostering: "/ims/oneroster/rostering/v1p2",
|
|
470
|
+
gradebook: "/ims/oneroster/gradebook/v1p2",
|
|
471
|
+
resources: "/ims/oneroster/resources/v1p2"
|
|
472
|
+
},
|
|
473
|
+
edubridge: {
|
|
474
|
+
base: "/edubridge"
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
var LEARNWITHAI_PATHS = {
|
|
478
|
+
caliper: {
|
|
479
|
+
send: "/events/1.0/",
|
|
480
|
+
validate: null,
|
|
481
|
+
list: null,
|
|
482
|
+
get: null,
|
|
483
|
+
jobStatus: null
|
|
484
|
+
},
|
|
485
|
+
oneroster: {
|
|
486
|
+
rostering: "/rostering/1.0",
|
|
487
|
+
gradebook: "/gradebook/1.0",
|
|
488
|
+
resources: "/resources/1.0"
|
|
489
|
+
},
|
|
490
|
+
edubridge: null
|
|
491
|
+
};
|
|
492
|
+
var PLATFORM_PATHS = {
|
|
493
|
+
BEYOND_AI: BEYONDAI_PATHS,
|
|
494
|
+
LEARNWITH_AI: LEARNWITHAI_PATHS
|
|
495
|
+
};
|
|
496
|
+
function isEnvConfig(config) {
|
|
497
|
+
return "env" in config && !("baseUrl" in config) && !("services" in config);
|
|
498
|
+
}
|
|
499
|
+
function isExplicitConfig(config) {
|
|
500
|
+
return "baseUrl" in config && !("services" in config);
|
|
501
|
+
}
|
|
502
|
+
function isServicesConfig(config) {
|
|
503
|
+
return "services" in config;
|
|
504
|
+
}
|
|
505
|
+
function resolvePathProfiles(pathProfile, customPaths) {
|
|
506
|
+
const basePaths = pathProfile ? PLATFORM_PATHS[pathProfile] ?? BEYONDAI_PATHS : BEYONDAI_PATHS;
|
|
507
|
+
return {
|
|
508
|
+
caliper: customPaths?.caliper ?? basePaths.caliper,
|
|
509
|
+
oneroster: customPaths?.oneroster ?? basePaths.oneroster,
|
|
510
|
+
edubridge: customPaths?.edubridge ?? basePaths.edubridge
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
class TimebackProvider {
|
|
515
|
+
platform;
|
|
516
|
+
env;
|
|
517
|
+
auth;
|
|
518
|
+
timeout;
|
|
519
|
+
endpoints;
|
|
520
|
+
authUrl;
|
|
521
|
+
pathProfiles;
|
|
522
|
+
tokenManagers = new Map;
|
|
523
|
+
constructor(config) {
|
|
524
|
+
this.timeout = config.timeout ?? 30000;
|
|
525
|
+
if (isEnvConfig(config)) {
|
|
526
|
+
this.auth = config.auth;
|
|
527
|
+
const platform = config.platform ?? DEFAULT_PLATFORM;
|
|
528
|
+
const env = config.env;
|
|
529
|
+
this.platform = platform;
|
|
530
|
+
this.env = env;
|
|
531
|
+
const platformEndpoints = PLATFORM_ENDPOINTS[platform];
|
|
532
|
+
if (!platformEndpoints) {
|
|
533
|
+
throw new Error(`Unknown platform: ${platform}`);
|
|
534
|
+
}
|
|
535
|
+
this.authUrl = platformEndpoints.token[env];
|
|
536
|
+
this.pathProfiles = PLATFORM_PATHS[platform] ?? BEYONDAI_PATHS;
|
|
537
|
+
this.endpoints = {
|
|
538
|
+
oneroster: {
|
|
539
|
+
baseUrl: platformEndpoints.api[env],
|
|
540
|
+
authUrl: this.authUrl
|
|
541
|
+
},
|
|
542
|
+
edubridge: {
|
|
543
|
+
baseUrl: platformEndpoints.api[env],
|
|
544
|
+
authUrl: this.authUrl
|
|
545
|
+
},
|
|
546
|
+
caliper: {
|
|
547
|
+
baseUrl: platformEndpoints.caliper[env],
|
|
548
|
+
authUrl: this.authUrl
|
|
549
|
+
},
|
|
550
|
+
qti: {
|
|
551
|
+
baseUrl: platformEndpoints.qti[env],
|
|
552
|
+
authUrl: this.authUrl
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
} else if (isExplicitConfig(config)) {
|
|
556
|
+
this.auth = config.auth;
|
|
557
|
+
this.authUrl = config.authUrl;
|
|
558
|
+
this.pathProfiles = resolvePathProfiles(config.pathProfile, config.paths);
|
|
559
|
+
this.endpoints = {
|
|
560
|
+
oneroster: { baseUrl: config.baseUrl, authUrl: this.authUrl },
|
|
561
|
+
edubridge: { baseUrl: config.baseUrl, authUrl: this.authUrl },
|
|
562
|
+
caliper: { baseUrl: config.baseUrl, authUrl: this.authUrl },
|
|
563
|
+
qti: { baseUrl: config.baseUrl, authUrl: this.authUrl }
|
|
564
|
+
};
|
|
565
|
+
} else if (isServicesConfig(config)) {
|
|
566
|
+
this.auth = config.auth;
|
|
567
|
+
this.authUrl = config.authUrl;
|
|
568
|
+
this.pathProfiles = resolvePathProfiles(config.pathProfile, config.paths);
|
|
569
|
+
this.endpoints = {};
|
|
570
|
+
for (const [service, baseUrl] of Object.entries(config.services)) {
|
|
571
|
+
if (baseUrl) {
|
|
572
|
+
this.endpoints[service] = {
|
|
573
|
+
baseUrl,
|
|
574
|
+
authUrl: this.authUrl
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
} else {
|
|
579
|
+
throw new Error("Invalid provider configuration");
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
getEndpoint(service) {
|
|
583
|
+
const endpoint = this.endpoints[service];
|
|
584
|
+
if (!endpoint) {
|
|
585
|
+
throw new Error(`Service "${service}" is not configured in this provider`);
|
|
586
|
+
}
|
|
587
|
+
return endpoint;
|
|
588
|
+
}
|
|
589
|
+
hasService(service) {
|
|
590
|
+
return service in this.endpoints;
|
|
591
|
+
}
|
|
592
|
+
getAvailableServices() {
|
|
593
|
+
return Object.keys(this.endpoints);
|
|
594
|
+
}
|
|
595
|
+
getTokenUrl() {
|
|
596
|
+
return this.authUrl;
|
|
597
|
+
}
|
|
598
|
+
getEndpointWithPaths(service) {
|
|
599
|
+
const endpoint = this.getEndpoint(service);
|
|
600
|
+
const paths = this.getServicePaths(service);
|
|
601
|
+
return { ...endpoint, paths };
|
|
602
|
+
}
|
|
603
|
+
getPaths() {
|
|
604
|
+
return this.pathProfiles;
|
|
605
|
+
}
|
|
606
|
+
getServicePaths(service) {
|
|
607
|
+
const paths = this.pathProfiles[service];
|
|
608
|
+
if (!paths) {
|
|
609
|
+
throw new Error(`Service "${service}" is not supported on ${this.platform ?? "this"} platform.`);
|
|
610
|
+
}
|
|
611
|
+
return paths;
|
|
612
|
+
}
|
|
613
|
+
hasServiceSupport(service) {
|
|
614
|
+
return this.pathProfiles[service] !== null;
|
|
615
|
+
}
|
|
616
|
+
getTokenProvider(service) {
|
|
617
|
+
const endpoint = this.getEndpoint(service);
|
|
618
|
+
const { authUrl } = endpoint;
|
|
619
|
+
if (!authUrl) {
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
if (!this.auth) {
|
|
623
|
+
throw new Error(`Service "${service}" requires authentication but no credentials were provided`);
|
|
624
|
+
}
|
|
625
|
+
let manager = this.tokenManagers.get(authUrl);
|
|
626
|
+
if (!manager) {
|
|
627
|
+
manager = new TokenManager({
|
|
628
|
+
tokenUrl: authUrl,
|
|
629
|
+
credentials: {
|
|
630
|
+
clientId: this.auth.clientId,
|
|
631
|
+
clientSecret: this.auth.clientSecret
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
this.tokenManagers.set(authUrl, manager);
|
|
635
|
+
}
|
|
636
|
+
return manager;
|
|
637
|
+
}
|
|
638
|
+
async checkAuth() {
|
|
639
|
+
if (!this.authUrl || !this.auth) {
|
|
640
|
+
throw new Error("No auth configured on this provider");
|
|
641
|
+
}
|
|
642
|
+
const startTime = Date.now();
|
|
643
|
+
let manager = this.tokenManagers.get(this.authUrl);
|
|
644
|
+
if (!manager) {
|
|
645
|
+
manager = new TokenManager({
|
|
646
|
+
tokenUrl: this.authUrl,
|
|
647
|
+
credentials: {
|
|
648
|
+
clientId: this.auth.clientId,
|
|
649
|
+
clientSecret: this.auth.clientSecret
|
|
650
|
+
}
|
|
651
|
+
});
|
|
652
|
+
this.tokenManagers.set(this.authUrl, manager);
|
|
653
|
+
}
|
|
654
|
+
try {
|
|
655
|
+
await manager.getToken();
|
|
656
|
+
return {
|
|
657
|
+
ok: true,
|
|
658
|
+
latencyMs: Date.now() - startTime,
|
|
659
|
+
checks: { tokenAcquisition: true }
|
|
660
|
+
};
|
|
661
|
+
} catch (error) {
|
|
662
|
+
return {
|
|
663
|
+
ok: false,
|
|
664
|
+
latencyMs: Date.now() - startTime,
|
|
665
|
+
error: error instanceof Error ? error.message : String(error),
|
|
666
|
+
checks: { tokenAcquisition: false }
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
invalidateTokens() {
|
|
671
|
+
for (const manager of this.tokenManagers.values()) {
|
|
672
|
+
manager.invalidate?.();
|
|
673
|
+
}
|
|
674
|
+
this.tokenManagers.clear();
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
function getEnv(key) {
|
|
678
|
+
try {
|
|
679
|
+
return typeof process === "undefined" ? undefined : process.env[key];
|
|
680
|
+
} catch {
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
function isDebug2() {
|
|
685
|
+
const debug = getEnv("DEBUG");
|
|
686
|
+
return debug === "1" || debug === "true";
|
|
687
|
+
}
|
|
688
|
+
function generateRequestId() {
|
|
689
|
+
return Math.random().toString(16).slice(2, 10);
|
|
690
|
+
}
|
|
691
|
+
function createScopedLogger(scope) {
|
|
692
|
+
return createLogger({
|
|
693
|
+
scope,
|
|
694
|
+
minLevel: isDebug2() ? "debug" : "warn"
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
var DEFAULT_PROVIDER_REGISTRY = {
|
|
698
|
+
defaultPlatform: DEFAULT_PLATFORM,
|
|
699
|
+
templates: {
|
|
700
|
+
BEYOND_AI: {
|
|
701
|
+
staging: { platform: "BEYOND_AI", env: "staging" },
|
|
702
|
+
production: { platform: "BEYOND_AI", env: "production" }
|
|
703
|
+
},
|
|
704
|
+
LEARNWITH_AI: {
|
|
705
|
+
staging: { platform: "LEARNWITH_AI", env: "staging" },
|
|
706
|
+
production: { platform: "LEARNWITH_AI", env: "production" }
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
function validateEnv(env) {
|
|
711
|
+
if (env !== "staging" && env !== "production") {
|
|
712
|
+
throw new Error(`Invalid env "${env}": must be "staging" or "production"`);
|
|
713
|
+
}
|
|
714
|
+
return env;
|
|
715
|
+
}
|
|
716
|
+
function validateAuth(auth, envVars) {
|
|
717
|
+
const clientId = auth?.clientId ?? getEnv(envVars.clientId);
|
|
718
|
+
const clientSecret = auth?.clientSecret ?? getEnv(envVars.clientSecret);
|
|
719
|
+
if (!clientId) {
|
|
720
|
+
throw new Error(`Missing clientId: provide in config or set ${envVars.clientId}`);
|
|
721
|
+
}
|
|
722
|
+
if (!clientSecret) {
|
|
723
|
+
throw new Error(`Missing clientSecret: provide in config or set ${envVars.clientSecret}`);
|
|
724
|
+
}
|
|
725
|
+
return { clientId, clientSecret };
|
|
726
|
+
}
|
|
727
|
+
function validateAuthOptional(auth, envVars, requireAuth) {
|
|
728
|
+
if (!requireAuth) {
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
return validateAuth(auth, envVars);
|
|
732
|
+
}
|
|
733
|
+
function buildMissingEnvError(envVars) {
|
|
734
|
+
const baseUrl = getEnv(envVars.baseUrl);
|
|
735
|
+
const authUrl = getEnv(envVars.authUrl);
|
|
736
|
+
const clientId = getEnv(envVars.clientId);
|
|
737
|
+
const clientSecret = getEnv(envVars.clientSecret);
|
|
738
|
+
if (baseUrl === undefined && clientId === undefined) {
|
|
739
|
+
const hint = envVars.env ?? envVars.baseUrl;
|
|
740
|
+
return `Missing env: provide in config or set ${hint}`;
|
|
741
|
+
}
|
|
742
|
+
const missing = [];
|
|
743
|
+
if (baseUrl === undefined) {
|
|
744
|
+
missing.push(envVars.env ?? envVars.baseUrl);
|
|
745
|
+
}
|
|
746
|
+
if (baseUrl !== undefined && authUrl === undefined) {
|
|
747
|
+
missing.push(envVars.authUrl);
|
|
748
|
+
}
|
|
749
|
+
if (clientId === undefined) {
|
|
750
|
+
missing.push(envVars.clientId);
|
|
751
|
+
}
|
|
752
|
+
if (clientSecret === undefined) {
|
|
753
|
+
missing.push(envVars.clientSecret);
|
|
754
|
+
}
|
|
755
|
+
return `Missing environment variables: ${missing.join(", ")}`;
|
|
756
|
+
}
|
|
757
|
+
var MODE_TRANSPORT = {
|
|
758
|
+
name: "transport",
|
|
759
|
+
matches(config) {
|
|
760
|
+
return "transport" in config && !!config.transport;
|
|
761
|
+
},
|
|
762
|
+
resolve(config) {
|
|
763
|
+
const c = config;
|
|
764
|
+
return { mode: "transport", transport: c.transport };
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
var MODE_PROVIDER = {
|
|
768
|
+
name: "provider",
|
|
769
|
+
matches(config) {
|
|
770
|
+
return "provider" in config && !!config.provider;
|
|
771
|
+
},
|
|
772
|
+
resolve(config) {
|
|
773
|
+
const c = config;
|
|
774
|
+
return { mode: "provider", provider: c.provider };
|
|
775
|
+
}
|
|
776
|
+
};
|
|
777
|
+
var MODE_ENV_CONFIG = {
|
|
778
|
+
name: "env-config",
|
|
779
|
+
matches(config) {
|
|
780
|
+
return "env" in config;
|
|
781
|
+
},
|
|
782
|
+
resolve(config, envVars, registry) {
|
|
783
|
+
const c = config;
|
|
784
|
+
const env = validateEnv(c.env);
|
|
785
|
+
const auth = validateAuth(c.auth, envVars);
|
|
786
|
+
const platform = c.platform ?? registry.defaultPlatform;
|
|
787
|
+
const platformTemplates = registry.templates[platform];
|
|
788
|
+
if (!platformTemplates) {
|
|
789
|
+
const available = Object.keys(registry.templates).join(", ");
|
|
790
|
+
throw new Error(`Unknown platform "${platform}": available platforms are ${available}`);
|
|
791
|
+
}
|
|
792
|
+
const template = platformTemplates[env];
|
|
793
|
+
if (!template) {
|
|
794
|
+
const available = Object.keys(platformTemplates).join(", ");
|
|
795
|
+
throw new Error(`Unknown env "${env}" for platform "${platform}": available environments are ${available}`);
|
|
796
|
+
}
|
|
797
|
+
return {
|
|
798
|
+
mode: "provider",
|
|
799
|
+
provider: new TimebackProvider({
|
|
800
|
+
platform: template.platform,
|
|
801
|
+
env: template.env,
|
|
802
|
+
auth,
|
|
803
|
+
timeout: c.timeout
|
|
804
|
+
})
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
var MODE_EXPLICIT_CONFIG = {
|
|
809
|
+
name: "explicit-config",
|
|
810
|
+
matches(config) {
|
|
811
|
+
return "baseUrl" in config;
|
|
812
|
+
},
|
|
813
|
+
resolve(config, envVars) {
|
|
814
|
+
const c = config;
|
|
815
|
+
const authUrl = c.authUrl ?? c.auth?.authUrl;
|
|
816
|
+
const requireAuth = !!authUrl;
|
|
817
|
+
const auth = validateAuthOptional(c.auth, envVars, requireAuth);
|
|
818
|
+
return {
|
|
819
|
+
mode: "provider",
|
|
820
|
+
provider: new TimebackProvider({
|
|
821
|
+
baseUrl: c.baseUrl,
|
|
822
|
+
authUrl,
|
|
823
|
+
auth,
|
|
824
|
+
timeout: c.timeout,
|
|
825
|
+
pathProfile: c.pathProfile,
|
|
826
|
+
paths: c.paths
|
|
827
|
+
})
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
var MODE_ENV_FALLBACK_PLATFORM = {
|
|
832
|
+
name: "env-fallback-platform",
|
|
833
|
+
matches(config, envVars) {
|
|
834
|
+
if (Object.keys(config).length > 0)
|
|
835
|
+
return false;
|
|
836
|
+
const env = envVars.env ? getEnv(envVars.env) : undefined;
|
|
837
|
+
const clientId = getEnv(envVars.clientId);
|
|
838
|
+
const clientSecret = getEnv(envVars.clientSecret);
|
|
839
|
+
return env !== undefined && clientId !== undefined && clientSecret !== undefined;
|
|
840
|
+
},
|
|
841
|
+
resolve(_config, envVars, registry) {
|
|
842
|
+
const env = validateEnv(getEnv(envVars.env));
|
|
843
|
+
const clientId = getEnv(envVars.clientId);
|
|
844
|
+
const clientSecret = getEnv(envVars.clientSecret);
|
|
845
|
+
const platform = registry.defaultPlatform;
|
|
846
|
+
const template = registry.templates[platform]?.[env];
|
|
847
|
+
if (!template) {
|
|
848
|
+
throw new Error(`Unknown env "${env}" for platform "${platform}"`);
|
|
849
|
+
}
|
|
850
|
+
return {
|
|
851
|
+
mode: "provider",
|
|
852
|
+
provider: new TimebackProvider({
|
|
853
|
+
platform: template.platform,
|
|
854
|
+
env: template.env,
|
|
855
|
+
auth: { clientId, clientSecret }
|
|
856
|
+
})
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
var MODE_ENV_FALLBACK_EXPLICIT = {
|
|
861
|
+
name: "env-fallback-explicit",
|
|
862
|
+
matches(config, envVars) {
|
|
863
|
+
if (Object.keys(config).length > 0)
|
|
864
|
+
return false;
|
|
865
|
+
const baseUrl = getEnv(envVars.baseUrl);
|
|
866
|
+
const authUrl = getEnv(envVars.authUrl);
|
|
867
|
+
const clientId = getEnv(envVars.clientId);
|
|
868
|
+
const clientSecret = getEnv(envVars.clientSecret);
|
|
869
|
+
return baseUrl !== undefined && authUrl !== undefined && clientId !== undefined && clientSecret !== undefined;
|
|
870
|
+
},
|
|
871
|
+
resolve(_config, envVars) {
|
|
872
|
+
const baseUrl = getEnv(envVars.baseUrl);
|
|
873
|
+
const authUrl = getEnv(envVars.authUrl);
|
|
874
|
+
const clientId = getEnv(envVars.clientId);
|
|
875
|
+
const clientSecret = getEnv(envVars.clientSecret);
|
|
876
|
+
return {
|
|
877
|
+
mode: "provider",
|
|
878
|
+
provider: new TimebackProvider({
|
|
879
|
+
baseUrl,
|
|
880
|
+
authUrl,
|
|
881
|
+
auth: { clientId, clientSecret }
|
|
882
|
+
})
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
var MODE_TOKEN_PROVIDER = {
|
|
887
|
+
name: "token-provider",
|
|
888
|
+
matches(config) {
|
|
889
|
+
return "tokenProvider" in config;
|
|
890
|
+
},
|
|
891
|
+
resolve() {
|
|
892
|
+
throw new Error("TokenProvider mode is not supported with provider pattern. Use { provider: TimebackProvider } or { env, auth } instead.");
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
var MODES = [
|
|
896
|
+
MODE_TRANSPORT,
|
|
897
|
+
MODE_PROVIDER,
|
|
898
|
+
MODE_ENV_CONFIG,
|
|
899
|
+
MODE_TOKEN_PROVIDER,
|
|
900
|
+
MODE_EXPLICIT_CONFIG,
|
|
901
|
+
MODE_ENV_FALLBACK_PLATFORM,
|
|
902
|
+
MODE_ENV_FALLBACK_EXPLICIT
|
|
903
|
+
];
|
|
904
|
+
function resolveToProvider(config, envVars, registry = DEFAULT_PROVIDER_REGISTRY) {
|
|
905
|
+
for (const mode of MODES) {
|
|
906
|
+
if (mode.matches(config, envVars)) {
|
|
907
|
+
return mode.resolve(config, envVars, registry);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
throw new Error(buildMissingEnvError(envVars));
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
class ApiError extends Error {
|
|
914
|
+
statusCode;
|
|
915
|
+
response;
|
|
916
|
+
name = "ApiError";
|
|
917
|
+
constructor(message, statusCode, response) {
|
|
918
|
+
super(message);
|
|
919
|
+
this.statusCode = statusCode;
|
|
920
|
+
this.response = response;
|
|
921
|
+
}
|
|
922
|
+
get minorCodes() {
|
|
923
|
+
const ims = this.response;
|
|
924
|
+
if (!ims?.imsx_CodeMinor?.imsx_codeMinorField) {
|
|
925
|
+
return [];
|
|
926
|
+
}
|
|
927
|
+
return ims.imsx_CodeMinor.imsx_codeMinorField.map((field) => ({
|
|
928
|
+
field: field.imsx_codeMinorFieldName,
|
|
929
|
+
value: field.imsx_codeMinorFieldValue
|
|
930
|
+
}));
|
|
931
|
+
}
|
|
932
|
+
get details() {
|
|
933
|
+
const ims = this.response;
|
|
934
|
+
return ims?.imsx_error_details ?? [];
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
class UnauthorizedError extends ApiError {
|
|
939
|
+
name = "UnauthorizedError";
|
|
940
|
+
constructor(message = "Unauthorized", response) {
|
|
941
|
+
super(message, 401, response);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
class ForbiddenError extends ApiError {
|
|
946
|
+
name = "ForbiddenError";
|
|
947
|
+
constructor(message = "Forbidden", response) {
|
|
948
|
+
super(message, 403, response);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
class NotFoundError extends ApiError {
|
|
953
|
+
name = "NotFoundError";
|
|
954
|
+
constructor(message = "Not Found", response) {
|
|
955
|
+
super(message, 404, response);
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
class ValidationError extends ApiError {
|
|
960
|
+
name = "ValidationError";
|
|
961
|
+
constructor(message = "Validation Error", response) {
|
|
962
|
+
super(message, 422, response);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
var MAX_RETRIES = 3;
|
|
966
|
+
var RETRY_STATUS_CODES = [429, 503];
|
|
967
|
+
var INITIAL_RETRY_DELAY_MS = 1000;
|
|
968
|
+
|
|
969
|
+
class BaseTransport {
|
|
970
|
+
config;
|
|
971
|
+
log;
|
|
972
|
+
constructor(options) {
|
|
973
|
+
const { config, logger } = options;
|
|
974
|
+
const fetchFn = config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
975
|
+
let tokenProvider;
|
|
976
|
+
if ("tokenProvider" in config && config.tokenProvider) {
|
|
977
|
+
tokenProvider = config.tokenProvider;
|
|
978
|
+
} else if ("auth" in config && config.auth) {
|
|
979
|
+
tokenProvider = new TokenManager({
|
|
980
|
+
tokenUrl: config.auth.authUrl,
|
|
981
|
+
credentials: {
|
|
982
|
+
clientId: config.auth.clientId,
|
|
983
|
+
clientSecret: config.auth.clientSecret
|
|
984
|
+
},
|
|
985
|
+
fetch: fetchFn
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
this.config = {
|
|
989
|
+
baseUrl: config.baseUrl,
|
|
990
|
+
timeout: config.timeout ?? 30000,
|
|
991
|
+
fetch: fetchFn,
|
|
992
|
+
tokenProvider
|
|
993
|
+
};
|
|
994
|
+
this.log = logger.child("http");
|
|
995
|
+
}
|
|
996
|
+
get baseUrl() {
|
|
997
|
+
return this.config.baseUrl;
|
|
998
|
+
}
|
|
999
|
+
async request(path, options = {}) {
|
|
1000
|
+
const response = await this.requestRaw(path, options);
|
|
1001
|
+
return this.handleResponse(response);
|
|
1002
|
+
}
|
|
1003
|
+
async requestRaw(path, options = {}) {
|
|
1004
|
+
const { method = "GET", params, body, headers = {} } = options;
|
|
1005
|
+
const url = this.buildUrl(path, params);
|
|
1006
|
+
const requestId = options.requestId ?? generateRequestId();
|
|
1007
|
+
const operationStart = Date.now();
|
|
1008
|
+
const operationDeadline = operationStart + this.config.timeout;
|
|
1009
|
+
for (let attempt = 0;attempt < MAX_RETRIES; attempt++) {
|
|
1010
|
+
const remainingTime = operationDeadline - Date.now();
|
|
1011
|
+
if (remainingTime <= 0) {
|
|
1012
|
+
this.log.error("Request timeout before attempt", isDebug2() ? { requestId, path } : { path });
|
|
1013
|
+
throw new ApiError("Request timeout", 408);
|
|
1014
|
+
}
|
|
1015
|
+
const token = await this.getAccessToken();
|
|
1016
|
+
const isLastAttempt = attempt === MAX_RETRIES - 1;
|
|
1017
|
+
const start = performance.now();
|
|
1018
|
+
this.log.debug(`→ ${method} ${url}`, {
|
|
1019
|
+
requestId,
|
|
1020
|
+
attempt: attempt > 0 ? attempt + 1 : undefined
|
|
1021
|
+
});
|
|
1022
|
+
const requestHeaders = {
|
|
1023
|
+
"Content-Type": "application/json",
|
|
1024
|
+
Accept: "application/json",
|
|
1025
|
+
"X-Request-ID": requestId,
|
|
1026
|
+
...headers
|
|
1027
|
+
};
|
|
1028
|
+
if (token) {
|
|
1029
|
+
requestHeaders.Authorization = `Bearer ${token}`;
|
|
1030
|
+
}
|
|
1031
|
+
const response = await this.config.fetch(url, {
|
|
1032
|
+
method,
|
|
1033
|
+
headers: requestHeaders,
|
|
1034
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
1035
|
+
signal: AbortSignal.timeout(Math.min(remainingTime, this.config.timeout))
|
|
1036
|
+
});
|
|
1037
|
+
const duration = Math.round(performance.now() - start);
|
|
1038
|
+
this.log.debug(`← ${response.status} ${response.statusText} (${duration}ms)`, {
|
|
1039
|
+
requestId
|
|
1040
|
+
});
|
|
1041
|
+
const shouldRetry = RETRY_STATUS_CODES.includes(response.status) && !isLastAttempt;
|
|
1042
|
+
if (shouldRetry) {
|
|
1043
|
+
const retryAfter = response.headers.get("Retry-After");
|
|
1044
|
+
const delayMs = this.parseRetryAfter(retryAfter, attempt);
|
|
1045
|
+
const timeRemaining = operationDeadline - Date.now();
|
|
1046
|
+
if (delayMs >= timeRemaining) {
|
|
1047
|
+
this.log.error("Request timeout during retry backoff", isDebug2() ? { requestId, path } : { path });
|
|
1048
|
+
throw new ApiError("Request timeout", 408);
|
|
1049
|
+
}
|
|
1050
|
+
this.log.warn(`Retrying in ${delayMs}ms (attempt ${attempt + 1}/${MAX_RETRIES})`, {
|
|
1051
|
+
...isDebug2() && { requestId },
|
|
1052
|
+
status: response.status
|
|
1053
|
+
});
|
|
1054
|
+
await this.sleep(delayMs);
|
|
1055
|
+
continue;
|
|
1056
|
+
}
|
|
1057
|
+
if (!response.ok) {
|
|
1058
|
+
return this.handleErrorResponse(response, requestId);
|
|
1059
|
+
}
|
|
1060
|
+
return response;
|
|
1061
|
+
}
|
|
1062
|
+
this.log.error("Max retries exceeded", isDebug2() ? { requestId, path } : { path });
|
|
1063
|
+
throw new ApiError("Max retries exceeded");
|
|
1064
|
+
}
|
|
1065
|
+
getAccessToken() {
|
|
1066
|
+
if (!this.config.tokenProvider) {
|
|
1067
|
+
return Promise.resolve(undefined);
|
|
1068
|
+
}
|
|
1069
|
+
return this.config.tokenProvider.getToken();
|
|
1070
|
+
}
|
|
1071
|
+
buildUrl(path, params) {
|
|
1072
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(path)) {
|
|
1073
|
+
throw new Error(`Absolute URLs are not allowed in path: ${path}. Use relative paths only.`);
|
|
1074
|
+
}
|
|
1075
|
+
const url = new URL(path, this.config.baseUrl);
|
|
1076
|
+
if (params) {
|
|
1077
|
+
for (const [key, value] of Object.entries(params)) {
|
|
1078
|
+
if (value !== undefined) {
|
|
1079
|
+
url.searchParams.set(key, String(value));
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
return url.toString();
|
|
1084
|
+
}
|
|
1085
|
+
async handleResponse(response) {
|
|
1086
|
+
if (!response.ok) {
|
|
1087
|
+
await this.handleErrorResponse(response);
|
|
1088
|
+
}
|
|
1089
|
+
if (response.status === 204) {
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
const contentLength = response.headers.get("content-length");
|
|
1093
|
+
if (contentLength === "0") {
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
return this.parseJsonResponse(response);
|
|
1097
|
+
}
|
|
1098
|
+
async parseJsonResponse(response) {
|
|
1099
|
+
const text = await response.text();
|
|
1100
|
+
if (!text || text.trim() === "") {
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
try {
|
|
1104
|
+
return JSON.parse(text);
|
|
1105
|
+
} catch (error) {
|
|
1106
|
+
const preview = text.length > 200 ? text.slice(0, 200) + "..." : text;
|
|
1107
|
+
const parseError = error instanceof Error ? error.message : String(error);
|
|
1108
|
+
const url = response.url || "unknown";
|
|
1109
|
+
this.log.error("Failed to parse JSON response", {
|
|
1110
|
+
url,
|
|
1111
|
+
status: response.status,
|
|
1112
|
+
contentType: response.headers.get("content-type"),
|
|
1113
|
+
bodyPreview: preview,
|
|
1114
|
+
error: parseError
|
|
1115
|
+
});
|
|
1116
|
+
throw new ApiError(`Invalid JSON response from ${url}`, response.status, {
|
|
1117
|
+
parseError,
|
|
1118
|
+
body: preview
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
async handleErrorResponse(response, requestId) {
|
|
1123
|
+
let errorBody;
|
|
1124
|
+
const text = await response.text().catch(() => "");
|
|
1125
|
+
if (text) {
|
|
1126
|
+
try {
|
|
1127
|
+
errorBody = JSON.parse(text);
|
|
1128
|
+
} catch (parseError) {
|
|
1129
|
+
const parseWarning = parseError instanceof Error ? parseError.message : "Unknown parse error";
|
|
1130
|
+
errorBody = { rawBody: text.slice(0, 500), parseError: parseWarning };
|
|
1131
|
+
this.log.warn("Failed to parse error response as JSON", {
|
|
1132
|
+
...isDebug2() && { requestId },
|
|
1133
|
+
url: response.url,
|
|
1134
|
+
status: response.status,
|
|
1135
|
+
parseError: parseWarning,
|
|
1136
|
+
bodyPreview: text.slice(0, 200)
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
const message = this.extractErrorMessage(errorBody, response.statusText);
|
|
1141
|
+
if (response.status !== 404) {
|
|
1142
|
+
this.log.error(`Request failed: ${response.status} ${message}`, isDebug2() ? { requestId } : undefined);
|
|
1143
|
+
}
|
|
1144
|
+
switch (response.status) {
|
|
1145
|
+
case 401:
|
|
1146
|
+
this.config.tokenProvider?.invalidate?.();
|
|
1147
|
+
throw new UnauthorizedError(message, errorBody);
|
|
1148
|
+
case 403:
|
|
1149
|
+
throw new ForbiddenError(message, errorBody);
|
|
1150
|
+
case 404:
|
|
1151
|
+
throw new NotFoundError(message, errorBody);
|
|
1152
|
+
case 422:
|
|
1153
|
+
throw new ValidationError(message, errorBody);
|
|
1154
|
+
default:
|
|
1155
|
+
throw new ApiError(message, response.status, errorBody);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
extractErrorMessage(body, fallback) {
|
|
1159
|
+
if (typeof body === "object" && body !== null) {
|
|
1160
|
+
const obj = body;
|
|
1161
|
+
if (typeof obj.message === "string")
|
|
1162
|
+
return obj.message;
|
|
1163
|
+
if (typeof obj.error === "string")
|
|
1164
|
+
return obj.error;
|
|
1165
|
+
if (typeof obj.imsx_description === "string")
|
|
1166
|
+
return obj.imsx_description;
|
|
1167
|
+
}
|
|
1168
|
+
return fallback;
|
|
1169
|
+
}
|
|
1170
|
+
sleep(ms) {
|
|
1171
|
+
return new Promise((resolve) => {
|
|
1172
|
+
setTimeout(resolve, ms);
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
parseRetryAfter(retryAfter, attempt) {
|
|
1176
|
+
if (!retryAfter) {
|
|
1177
|
+
return INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt);
|
|
1178
|
+
}
|
|
1179
|
+
const seconds = parseInt(retryAfter, 10);
|
|
1180
|
+
if (!isNaN(seconds)) {
|
|
1181
|
+
return seconds * 1000;
|
|
1182
|
+
}
|
|
1183
|
+
const date = Date.parse(retryAfter);
|
|
1184
|
+
if (!isNaN(date)) {
|
|
1185
|
+
const delayMs = date - Date.now();
|
|
1186
|
+
return Math.max(0, delayMs);
|
|
1187
|
+
}
|
|
1188
|
+
return INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt);
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
function parseBodyPaginationRaw(body) {
|
|
1192
|
+
const hasMore = body.pageNumber < body.pageCount;
|
|
1193
|
+
return {
|
|
1194
|
+
data: body,
|
|
1195
|
+
hasMore,
|
|
1196
|
+
total: body.totalCount
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
var EDUBRIDGE_ENV_VARS = {
|
|
1200
|
+
baseUrl: "EDUBRIDGE_BASE_URL",
|
|
1201
|
+
clientId: "EDUBRIDGE_CLIENT_ID",
|
|
1202
|
+
clientSecret: "EDUBRIDGE_CLIENT_SECRET",
|
|
1203
|
+
authUrl: "EDUBRIDGE_TOKEN_URL"
|
|
1204
|
+
};
|
|
1205
|
+
function resolveToProvider2(config, registry = DEFAULT_PROVIDER_REGISTRY) {
|
|
1206
|
+
return resolveToProvider(config, EDUBRIDGE_ENV_VARS, registry);
|
|
1207
|
+
}
|
|
1208
|
+
var log2 = createScopedLogger("edubridge");
|
|
1209
|
+
function normalizeBoolean(value) {
|
|
1210
|
+
if (typeof value === "boolean")
|
|
1211
|
+
return value;
|
|
1212
|
+
return value === "true";
|
|
1213
|
+
}
|
|
1214
|
+
function normalizeUser(user) {
|
|
1215
|
+
return {
|
|
1216
|
+
...user,
|
|
1217
|
+
enabledUser: normalizeBoolean(user.enabledUser)
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
function normalizeDate(date) {
|
|
1221
|
+
if (date === undefined) {
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
if (date instanceof Date) {
|
|
1225
|
+
return date.toISOString();
|
|
1226
|
+
}
|
|
1227
|
+
if (date.includes("T")) {
|
|
1228
|
+
return date;
|
|
1229
|
+
}
|
|
1230
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
|
1231
|
+
return `${date}T00:00:00.000Z`;
|
|
1232
|
+
}
|
|
1233
|
+
return date;
|
|
1234
|
+
}
|
|
1235
|
+
function aggregateActivityMetrics(data) {
|
|
1236
|
+
const result = {
|
|
1237
|
+
totalXp: 0,
|
|
1238
|
+
totalQuestions: 0,
|
|
1239
|
+
correctQuestions: 0,
|
|
1240
|
+
masteredUnits: 0,
|
|
1241
|
+
activeSeconds: 0,
|
|
1242
|
+
inactiveSeconds: 0,
|
|
1243
|
+
wasteSeconds: 0,
|
|
1244
|
+
dayCount: 0,
|
|
1245
|
+
subjectCount: 0
|
|
1246
|
+
};
|
|
1247
|
+
const dates = Object.keys(data);
|
|
1248
|
+
result.dayCount = dates.length;
|
|
1249
|
+
for (const date of dates) {
|
|
1250
|
+
const subjects = data[date];
|
|
1251
|
+
if (!subjects)
|
|
1252
|
+
continue;
|
|
1253
|
+
for (const subjectKey of Object.keys(subjects)) {
|
|
1254
|
+
const metrics = subjects[subjectKey];
|
|
1255
|
+
if (!metrics)
|
|
1256
|
+
continue;
|
|
1257
|
+
result.subjectCount += 1;
|
|
1258
|
+
result.totalXp += metrics.activityMetrics.xpEarned;
|
|
1259
|
+
result.totalQuestions += metrics.activityMetrics.totalQuestions;
|
|
1260
|
+
result.correctQuestions += metrics.activityMetrics.correctQuestions;
|
|
1261
|
+
result.masteredUnits += metrics.activityMetrics.masteredUnits;
|
|
1262
|
+
result.activeSeconds += metrics.timeSpentMetrics.activeSeconds;
|
|
1263
|
+
result.inactiveSeconds += metrics.timeSpentMetrics.inactiveSeconds;
|
|
1264
|
+
result.wasteSeconds += metrics.timeSpentMetrics.wasteSeconds;
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
return result;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
class Transport extends BaseTransport {
|
|
1271
|
+
paths;
|
|
1272
|
+
constructor(config) {
|
|
1273
|
+
super({ config, logger: log2 });
|
|
1274
|
+
this.paths = config.paths;
|
|
1275
|
+
}
|
|
1276
|
+
async requestPaginated(path, options = {}) {
|
|
1277
|
+
const response = await this.requestRaw(path, options);
|
|
1278
|
+
const body = await response.json();
|
|
1279
|
+
return parseBodyPaginationRaw(body);
|
|
1280
|
+
}
|
|
1281
|
+
extractErrorMessage(body, fallback) {
|
|
1282
|
+
const baseMessage = super.extractErrorMessage(body, "");
|
|
1283
|
+
if (baseMessage)
|
|
1284
|
+
return baseMessage;
|
|
1285
|
+
const edubridgeBody = body;
|
|
1286
|
+
const firstError = edubridgeBody?.errors?.[0];
|
|
1287
|
+
if (firstError) {
|
|
1288
|
+
const parts = [];
|
|
1289
|
+
if (firstError.message) {
|
|
1290
|
+
parts.push(firstError.message);
|
|
1291
|
+
}
|
|
1292
|
+
if (firstError.detail && firstError.detail !== firstError.message) {
|
|
1293
|
+
parts.push(firstError.detail);
|
|
1294
|
+
}
|
|
1295
|
+
if (firstError.meta?.issues?.length) {
|
|
1296
|
+
const issueMessages = firstError.meta.issues.filter((issue) => issue.path && issue.message).map((issue) => `${issue.path}: ${issue.message}`);
|
|
1297
|
+
if (issueMessages.length > 0) {
|
|
1298
|
+
parts.push(`[${issueMessages.join(", ")}]`);
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
if (parts.length > 0) {
|
|
1302
|
+
return parts.join(" - ");
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
return fallback;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
class AnalyticsResource {
|
|
1310
|
+
transport;
|
|
1311
|
+
constructor(transport) {
|
|
1312
|
+
this.transport = transport;
|
|
1313
|
+
}
|
|
1314
|
+
async getActivity(params) {
|
|
1315
|
+
const response = await this.transport.request(`${this.transport.paths.base}/analytics/activity`, {
|
|
1316
|
+
params: {
|
|
1317
|
+
email: params.email,
|
|
1318
|
+
studentId: params.studentId,
|
|
1319
|
+
startDate: normalizeDate(params.startDate),
|
|
1320
|
+
endDate: normalizeDate(params.endDate),
|
|
1321
|
+
timezone: params.timezone
|
|
1322
|
+
}
|
|
1323
|
+
});
|
|
1324
|
+
return response.facts;
|
|
1325
|
+
}
|
|
1326
|
+
async getWeeklyFacts(params) {
|
|
1327
|
+
const response = await this.transport.request(`${this.transport.paths.base}/analytics/facts/weekly`, {
|
|
1328
|
+
params: {
|
|
1329
|
+
email: params.email,
|
|
1330
|
+
studentId: params.studentId,
|
|
1331
|
+
weekDate: normalizeDate(params.weekDate),
|
|
1332
|
+
timezone: params.timezone
|
|
1333
|
+
}
|
|
1334
|
+
});
|
|
1335
|
+
return response.facts;
|
|
1336
|
+
}
|
|
1337
|
+
async getEnrollmentFacts(params) {
|
|
1338
|
+
const response = await this.transport.request(`${this.transport.paths.base}/analytics/enrollment/${encodeURIComponent(params.enrollmentId)}`, {
|
|
1339
|
+
params: {
|
|
1340
|
+
startDate: normalizeDate(params.startDate),
|
|
1341
|
+
endDate: normalizeDate(params.endDate),
|
|
1342
|
+
timezone: params.timezone
|
|
1343
|
+
}
|
|
1344
|
+
});
|
|
1345
|
+
return response.facts;
|
|
1346
|
+
}
|
|
1347
|
+
getHighestGradeMastered(studentId, subject) {
|
|
1348
|
+
return this.transport.request(`${this.transport.paths.base}/analytics/highestGradeMastered/${encodeURIComponent(studentId)}/${encodeURIComponent(subject)}`);
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
class ApplicationsResource {
|
|
1353
|
+
transport;
|
|
1354
|
+
constructor(transport) {
|
|
1355
|
+
this.transport = transport;
|
|
1356
|
+
}
|
|
1357
|
+
async list() {
|
|
1358
|
+
const response = await this.transport.request(`${this.transport.paths.base}/applications/`);
|
|
1359
|
+
return response.applications;
|
|
1360
|
+
}
|
|
1361
|
+
async getMetrics(applicationSourcedId) {
|
|
1362
|
+
const response = await this.transport.request(`${this.transport.paths.base}/applicationMetrics/${encodeURIComponent(applicationSourcedId)}`);
|
|
1363
|
+
return response.data;
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
class EnrollmentsResource {
|
|
1368
|
+
transport;
|
|
1369
|
+
constructor(transport) {
|
|
1370
|
+
this.transport = transport;
|
|
1371
|
+
}
|
|
1372
|
+
async list(params) {
|
|
1373
|
+
const response = await this.transport.request(`${this.transport.paths.base}/enrollments/user/${encodeURIComponent(params.userId)}`);
|
|
1374
|
+
return response.data;
|
|
1375
|
+
}
|
|
1376
|
+
async enroll(userId, courseId, schoolId, options = {}) {
|
|
1377
|
+
const base = `${this.transport.paths.base}/enrollments/enroll/${encodeURIComponent(userId)}/${encodeURIComponent(courseId)}`;
|
|
1378
|
+
const path = schoolId ? `${base}/${encodeURIComponent(schoolId)}` : base;
|
|
1379
|
+
const response = await this.transport.request(path, {
|
|
1380
|
+
method: "POST",
|
|
1381
|
+
body: options
|
|
1382
|
+
});
|
|
1383
|
+
return response.data;
|
|
1384
|
+
}
|
|
1385
|
+
async unenroll(userId, courseId, schoolId) {
|
|
1386
|
+
const base = `${this.transport.paths.base}/enrollments/unenroll/${encodeURIComponent(userId)}/${encodeURIComponent(courseId)}`;
|
|
1387
|
+
const path = schoolId ? `${base}/${encodeURIComponent(schoolId)}` : base;
|
|
1388
|
+
await this.transport.request(path, { method: "DELETE" });
|
|
1389
|
+
}
|
|
1390
|
+
async resetGoals(courseId) {
|
|
1391
|
+
const response = await this.transport.request(`${this.transport.paths.base}/enrollments/resetGoals/${encodeURIComponent(courseId)}`, { method: "POST" });
|
|
1392
|
+
return response.data;
|
|
1393
|
+
}
|
|
1394
|
+
async resetProgress(userId, courseId) {
|
|
1395
|
+
await this.transport.request(`${this.transport.paths.base}/enrollments/resetProgress/${encodeURIComponent(userId)}/${encodeURIComponent(courseId)}`, { method: "DELETE" });
|
|
1396
|
+
}
|
|
1397
|
+
async getDefaultClass(courseId, schoolId) {
|
|
1398
|
+
const base = `${this.transport.paths.base}/enrollments/defaultClass/${encodeURIComponent(courseId)}`;
|
|
1399
|
+
const path = schoolId ? `${base}/${encodeURIComponent(schoolId)}` : base;
|
|
1400
|
+
const response = await this.transport.request(path);
|
|
1401
|
+
return response.data;
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
class LearningReportsResource {
|
|
1406
|
+
transport;
|
|
1407
|
+
constructor(transport) {
|
|
1408
|
+
this.transport = transport;
|
|
1409
|
+
}
|
|
1410
|
+
async getMapProfile(userId) {
|
|
1411
|
+
const response = await this.transport.request(`${this.transport.paths.base}/learning-reports/map-profile/${encodeURIComponent(userId)}`);
|
|
1412
|
+
return response.data;
|
|
1413
|
+
}
|
|
1414
|
+
async getTimeSaved(userId) {
|
|
1415
|
+
const response = await this.transport.request(`${this.transport.paths.base}/time-saved/user/${encodeURIComponent(userId)}`);
|
|
1416
|
+
return response.data;
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
class SubjectTrackResource {
|
|
1421
|
+
transport;
|
|
1422
|
+
constructor(transport) {
|
|
1423
|
+
this.transport = transport;
|
|
1424
|
+
}
|
|
1425
|
+
async list() {
|
|
1426
|
+
const response = await this.transport.request(`${this.transport.paths.base}/subject-track/`);
|
|
1427
|
+
return response.subjectTrack;
|
|
1428
|
+
}
|
|
1429
|
+
async upsert(data) {
|
|
1430
|
+
const response = await this.transport.request(`${this.transport.paths.base}/subject-track/`, { method: "PUT", body: data });
|
|
1431
|
+
return response.subjectTrack;
|
|
1432
|
+
}
|
|
1433
|
+
async delete(id) {
|
|
1434
|
+
await this.transport.request(`${this.transport.paths.base}/subject-track/${encodeURIComponent(id)}`, { method: "DELETE" });
|
|
1435
|
+
}
|
|
1436
|
+
async listGroups() {
|
|
1437
|
+
const response = await this.transport.request(`${this.transport.paths.base}/subject-track/groups`);
|
|
1438
|
+
return response.groups;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
class UsersResource {
|
|
1443
|
+
transport;
|
|
1444
|
+
constructor(transport) {
|
|
1445
|
+
this.transport = transport;
|
|
1446
|
+
}
|
|
1447
|
+
async list(params) {
|
|
1448
|
+
const queryParams = {
|
|
1449
|
+
fields: params.fields,
|
|
1450
|
+
limit: params.limit,
|
|
1451
|
+
offset: params.offset,
|
|
1452
|
+
sort: params.sort,
|
|
1453
|
+
orderBy: params.orderBy,
|
|
1454
|
+
filter: params.filter,
|
|
1455
|
+
search: params.search
|
|
1456
|
+
};
|
|
1457
|
+
const url = new URL(`${this.transport.paths.base}/users/`, "http://placeholder");
|
|
1458
|
+
for (const [key, value] of Object.entries(queryParams)) {
|
|
1459
|
+
if (value !== undefined) {
|
|
1460
|
+
url.searchParams.set(key, String(value));
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
for (const role of params.roles) {
|
|
1464
|
+
url.searchParams.append("roles", role);
|
|
1465
|
+
}
|
|
1466
|
+
if (params.orgSourcedIds) {
|
|
1467
|
+
for (const orgId of params.orgSourcedIds) {
|
|
1468
|
+
url.searchParams.append("orgSourcedIds", orgId);
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
const path = `${this.transport.paths.base}/users/${url.search}`;
|
|
1472
|
+
const response = await this.transport.request(path);
|
|
1473
|
+
return response.users.map(normalizeUser);
|
|
1474
|
+
}
|
|
1475
|
+
listStudents(params = {}) {
|
|
1476
|
+
return this.list({ ...params, roles: ["student"] });
|
|
1477
|
+
}
|
|
1478
|
+
listTeachers(params = {}) {
|
|
1479
|
+
return this.list({ ...params, roles: ["teacher"] });
|
|
1480
|
+
}
|
|
1481
|
+
search(roles, search, limit = 100) {
|
|
1482
|
+
return this.list({ roles, search, limit });
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
function createEdubridgeClient(registry = DEFAULT_PROVIDER_REGISTRY) {
|
|
1486
|
+
return class EdubridgeClient {
|
|
1487
|
+
transport;
|
|
1488
|
+
_provider;
|
|
1489
|
+
enrollments;
|
|
1490
|
+
users;
|
|
1491
|
+
analytics;
|
|
1492
|
+
applications;
|
|
1493
|
+
subjectTracks;
|
|
1494
|
+
learningReports;
|
|
1495
|
+
constructor(config = {}) {
|
|
1496
|
+
const resolved = resolveToProvider2(config, registry);
|
|
1497
|
+
if (resolved.mode === "transport") {
|
|
1498
|
+
this.transport = resolved.transport;
|
|
1499
|
+
log2.info("Client initialized with custom transport");
|
|
1500
|
+
} else {
|
|
1501
|
+
const { provider } = resolved;
|
|
1502
|
+
const { baseUrl, paths } = provider.getEndpointWithPaths("edubridge");
|
|
1503
|
+
const tokenProvider = provider.getTokenProvider("edubridge");
|
|
1504
|
+
if (!tokenProvider) {
|
|
1505
|
+
throw new Error("Edubridge API requires authentication");
|
|
1506
|
+
}
|
|
1507
|
+
this._provider = provider;
|
|
1508
|
+
this.transport = new Transport({
|
|
1509
|
+
baseUrl,
|
|
1510
|
+
tokenProvider,
|
|
1511
|
+
timeout: provider.timeout,
|
|
1512
|
+
paths
|
|
1513
|
+
});
|
|
1514
|
+
log2.info("Client initialized", {
|
|
1515
|
+
platform: provider.platform,
|
|
1516
|
+
env: provider.env,
|
|
1517
|
+
baseUrl
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
this.enrollments = new EnrollmentsResource(this.transport);
|
|
1521
|
+
this.users = new UsersResource(this.transport);
|
|
1522
|
+
this.analytics = new AnalyticsResource(this.transport);
|
|
1523
|
+
this.applications = new ApplicationsResource(this.transport);
|
|
1524
|
+
this.subjectTracks = new SubjectTrackResource(this.transport);
|
|
1525
|
+
this.learningReports = new LearningReportsResource(this.transport);
|
|
1526
|
+
}
|
|
1527
|
+
getTransport() {
|
|
1528
|
+
return this.transport;
|
|
1529
|
+
}
|
|
1530
|
+
checkAuth() {
|
|
1531
|
+
if (!this._provider) {
|
|
1532
|
+
throw new Error("Cannot check auth: client initialized with custom transport");
|
|
1533
|
+
}
|
|
1534
|
+
return this._provider.checkAuth();
|
|
1535
|
+
}
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
var EdubridgeClient = createEdubridgeClient();
|
|
1539
|
+
export {
|
|
1540
|
+
aggregateActivityMetrics
|
|
1541
|
+
};
|