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