@pie-qti/item-player 0.1.27 → 1.0.0-beta.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 (109) hide show
  1. package/README.md +35 -6
  2. package/dist/catalog/applyGlossaryTriggers.js +8 -2
  3. package/dist/catalog/applyGlossaryTriggers.js.map +1 -1
  4. package/dist/catalog/catalogExtractor.js +44 -7
  5. package/dist/catalog/catalogExtractor.js.map +1 -1
  6. package/dist/catalog/catalogLookup.d.ts +8 -0
  7. package/dist/catalog/catalogLookup.js +17 -0
  8. package/dist/catalog/catalogLookup.js.map +1 -1
  9. package/dist/catalog/types.d.ts +3 -3
  10. package/dist/catalog/types.js.map +1 -1
  11. package/dist/components/utils/feedbackUtils.d.ts +9 -4
  12. package/dist/components/utils/feedbackUtils.js +67 -34
  13. package/dist/components/utils/feedbackUtils.js.map +1 -1
  14. package/dist/core/AssessmentItemDefinition.js +35 -0
  15. package/dist/core/AssessmentItemDefinition.js.map +1 -1
  16. package/dist/core/ItemSession.d.ts +19 -1
  17. package/dist/core/ItemSession.js +12 -2
  18. package/dist/core/ItemSession.js.map +1 -1
  19. package/dist/core/Player.d.ts +41 -1
  20. package/dist/core/Player.js +216 -48
  21. package/dist/core/Player.js.map +1 -1
  22. package/dist/core/sanitizer.js +16 -3
  23. package/dist/core/sanitizer.js.map +1 -1
  24. package/dist/document/AssessmentItemDocument.d.ts +12 -5
  25. package/dist/document/AssessmentItemDocument.js +28 -19
  26. package/dist/document/AssessmentItemDocument.js.map +1 -1
  27. package/dist/document/contentPass.d.ts +17 -0
  28. package/dist/document/contentPass.js +40 -0
  29. package/dist/document/contentPass.js.map +1 -0
  30. package/dist/document/printedVariable.d.ts +35 -0
  31. package/dist/document/printedVariable.js +215 -0
  32. package/dist/document/printedVariable.js.map +1 -0
  33. package/dist/{element-class-BzATCyhV.js → element-class-D-kJi_w9.js} +3211 -2125
  34. package/dist/element-class-D-kJi_w9.js.map +1 -0
  35. package/dist/element-class.js +1 -1
  36. package/dist/element.js +1 -1
  37. package/dist/extraction/interactionAccessibility.d.ts +14 -0
  38. package/dist/extraction/interactionAccessibility.js +58 -0
  39. package/dist/extraction/interactionAccessibility.js.map +1 -0
  40. package/dist/extraction/interactionExtractionPipeline.d.ts +4 -1
  41. package/dist/extraction/interactionExtractionPipeline.js +7 -2
  42. package/dist/extraction/interactionExtractionPipeline.js.map +1 -1
  43. package/dist/extraction/utils.js +20 -1
  44. package/dist/extraction/utils.js.map +1 -1
  45. package/dist/index.d.ts +9 -3
  46. package/dist/index.js +4 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/interactions/order/extractor.js +2 -0
  49. package/dist/interactions/order/extractor.js.map +1 -1
  50. package/dist/interactions/portable-custom/extractor.js +47 -11
  51. package/dist/interactions/portable-custom/extractor.js.map +1 -1
  52. package/dist/interactions/shared/types.d.ts +16 -0
  53. package/dist/interactions/shared/types.js.map +1 -1
  54. package/dist/pci/PciHost.d.ts +85 -43
  55. package/dist/pci/PciHost.js +229 -148
  56. package/dist/pci/PciHost.js.map +1 -1
  57. package/dist/pci/allowlistResolver.d.ts +10 -1
  58. package/dist/pci/allowlistResolver.js +43 -4
  59. package/dist/pci/allowlistResolver.js.map +1 -1
  60. package/dist/pci/amdLoader.d.ts +23 -0
  61. package/dist/pci/amdLoader.js +190 -0
  62. package/dist/pci/amdLoader.js.map +1 -0
  63. package/dist/pci/index.d.ts +14 -3
  64. package/dist/pci/index.js +8 -1
  65. package/dist/pci/index.js.map +1 -1
  66. package/dist/pci/moduleSession.d.ts +41 -0
  67. package/dist/pci/moduleSession.js +2 -0
  68. package/dist/pci/moduleSession.js.map +1 -0
  69. package/dist/pci/pageRealmSession.d.ts +49 -0
  70. package/dist/pci/pageRealmSession.js +193 -0
  71. package/dist/pci/pageRealmSession.js.map +1 -0
  72. package/dist/pci/qtiVariableJson.d.ts +7 -0
  73. package/dist/pci/qtiVariableJson.js +93 -0
  74. package/dist/pci/qtiVariableJson.js.map +1 -0
  75. package/dist/pci/registry.d.ts +15 -0
  76. package/dist/pci/registry.js +77 -0
  77. package/dist/pci/registry.js.map +1 -0
  78. package/dist/pci/resolutionConfig.d.ts +23 -0
  79. package/dist/pci/resolutionConfig.js +63 -0
  80. package/dist/pci/resolutionConfig.js.map +1 -0
  81. package/dist/pci/sandbox/SandboxedPciSession.d.ts +78 -0
  82. package/dist/pci/sandbox/SandboxedPciSession.js +332 -0
  83. package/dist/pci/sandbox/SandboxedPciSession.js.map +1 -0
  84. package/dist/pci/sandbox/iframeConnector.d.ts +13 -0
  85. package/dist/pci/sandbox/iframeConnector.js +94 -0
  86. package/dist/pci/sandbox/iframeConnector.js.map +1 -0
  87. package/dist/pci/sandbox/protocol.d.ts +117 -0
  88. package/dist/pci/sandbox/protocol.js +49 -0
  89. package/dist/pci/sandbox/protocol.js.map +1 -0
  90. package/dist/pci/types.d.ts +213 -30
  91. package/dist/pci/types.js +8 -1
  92. package/dist/pci/types.js.map +1 -1
  93. package/dist/pnp/applyPnp.d.ts +3 -4
  94. package/dist/pnp/applyPnp.js +54 -8
  95. package/dist/pnp/applyPnp.js.map +1 -1
  96. package/dist/pnp/parsePnpXml.d.ts +2 -2
  97. package/dist/pnp/parsePnpXml.js +146 -4
  98. package/dist/pnp/parsePnpXml.js.map +1 -1
  99. package/dist/pnp/types.d.ts +57 -0
  100. package/dist/pnp/types.js.map +1 -1
  101. package/dist/presentation/itemPresentationPlan.d.ts +12 -1
  102. package/dist/presentation/itemPresentationPlan.js +11 -3
  103. package/dist/presentation/itemPresentationPlan.js.map +1 -1
  104. package/dist/server.d.ts +5 -0
  105. package/dist/server.js.map +1 -1
  106. package/dist/types/index.d.ts +5 -0
  107. package/dist/types/index.js.map +1 -1
  108. package/package.json +6 -6
  109. package/dist/element-class-BzATCyhV.js.map +0 -1
@@ -0,0 +1,193 @@
1
+ import { PciLoadError, PciModuleResolverRequiredError } from './types.js';
2
+ import { getSharedPciRegistry } from './registry.js';
3
+ import { DEFAULT_RESOLUTION_CONFIG_PATHS, emptyResolutionConfig, parseModuleResolutionConfig, } from './resolutionConfig.js';
4
+ import { createAmdLoader } from './amdLoader.js';
5
+ const DEFAULT_REGISTRATION_TIMEOUT_MS = 5000;
6
+ /**
7
+ * The page-realm engine: the host resolver evaluates the module in the page,
8
+ * the registry global observes its registration, and instantiation is a direct
9
+ * `getInstance` call. This is the behavior `PciHost` carried before the
10
+ * sandboxed engine existed, extracted behind the session seam unchanged.
11
+ */
12
+ export class PageRealmPciSession {
13
+ constructor(options) {
14
+ this.registration = null;
15
+ this.data = options.data;
16
+ this.baseUrl = options.baseUrl;
17
+ this.moduleResolver = options.moduleResolver;
18
+ this.registry = options.registry ?? getSharedPciRegistry();
19
+ this.registrationTimeoutMs = options.registrationTimeoutMs ?? DEFAULT_REGISTRATION_TIMEOUT_MS;
20
+ }
21
+ /** {@inheritdoc PciModuleSession.load} */
22
+ async load(context) {
23
+ if (!this.moduleResolver) {
24
+ throw new PciModuleResolverRequiredError(this.data.responseIdentifier, this.data.primaryPath);
25
+ }
26
+ const useAmd = this.data.modules.length > 1 || this.data.resolutionConfigPath !== undefined;
27
+ if (useAmd) {
28
+ await this.loadViaAmd(context);
29
+ return;
30
+ }
31
+ const primary = this.resolveUrl(this.data.primaryPath);
32
+ try {
33
+ await this.evaluateModule(primary, this.data.primaryPath, 'primary');
34
+ this.adoptRegistration(await this.awaitRegistration(), context);
35
+ return;
36
+ }
37
+ catch (primaryErr) {
38
+ if (!context.isCurrent())
39
+ throw primaryErr;
40
+ if (!this.data.fallbackPath) {
41
+ throw new PciLoadError(this.data.primaryPath, undefined, primaryErr);
42
+ }
43
+ }
44
+ const fallback = this.resolveUrl(this.data.fallbackPath);
45
+ try {
46
+ await this.evaluateModule(fallback, this.data.fallbackPath, 'fallback');
47
+ this.adoptRegistration(await this.awaitRegistration(), context);
48
+ }
49
+ catch (fallbackErr) {
50
+ if (!context.isCurrent())
51
+ throw fallbackErr;
52
+ throw new PciLoadError(this.data.primaryPath, this.data.fallbackPath, fallbackErr);
53
+ }
54
+ }
55
+ /** {@inheritdoc PciModuleSession.instantiate} */
56
+ instantiate(dom, configuration, state) {
57
+ if (!this.registration)
58
+ return undefined;
59
+ return this.registration.getInstance(dom, configuration, state);
60
+ }
61
+ /** {@inheritdoc PciModuleSession.destroyInstance} */
62
+ destroyInstance(instance) {
63
+ instance?.destroy?.();
64
+ }
65
+ /** {@inheritdoc PciModuleSession.dispose} */
66
+ dispose() {
67
+ this.registration = null;
68
+ }
69
+ // ---------------------------------------------------------------------------
70
+ // Private helpers
71
+ // ---------------------------------------------------------------------------
72
+ awaitRegistration() {
73
+ const typeIdentifier = this.data.customInteractionTypeIdentifier;
74
+ let timer;
75
+ const timeout = new Promise((_, reject) => {
76
+ timer = setTimeout(() => reject(new Error(`PCI module for '${typeIdentifier}' did not register`)), this.registrationTimeoutMs);
77
+ });
78
+ return Promise.race([this.registry.whenRegistered(typeIdentifier), timeout]).finally(() => {
79
+ if (timer !== undefined)
80
+ clearTimeout(timer);
81
+ });
82
+ }
83
+ evaluateModule(resolvedUrl, authoredPath, kind) {
84
+ const resolver = this.moduleResolver;
85
+ if (!resolver) {
86
+ // Unreachable through load(), which gates on the resolver first.
87
+ throw new PciModuleResolverRequiredError(this.data.responseIdentifier, authoredPath);
88
+ }
89
+ return Promise.resolve(resolver(resolvedUrl, {
90
+ authoredPath,
91
+ kind,
92
+ responseIdentifier: this.data.responseIdentifier,
93
+ customInteractionTypeIdentifier: this.data.customInteractionTypeIdentifier,
94
+ }));
95
+ }
96
+ /**
97
+ * Multi-module loading: fetch the resolution config (authored reference first,
98
+ * then the defined default locations), then drive the entry module — its
99
+ * primary path, or its fallback — through the AMD loader so `define`
100
+ * dependencies wire up before the registration is read.
101
+ */
102
+ async loadViaAmd(context) {
103
+ const entry = this.data.modules.find((module) => module.primaryPath === this.data.primaryPath) ??
104
+ this.data.modules[this.data.modules.length - 1];
105
+ const entryId = entry?.id || this.data.primaryPath;
106
+ const attempt = async (entryPath, kind) => {
107
+ const config = await this.loadResolutionConfig();
108
+ const loader = createAmdLoader({
109
+ baseUrl: this.baseUrl,
110
+ config,
111
+ evaluate: (resolvedUrl, authoredPath) => this.evaluateModule(resolvedUrl, authoredPath, kind),
112
+ resolveUrl: (path) => this.resolveUrl(path),
113
+ });
114
+ loader.install();
115
+ try {
116
+ // Authored `qti-interaction-module` entries bind their own ids; the
117
+ // resolution config fills in dependency ids the item does not declare.
118
+ // On the fallback attempt the entry id rebinds to the fallback path.
119
+ loader.addPaths(Object.fromEntries(this.data.modules
120
+ .filter((module) => module.primaryPath)
121
+ .map((module) => [module.id || module.primaryPath, module.primaryPath])));
122
+ loader.addPaths({ [entryId]: entryPath });
123
+ await loader.load([entryId]);
124
+ this.adoptRegistration(await this.awaitRegistration(), context);
125
+ }
126
+ finally {
127
+ loader.dispose();
128
+ }
129
+ };
130
+ try {
131
+ await attempt(this.data.primaryPath, 'primary');
132
+ }
133
+ catch (primaryErr) {
134
+ if (!context.isCurrent())
135
+ throw primaryErr;
136
+ const fallbackPath = entry?.fallbackPath;
137
+ if (!fallbackPath) {
138
+ throw new PciLoadError(this.data.primaryPath, undefined, primaryErr);
139
+ }
140
+ try {
141
+ await attempt(fallbackPath, 'fallback');
142
+ }
143
+ catch (fallbackErr) {
144
+ if (!context.isCurrent())
145
+ throw fallbackErr;
146
+ throw new PciLoadError(this.data.primaryPath, fallbackPath, fallbackErr);
147
+ }
148
+ }
149
+ }
150
+ /** The resolution config: the authored reference, then the defined default locations. */
151
+ async loadResolutionConfig() {
152
+ const candidates = this.data.resolutionConfigPath
153
+ ? [this.data.resolutionConfigPath, ...DEFAULT_RESOLUTION_CONFIG_PATHS]
154
+ : DEFAULT_RESOLUTION_CONFIG_PATHS;
155
+ for (const path of candidates) {
156
+ try {
157
+ const raw = await this.evaluateModule(this.resolveUrl(path), path, 'primary');
158
+ const parsed = parseModuleResolutionConfig(raw);
159
+ if (Object.keys(parsed.paths).length > 0)
160
+ return parsed;
161
+ }
162
+ catch {
163
+ // A package without a config file at this location falls through.
164
+ }
165
+ }
166
+ return emptyResolutionConfig();
167
+ }
168
+ resolveUrl(path) {
169
+ if (/^[a-z][a-z\d+.-]*:/i.test(path) || path.startsWith('//') || path.startsWith('/')) {
170
+ return path;
171
+ }
172
+ if (!this.baseUrl)
173
+ return path;
174
+ // Relative path: resolve against baseUrl
175
+ const base = this.baseUrl.endsWith('/') ? this.baseUrl : this.baseUrl + '/';
176
+ try {
177
+ return new URL(path, base).href;
178
+ }
179
+ catch {
180
+ return base + path;
181
+ }
182
+ }
183
+ adoptRegistration(registration, context) {
184
+ if (!registration || typeof registration.getInstance !== 'function') {
185
+ throw new Error(`PCI registration for '${this.data.customInteractionTypeIdentifier}' is not a valid spec registration`);
186
+ }
187
+ if (!context.isCurrent()) {
188
+ throw new Error('PciHost was destroyed before its module finished loading');
189
+ }
190
+ this.registration = registration;
191
+ }
192
+ }
193
+ //# sourceMappingURL=pageRealmSession.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pageRealmSession.js","sourceRoot":"","sources":["../../src/pci/pageRealmSession.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,YAAY,EAAE,8BAA8B,EAAE,MAAM,YAAY,CAAC;AAC1E,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EACN,+BAA+B,EAC/B,qBAAqB,EACrB,2BAA2B,GAE3B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAEjD,MAAM,+BAA+B,GAAG,IAAI,CAAC;AAc7C;;;;;GAKG;AACH,MAAM,OAAO,mBAAmB;IAQ/B,YAAY,OAAgC;QAFpC,iBAAY,GAA4C,IAAI,CAAC;QAGpE,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,cAAc,GAAG,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oadContext, PciModuleSession } from './moduleSession.js';\nimport type {\n\tExtractedPci,\n\tPciModulePathKind,\n\tPciModuleResolver,\n\tPciRegistryObservation,\n\tQtiCustomInteractionRegistration,\n\tQtiPciConfiguration,\n\tQtiPciInstance,\n} from './types.js';\nimport { PciLoadError, PciModuleResolverRequiredError } from './types.js';\nimport { getSharedPciRegistry } from './registry.js';\nimport {\n\tDEFAULT_RESOLUTION_CONFIG_PATHS,\n\temptyResolutionConfig,\n\tparseModuleResolutionConfig,\n\ttype PciResolutionConfig,\n} from './resolutionConfig.js';\nimport { createAmdLoader } from './amdLoader.js';\n\nconst DEFAULT_REGISTRATION_TIMEOUT_MS = 5000;\n\nexport interface PageRealmSessionOptions {\n\tdata: ExtractedPci;\n\tbaseUrl: string;\n\t/**\n\t * Undefined is allowed at construction so an unconfigured host can be built\n\t * and report the secure-default error at load time, as it always has.\n\t */\n\tmoduleResolver?: PciModuleResolver;\n\tregistry?: PciRegistryObservation;\n\tregistrationTimeoutMs?: number;\n}\n\n/**\n * The page-realm engine: the host resolver evaluates the module in the page,\n * the registry global observes its registration, and instantiation is a direct\n * `getInstance` call. This is the behavior `PciHost` carried before the\n * sandboxed engine existed, extracted behind the session seam unchanged.\n */\nexport class PageRealmPciSession implements PciModuleSession {\n\tprivate readonly data: ExtractedPci;\n\tprivate readonly baseUrl: string;\n\tprivate readonly moduleResolver: PciModuleResolver | undefined;\n\tprivate readonly registry: PciRegistryObservation;\n\tprivate readonly registrationTimeoutMs: number;\n\tprivate registration: QtiCustomInteractionRegistration | null = null;\n\n\tconstructor(options: PageRealmSessionOptions) {\n\t\tthis.data = options.data;\n\t\tthis.baseUrl = options.baseUrl;\n\t\tthis.moduleResolver = options.moduleResolver;\n\t\tthis.registry = options.registry ?? getSharedPciRegistry();\n\t\tthis.registrationTimeoutMs = options.registrationTimeoutMs ?? DEFAULT_REGISTRATION_TIMEOUT_MS;\n\t}\n\n\t/** {@inheritdoc PciModuleSession.load} */\n\tpublic async load(context: PciLoadContext): Promise<void> {\n\t\tif (!this.moduleResolver) {\n\t\t\tthrow new PciModuleResolverRequiredError(\n\t\t\t\tthis.data.responseIdentifier,\n\t\t\t\tthis.data.primaryPath\n\t\t\t);\n\t\t}\n\t\tconst useAmd = this.data.modules.length > 1 || this.data.resolutionConfigPath !== undefined;\n\t\tif (useAmd) {\n\t\t\tawait this.loadViaAmd(context);\n\t\t\treturn;\n\t\t}\n\n\t\tconst primary = this.resolveUrl(this.data.primaryPath);\n\t\ttry {\n\t\t\tawait this.evaluateModule(primary, this.data.primaryPath, 'primary');\n\t\t\tthis.adoptRegistration(await this.awaitRegistration(), context);\n\t\t\treturn;\n\t\t} catch (primaryErr) {\n\t\t\tif (!context.isCurrent()) throw primaryErr;\n\t\t\tif (!this.data.fallbackPath) {\n\t\t\t\tthrow new PciLoadError(this.data.primaryPath, undefined, primaryErr as Error);\n\t\t\t}\n\t\t}\n\n\t\tconst fallback = this.resolveUrl(this.data.fallbackPath!);\n\t\ttry {\n\t\t\tawait this.evaluateModule(fallback, this.data.fallbackPath!, 'fallback');\n\t\t\tthis.adoptRegistration(await this.awaitRegistration(), context);\n\t\t} catch (fallbackErr) {\n\t\t\tif (!context.isCurrent()) throw fallbackErr;\n\t\t\tthrow new PciLoadError(\n\t\t\t\tthis.data.primaryPath,\n\t\t\t\tthis.data.fallbackPath,\n\t\t\t\tfallbackErr as Error\n\t\t\t);\n\t\t}\n\t}\n\n\t/** {@inheritdoc PciModuleSession.instantiate} */\n\tpublic instantiate(\n\t\tdom: HTMLElement,\n\t\tconfiguration: QtiPciConfiguration,\n\t\tstate: unknown\n\t): QtiPciInstance | undefined {\n\t\tif (!this.registration) return undefined;\n\t\treturn this.registration.getInstance(dom, configuration, state);\n\t}\n\n\t/** {@inheritdoc PciModuleSession.destroyInstance} */\n\tpublic destroyInstance(instance: QtiPciInstance): void {\n\t\t(instance as { destroy?: () => void } | null)?.destroy?.();\n\t}\n\n\t/** {@inheritdoc PciModuleSession.dispose} */\n\tpublic dispose(): void {\n\t\tthis.registration = null;\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Private helpers\n\t// ---------------------------------------------------------------------------\n\n\tprivate awaitRegistration(): Promise<QtiCustomInteractionRegistration> {\n\t\tconst typeIdentifier = this.data.customInteractionTypeIdentifier;\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst timeout = new Promise<never>((_, reject) => {\n\t\t\ttimer = setTimeout(\n\t\t\t\t() => reject(new Error(`PCI module for '${typeIdentifier}' did not register`)),\n\t\t\t\tthis.registrationTimeoutMs\n\t\t\t);\n\t\t});\n\t\treturn Promise.race([this.registry.whenRegistered(typeIdentifier), timeout]).finally(() => {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t});\n\t}\n\n\tprivate evaluateModule(\n\t\tresolvedUrl: string,\n\t\tauthoredPath: string,\n\t\tkind: PciModulePathKind\n\t): Promise<unknown> {\n\t\tconst resolver = this.moduleResolver;\n\t\tif (!resolver) {\n\t\t\t// Unreachable through load(), which gates on the resolver first.\n\t\t\tthrow new PciModuleResolverRequiredError(this.data.responseIdentifier, authoredPath);\n\t\t}\n\t\treturn Promise.resolve(\n\t\t\tresolver(resolvedUrl, {\n\t\t\t\tauthoredPath,\n\t\t\t\tkind,\n\t\t\t\tresponseIdentifier: this.data.responseIdentifier,\n\t\t\t\tcustomInteractionTypeIdentifier: this.data.customInteractionTypeIdentifier,\n\t\t\t})\n\t\t);\n\t}\n\n\t/**\n\t * Multi-module loading: fetch the resolution config (authored reference first,\n\t * then the defined default locations), then drive the entry module — its\n\t * primary path, or its fallback — through the AMD loader so `define`\n\t * dependencies wire up before the registration is read.\n\t */\n\tprivate async loadViaAmd(context: PciLoadContext): Promise<void> {\n\t\tconst entry =\n\t\t\tthis.data.modules.find((module) => module.primaryPath === this.data.primaryPath) ??\n\t\t\tthis.data.modules[this.data.modules.length - 1];\n\t\tconst entryId = entry?.id || this.data.primaryPath;\n\t\tconst attempt = async (entryPath: string, kind: PciModulePathKind): Promise<void> => {\n\t\t\tconst config = await this.loadResolutionConfig();\n\t\t\tconst loader = createAmdLoader({\n\t\t\t\tbaseUrl: this.baseUrl,\n\t\t\t\tconfig,\n\t\t\t\tevaluate: (resolvedUrl, authoredPath) => this.evaluateModule(resolvedUrl, authoredPath, kind),\n\t\t\t\tresolveUrl: (path) => this.resolveUrl(path),\n\t\t\t});\n\t\t\tloader.install();\n\t\t\ttry {\n\t\t\t\t// Authored `qti-interaction-module` entries bind their own ids; the\n\t\t\t\t// resolution config fills in dependency ids the item does not declare.\n\t\t\t\t// On the fallback attempt the entry id rebinds to the fallback path.\n\t\t\t\tloader.addPaths(\n\t\t\t\t\tObject.fromEntries(\n\t\t\t\t\t\tthis.data.modules\n\t\t\t\t\t\t\t.filter((module) => module.primaryPath)\n\t\t\t\t\t\t\t.map((module) => [module.id || module.primaryPath, module.primaryPath])\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t\tloader.addPaths({ [entryId]: entryPath });\n\t\t\t\tawait loader.load([entryId]);\n\t\t\t\tthis.adoptRegistration(await this.awaitRegistration(), context);\n\t\t\t} finally {\n\t\t\t\tloader.dispose();\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tawait attempt(this.data.primaryPath, 'primary');\n\t\t} catch (primaryErr) {\n\t\t\tif (!context.isCurrent()) throw primaryErr;\n\t\t\tconst fallbackPath = entry?.fallbackPath;\n\t\t\tif (!fallbackPath) {\n\t\t\t\tthrow new PciLoadError(\n\t\t\t\t\tthis.data.primaryPath,\n\t\t\t\t\tundefined,\n\t\t\t\t\tprimaryErr as Error\n\t\t\t\t);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait attempt(fallbackPath, 'fallback');\n\t\t\t} catch (fallbackErr) {\n\t\t\t\tif (!context.isCurrent()) throw fallbackErr;\n\t\t\t\tthrow new PciLoadError(\n\t\t\t\t\tthis.data.primaryPath,\n\t\t\t\t\tfallbackPath,\n\t\t\t\t\tfallbackErr as Error\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The resolution config: the authored reference, then the defined default locations. */\n\tprivate async loadResolutionConfig(): Promise<PciResolutionConfig> {\n\t\tconst candidates = this.data.resolutionConfigPath\n\t\t\t? [this.data.resolutionConfigPath, ...DEFAULT_RESOLUTION_CONFIG_PATHS]\n\t\t\t: DEFAULT_RESOLUTION_CONFIG_PATHS;\n\t\tfor (const path of candidates) {\n\t\t\ttry {\n\t\t\t\tconst raw = await this.evaluateModule(this.resolveUrl(path), path, 'primary');\n\t\t\t\tconst parsed = parseModuleResolutionConfig(raw);\n\t\t\t\tif (Object.keys(parsed.paths).length > 0) return parsed;\n\t\t\t} catch {\n\t\t\t\t// A package without a config file at this location falls through.\n\t\t\t}\n\t\t}\n\t\treturn emptyResolutionConfig();\n\t}\n\n\tprivate resolveUrl(path: string): string {\n\t\tif (/^[a-z][a-z\\d+.-]*:/i.test(path) || path.startsWith('//') || path.startsWith('/')) {\n\t\t\treturn path;\n\t\t}\n\t\tif (!this.baseUrl) return path;\n\t\t// Relative path: resolve against baseUrl\n\t\tconst base = this.baseUrl.endsWith('/') ? this.baseUrl : this.baseUrl + '/';\n\t\ttry {\n\t\t\treturn new URL(path, base).href;\n\t\t} catch {\n\t\t\treturn base + path;\n\t\t}\n\t}\n\n\tprivate adoptRegistration(\n\t\tregistration: QtiCustomInteractionRegistration,\n\t\tcontext: PciLoadContext\n\t): void {\n\t\tif (!registration || typeof registration.getInstance !== 'function') {\n\t\t\tthrow new Error(\n\t\t\t\t`PCI registration for '${this.data.customInteractionTypeIdentifier}' is not a valid spec registration`\n\t\t\t);\n\t\t}\n\t\tif (!context.isCurrent()) {\n\t\t\tthrow new Error('PciHost was destroyed before its module finished loading');\n\t\t}\n\t\tthis.registration = registration;\n\t}\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { BaseType, Cardinality } from '@pie-qti/qti-processing';
2
+ /** A runtime value as QTI variable JSON. `null`/`undefined` stay null. */
3
+ export declare function toQtiVariableJson(value: unknown, baseType: BaseType | undefined, cardinality: Cardinality): unknown;
4
+ /** QTI variable JSON as the player's runtime value; anything else passes through. */
5
+ export declare function fromQtiVariableJson(json: unknown): unknown;
6
+ /** Guard for config sources: only QTI base-type names are kept as-is. */
7
+ export declare function isKnownBaseType(value: string | undefined): value is BaseType;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * QTI variable JSON at the PCI runtime boundary (QTI 3.0 §6.1).
3
+ *
4
+ * A PCI module's `getResponse()` and the `state` seeded at `getInstance` use the QTI
5
+ * variable JSON binding: `{"base":{"identifier":"A"}}` for single cardinality,
6
+ * `{"list":{"identifier":["A","B"]}}` for multiple/ordered, and `{"record":{...}}` for
7
+ * records, each field its own variable JSON value. The player's runtime values are
8
+ * plain — these two functions are the whole translation.
9
+ */
10
+ const KNOWN_BASE_TYPES = new Set([
11
+ 'boolean',
12
+ 'integer',
13
+ 'float',
14
+ 'string',
15
+ 'identifier',
16
+ 'uri',
17
+ 'pair',
18
+ 'directedPair',
19
+ 'point',
20
+ 'duration',
21
+ 'file',
22
+ ]);
23
+ /** A runtime value as QTI variable JSON. `null`/`undefined` stay null. */
24
+ export function toQtiVariableJson(value, baseType, cardinality) {
25
+ if (value === null || value === undefined)
26
+ return null;
27
+ if (cardinality === 'record') {
28
+ if (typeof value !== 'object' || Array.isArray(value))
29
+ return null;
30
+ const record = {};
31
+ for (const [key, fieldValue] of Object.entries(value)) {
32
+ record[key] = toQtiVariableJson(fieldValue, inferBaseType(fieldValue), 'single');
33
+ }
34
+ return { record };
35
+ }
36
+ const type = baseType ?? inferBaseType(value) ?? 'string';
37
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
38
+ const list = Array.isArray(value) ? value : [value];
39
+ return { list: { [type]: list } };
40
+ }
41
+ return { base: { [type]: value } };
42
+ }
43
+ /** QTI variable JSON as the player's runtime value; anything else passes through. */
44
+ export function fromQtiVariableJson(json) {
45
+ if (json === null || json === undefined)
46
+ return null;
47
+ if (typeof json !== 'object' || Array.isArray(json))
48
+ return json;
49
+ const container = json;
50
+ if ('base' in container) {
51
+ const base = container.base;
52
+ if (typeof base !== 'object' || base === null)
53
+ return null;
54
+ const values = Object.values(base);
55
+ return values.length === 1 ? values[0] : null;
56
+ }
57
+ if ('list' in container) {
58
+ const list = container.list;
59
+ if (typeof list !== 'object' || list === null)
60
+ return null;
61
+ const values = Object.values(list);
62
+ return values.length === 1 && Array.isArray(values[0]) ? values[0] : null;
63
+ }
64
+ if ('record' in container) {
65
+ const record = container.record;
66
+ if (typeof record !== 'object' || record === null)
67
+ return null;
68
+ const fields = {};
69
+ for (const [key, fieldValue] of Object.entries(record)) {
70
+ fields[key] = fromQtiVariableJson(fieldValue);
71
+ }
72
+ return fields;
73
+ }
74
+ return json;
75
+ }
76
+ /** A plain runtime value's QTI base-type name, when its JavaScript type says one. */
77
+ function inferBaseType(value) {
78
+ switch (typeof value) {
79
+ case 'boolean':
80
+ return 'boolean';
81
+ case 'number':
82
+ return Number.isInteger(value) ? 'integer' : 'float';
83
+ case 'string':
84
+ return 'string';
85
+ default:
86
+ return undefined;
87
+ }
88
+ }
89
+ /** Guard for config sources: only QTI base-type names are kept as-is. */
90
+ export function isKnownBaseType(value) {
91
+ return typeof value === 'string' && KNOWN_BASE_TYPES.has(value);
92
+ }
93
+ //# sourceMappingURL=qtiVariableJson.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"qtiVariableJson.js","sourceRoot":"","sources":["../../src/pci/qtiVariableJson.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AAEH,MAAM,gBAAgB,GAAwB,IAAI,GAAG,CAAC;IACrD,SAAS;IACT,SAAS;IACT,OAAO;IACP,QAAQ;IACR,YAAY;IACZ,KAAK;IACL,MAAM;IACN,cAAc;IACd,OAAO;IACP,UAAU;IACV,MAAM;CACN,CAAC,CAAC;AAEH,0EAA0E;AAC1E,MAAM,UAAU,iBAAiB,CAChC,KAAc,EACd,QAA8B,EAC9B,WAAwB;IAExB,IAAI,KAAK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AC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC;AAED,qFAAqF;AACrF,SAAS,aAAa,CAAC,KAAc;IACpC,QAAQ,OAAO,KAAK,EAAE,CAAC;QACtB,KAAK,SAAS;YACb,OAAO,SAAS,CAAC;QAClB,KAAK,QAAQ;YACZ,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC;QACtD,KAAK,QAAQ;YACZ,OAAO,QAAQ,CAAC;QACjB;YACC,OAAO,SAAS,CAAC;IACnB,CAAC;AACF,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,eAAe,CAAC,KAAyB;IACxD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import type { BaseType, Cardinality } from '@pie-qti/qti-processing';\n\n/**\n * QTI variable JSON at the PCI runtime boundary (QTI 3.0 §6.1).\n *\n * A PCI module's `getResponse()` and the `state` seeded at `getInstance` use the QTI\n * variable JSON binding: `{\"base\":{\"identifier\":\"A\"}}` for single cardinality,\n * `{\"list\":{\"identifier\":[\"A\",\"B\"]}}` for multiple/ordered, and `{\"record\":{...}}` for\n * records, each field its own variable JSON value. The player's runtime values are\n * plain — these two functions are the whole translation.\n */\n\nconst KNOWN_BASE_TYPES: ReadonlySet<string> = new Set([\n\t'boolean',\n\t'integer',\n\t'float',\n\t'string',\n\t'identifier',\n\t'uri',\n\t'pair',\n\t'directedPair',\n\t'point',\n\t'duration',\n\t'file',\n]);\n\n/** A runtime value as QTI variable JSON. `null`/`undefined` stay null. */\nexport function toQtiVariableJson(\n\tvalue: unknown,\n\tbaseType: BaseType | undefined,\n\tcardinality: Cardinality\n): unknown {\n\tif (value === null || value === undefined) return null;\n\tif (cardinality === 'record') {\n\t\tif (typeof value !== 'object' || Array.isArray(value)) return null;\n\t\tconst record: Record<string, unknown> = {};\n\t\tfor (const [key, fieldValue] of Object.entries(value as Record<string, unknown>)) {\n\t\t\trecord[key] = toQtiVariableJson(fieldValue, inferBaseType(fieldValue), 'single');\n\t\t}\n\t\treturn { record };\n\t}\n\tconst type = baseType ?? inferBaseType(value) ?? 'string';\n\tif (cardinality === 'multiple' || cardinality === 'ordered') {\n\t\tconst list = Array.isArray(value) ? value : [value];\n\t\treturn { list: { [type]: list } };\n\t}\n\treturn { base: { [type]: value } };\n}\n\n/** QTI variable JSON as the player's runtime value; anything else passes through. */\nexport function fromQtiVariableJson(json: unknown): unknown {\n\tif (json === null || json === undefined) return null;\n\tif (typeof json !== 'object' || Array.isArray(json)) return json;\n\tconst container = json as Record<string, unknown>;\n\tif ('base' in container) {\n\t\tconst base = container.base;\n\t\tif (typeof base !== 'object' || base === null) return null;\n\t\tconst values = Object.values(base as Record<string, unknown>);\n\t\treturn values.length === 1 ? values[0] : null;\n\t}\n\tif ('list' in container) {\n\t\tconst list = container.list;\n\t\tif (typeof list !== 'object' || list === null) return null;\n\t\tconst values = Object.values(list as Record<string, unknown>);\n\t\treturn values.length === 1 && Array.isArray(values[0]) ? values[0] : null;\n\t}\n\tif ('record' in container) {\n\t\tconst record = container.record;\n\t\tif (typeof record !== 'object' || record === null) return null;\n\t\tconst fields: Record<string, unknown> = {};\n\t\tfor (const [key, fieldValue] of Object.entries(record as Record<string, unknown>)) {\n\t\t\tfields[key] = fromQtiVariableJson(fieldValue);\n\t\t}\n\t\treturn fields;\n\t}\n\treturn json;\n}\n\n/** A plain runtime value's QTI base-type name, when its JavaScript type says one. */\nfunction inferBaseType(value: unknown): BaseType | undefined {\n\tswitch (typeof value) {\n\t\tcase 'boolean':\n\t\t\treturn 'boolean';\n\t\tcase 'number':\n\t\t\treturn Number.isInteger(value) ? 'integer' : 'float';\n\t\tcase 'string':\n\t\t\treturn 'string';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/** Guard for config sources: only QTI base-type names are kept as-is. */\nexport function isKnownBaseType(value: string | undefined): value is BaseType {\n\treturn typeof value === 'string' && KNOWN_BASE_TYPES.has(value);\n}\n"]}
@@ -0,0 +1,15 @@
1
+ import type { PciRegistryObservation } from './types.js';
2
+ /** The global name QTI 3.0 §6.1 reserves for the PCI registry. */
3
+ export declare const PCI_REGISTRY_GLOBAL = "qtiCustomInteractionContext";
4
+ /**
5
+ * Install the page's `qtiCustomInteractionContext` and observe registrations.
6
+ *
7
+ * Conformant modules register as a side effect of their evaluation, so the runtime
8
+ * installs the registry global before the host resolver evaluates a module and reads
9
+ * the registration afterward. A context that already exists is preserved: registrations
10
+ * made through it keep working, and new registrations land in both — one PCI
11
+ * coordinator per page remains the sane assumption, but an existing global is never
12
+ * broken by the player's install.
13
+ */
14
+ export declare function installPciRegistry(target?: object): PciRegistryObservation;
15
+ export declare function getSharedPciRegistry(): PciRegistryObservation;
@@ -0,0 +1,77 @@
1
+ /** The global name QTI 3.0 §6.1 reserves for the PCI registry. */
2
+ export const PCI_REGISTRY_GLOBAL = 'qtiCustomInteractionContext';
3
+ /**
4
+ * Install the page's `qtiCustomInteractionContext` and observe registrations.
5
+ *
6
+ * Conformant modules register as a side effect of their evaluation, so the runtime
7
+ * installs the registry global before the host resolver evaluates a module and reads
8
+ * the registration afterward. A context that already exists is preserved: registrations
9
+ * made through it keep working, and new registrations land in both — one PCI
10
+ * coordinator per page remains the sane assumption, but an existing global is never
11
+ * broken by the player's install.
12
+ */
13
+ export function installPciRegistry(target = globalThis) {
14
+ const host = target;
15
+ const registrations = new Map();
16
+ const pending = new Map();
17
+ const register = (registration) => {
18
+ if (!registration || typeof registration.getInstance !== 'function')
19
+ return;
20
+ const typeIdentifier = registration.typeIdentifier;
21
+ if (typeof typeIdentifier !== 'string' || typeIdentifier.length === 0)
22
+ return;
23
+ registrations.set(typeIdentifier, registration);
24
+ const waiters = pending.get(typeIdentifier);
25
+ if (waiters) {
26
+ pending.delete(typeIdentifier);
27
+ for (const waiter of waiters)
28
+ waiter(registration);
29
+ }
30
+ };
31
+ const previous = host[PCI_REGISTRY_GLOBAL];
32
+ if (previous && typeof previous.register === 'function') {
33
+ const previousRegister = previous.register.bind(previous);
34
+ host[PCI_REGISTRY_GLOBAL] = {
35
+ register: (registration) => {
36
+ register(registration);
37
+ // A context installed before ours may keep its own bookkeeping.
38
+ try {
39
+ previousRegister(registration);
40
+ }
41
+ catch {
42
+ // The observer's job is to see the registration, not to police another
43
+ // context's reaction to it.
44
+ }
45
+ },
46
+ };
47
+ }
48
+ else {
49
+ const context = { register };
50
+ host[PCI_REGISTRY_GLOBAL] = context;
51
+ }
52
+ return {
53
+ whenRegistered(typeIdentifier) {
54
+ const known = registrations.get(typeIdentifier);
55
+ if (known)
56
+ return Promise.resolve(known);
57
+ return new Promise((resolve) => {
58
+ const waiters = pending.get(typeIdentifier) ?? new Set();
59
+ waiters.add(resolve);
60
+ pending.set(typeIdentifier, waiters);
61
+ });
62
+ },
63
+ registeredTypes() {
64
+ return [...registrations.keys()];
65
+ },
66
+ dispose() {
67
+ pending.clear();
68
+ },
69
+ };
70
+ }
71
+ /** The process-wide observation every PciHost uses unless it is given one. */
72
+ let sharedObservation;
73
+ export function getSharedPciRegistry() {
74
+ sharedObservation ?? (sharedObservation = installPciRegistry(globalThis));
75
+ return sharedObservation;
76
+ }
77
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["../../src/pci/registry.ts"],"names":[],"mappings":"AAMA,kEAAkE;AAClE,MAAM,CAAC,MAAM,mBAAmB,GAAG,6BAA6B,CAAC;AAMjE;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAAiB,UAAU;IAC7D,MAAM,IAAI,GAAG,MAAsB,CAAC;IACpC,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC1E,MAAM,OAAO,GAAG,IAAI,GAAG,EAAyE,CAAC;IAEjG,MAAM,QAAQ,GAA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AAc;YAC5B,MAAM,KAAK,GAAG,aAAa,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;YAChD,IAAI,KAAK;gBAAE,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACzC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;gBAC9B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC;gBACzD,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;gBACrB,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;YACtC,CAAC,CAAC,CAAC;QACJ,CAAC;QACD,eAAe;YACd,OAAO,CAAC,GAAG,aAAa,CAAC,IAAI,EAAE,CAAC,CAAC;QAClC,CAAC;QACD,OAAO;YACN,OAAO,CAAC,KAAK,EAAE,CAAC;QACjB,CAAC;KACD,CAAC;AACH,CAAC;AAED,8EAA8E;AAC9E,IAAI,iBAAqD,CAAC;AAE1D,MAAM,UAAU,oBAAoB;IACnC,iBAAiB,KAAjB,iBAAiB,GAAK,kBAAkB,CAAC,UAAU,CAAC,EAAC;IACrD,OAAO,iBAAiB,CAAC;AAC1B,CAAC","sourcesContent":["import type {\n\tPciCustomInteractionContext,\n\tPciRegistryObservation,\n\tQtiCustomInteractionRegistration,\n} from './types.js';\n\n/** The global name QTI 3.0 §6.1 reserves for the PCI registry. */\nexport const PCI_REGISTRY_GLOBAL = 'qtiCustomInteractionContext';\n\ninterface RegistryHost {\n\t[PCI_REGISTRY_GLOBAL]?: PciCustomInteractionContext;\n}\n\n/**\n * Install the page's `qtiCustomInteractionContext` and observe registrations.\n *\n * Conformant modules register as a side effect of their evaluation, so the runtime\n * installs the registry global before the host resolver evaluates a module and reads\n * the registration afterward. A context that already exists is preserved: registrations\n * made through it keep working, and new registrations land in both — one PCI\n * coordinator per page remains the sane assumption, but an existing global is never\n * broken by the player's install.\n */\nexport function installPciRegistry(target: object = globalThis): PciRegistryObservation {\n\tconst host = target as RegistryHost;\n\tconst registrations = new Map<string, QtiCustomInteractionRegistration>();\n\tconst pending = new Map<string, Set<(registration: QtiCustomInteractionRegistration) => void>>();\n\n\tconst register = (registration: QtiCustomInteractionRegistration): void => {\n\t\tif (!registration || typeof registration.getInstance !== 'function') return;\n\t\tconst typeIdentifier = registration.typeIdentifier;\n\t\tif (typeof typeIdentifier !== 'string' || typeIdentifier.length === 0) return;\n\t\tregistrations.set(typeIdentifier, registration);\n\t\tconst waiters = pending.get(typeIdentifier);\n\t\tif (waiters) {\n\t\t\tpending.delete(typeIdentifier);\n\t\t\tfor (const waiter of waiters) waiter(registration);\n\t\t}\n\t};\n\n\tconst previous = host[PCI_REGISTRY_GLOBAL];\n\tif (previous && typeof previous.register === 'function') {\n\t\tconst previousRegister = previous.register.bind(previous);\n\t\thost[PCI_REGISTRY_GLOBAL] = {\n\t\t\tregister: (registration) => {\n\t\t\t\tregister(registration);\n\t\t\t\t// A context installed before ours may keep its own bookkeeping.\n\t\t\t\ttry {\n\t\t\t\t\tpreviousRegister(registration);\n\t\t\t\t} catch {\n\t\t\t\t\t// The observer's job is to see the registration, not to police another\n\t\t\t\t\t// context's reaction to it.\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t} else {\n\t\tconst context: PciCustomInteractionContext = { register };\n\t\thost[PCI_REGISTRY_GLOBAL] = context;\n\t}\n\n\treturn {\n\t\twhenRegistered(typeIdentifier) {\n\t\t\tconst known = registrations.get(typeIdentifier);\n\t\t\tif (known) return Promise.resolve(known);\n\t\t\treturn new Promise((resolve) => {\n\t\t\t\tconst waiters = pending.get(typeIdentifier) ?? new Set();\n\t\t\t\twaiters.add(resolve);\n\t\t\t\tpending.set(typeIdentifier, waiters);\n\t\t\t});\n\t\t},\n\t\tregisteredTypes() {\n\t\t\treturn [...registrations.keys()];\n\t\t},\n\t\tdispose() {\n\t\t\tpending.clear();\n\t\t},\n\t};\n}\n\n/** The process-wide observation every PciHost uses unless it is given one. */\nlet sharedObservation: PciRegistryObservation | undefined;\n\nexport function getSharedPciRegistry(): PciRegistryObservation {\n\tsharedObservation ??= installPciRegistry(globalThis);\n\treturn sharedObservation;\n}\n"]}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The module resolution config format the QTI 3.0 PCI specification borrows from
3
+ * RequireJS: a `paths` map of module id to path (or list of paths, of which the
4
+ * first is primary), optional `shim` declarations for scripts that are not AMD,
5
+ * `waitSeconds` and `urlArgs`. The spec's default locations under the package base
6
+ * URL are `modules/module_resolution.js`, with `modules/fallback_module_resolution.js`
7
+ * as the defined fallback-resolution path — both are JSON despite the `.js` names.
8
+ */
9
+ export interface PciResolutionShim {
10
+ deps?: string[];
11
+ exports?: string;
12
+ }
13
+ export interface PciResolutionConfig {
14
+ waitSeconds?: number;
15
+ urlArgs?: string;
16
+ paths: Record<string, string>;
17
+ shim: Record<string, PciResolutionShim>;
18
+ }
19
+ /** The defined default config locations, in order, relative to the package base URL. */
20
+ export declare const DEFAULT_RESOLUTION_CONFIG_PATHS: readonly string[];
21
+ export declare function emptyResolutionConfig(): PciResolutionConfig;
22
+ /** A resolution config object from fetched content; anything unparseable is empty. */
23
+ export declare function parseModuleResolutionConfig(source: unknown): PciResolutionConfig;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The module resolution config format the QTI 3.0 PCI specification borrows from
3
+ * RequireJS: a `paths` map of module id to path (or list of paths, of which the
4
+ * first is primary), optional `shim` declarations for scripts that are not AMD,
5
+ * `waitSeconds` and `urlArgs`. The spec's default locations under the package base
6
+ * URL are `modules/module_resolution.js`, with `modules/fallback_module_resolution.js`
7
+ * as the defined fallback-resolution path — both are JSON despite the `.js` names.
8
+ */
9
+ /** The defined default config locations, in order, relative to the package base URL. */
10
+ export const DEFAULT_RESOLUTION_CONFIG_PATHS = [
11
+ 'modules/module_resolution.js',
12
+ 'modules/fallback_module_resolution.js',
13
+ ];
14
+ export function emptyResolutionConfig() {
15
+ return { paths: {}, shim: {} };
16
+ }
17
+ /** A resolution config object from fetched content; anything unparseable is empty. */
18
+ export function parseModuleResolutionConfig(source) {
19
+ if (typeof source === 'string') {
20
+ try {
21
+ return parseModuleResolutionConfig(JSON.parse(source));
22
+ }
23
+ catch {
24
+ return emptyResolutionConfig();
25
+ }
26
+ }
27
+ if (typeof source !== 'object' || source === null || Array.isArray(source)) {
28
+ return emptyResolutionConfig();
29
+ }
30
+ const raw = source;
31
+ const config = emptyResolutionConfig();
32
+ if (typeof raw.waitSeconds === 'number' && Number.isFinite(raw.waitSeconds)) {
33
+ config.waitSeconds = raw.waitSeconds;
34
+ }
35
+ if (typeof raw.urlArgs === 'string' && raw.urlArgs)
36
+ config.urlArgs = raw.urlArgs;
37
+ if (typeof raw.paths === 'object' && raw.paths !== null && !Array.isArray(raw.paths)) {
38
+ for (const [id, path] of Object.entries(raw.paths)) {
39
+ const primary = Array.isArray(path) ? path[0] : path;
40
+ if (typeof id === 'string' && id && typeof primary === 'string' && primary) {
41
+ config.paths[id] = primary;
42
+ }
43
+ }
44
+ }
45
+ if (typeof raw.shim === 'object' && raw.shim !== null && !Array.isArray(raw.shim)) {
46
+ for (const [id, shim] of Object.entries(raw.shim)) {
47
+ if (typeof id !== 'string' || !id || typeof shim !== 'object' || shim === null)
48
+ continue;
49
+ const entry = shim;
50
+ const resolved = {};
51
+ if (Array.isArray(entry.deps)) {
52
+ const deps = entry.deps.filter((dep) => typeof dep === 'string');
53
+ if (deps.length > 0)
54
+ resolved.deps = deps;
55
+ }
56
+ if (typeof entry.exports === 'string' && entry.exports)
57
+ resolved.exports = entry.exports;
58
+ config.shim[id] = resolved;
59
+ }
60
+ }
61
+ return config;
62
+ }
63
+ //# sourceMappingURL=resolutionConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolutionConfig.js","sourceRoot":"","sources":["../../src/pci/resolutionConfig.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAcH,wFAAwF;AACxF,MAAM,CAAC,MAAM,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E,QAAQ,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;YACzF,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC;QAC5B,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * The module resolution config format the QTI 3.0 PCI specification borrows from\n * RequireJS: a `paths` map of module id to path (or list of paths, of which the\n * first is primary), optional `shim` declarations for scripts that are not AMD,\n * `waitSeconds` and `urlArgs`. The spec's default locations under the package base\n * URL are `modules/module_resolution.js`, with `modules/fallback_module_resolution.js`\n * as the defined fallback-resolution path — both are JSON despite the `.js` names.\n */\n\nexport interface PciResolutionShim {\n\tdeps?: string[];\n\texports?: string;\n}\n\nexport interface PciResolutionConfig {\n\twaitSeconds?: number;\n\turlArgs?: string;\n\tpaths: Record<string, string>;\n\tshim: Record<string, PciResolutionShim>;\n}\n\n/** The defined default config locations, in order, relative to the package base URL. */\nexport const DEFAULT_RESOLUTION_CONFIG_PATHS: readonly string[] = [\n\t'modules/module_resolution.js',\n\t'modules/fallback_module_resolution.js',\n];\n\nexport function emptyResolutionConfig(): PciResolutionConfig {\n\treturn { paths: {}, shim: {} };\n}\n\n/** A resolution config object from fetched content; anything unparseable is empty. */\nexport function parseModuleResolutionConfig(source: unknown): PciResolutionConfig {\n\tif (typeof source === 'string') {\n\t\ttry {\n\t\t\treturn parseModuleResolutionConfig(JSON.parse(source));\n\t\t} catch {\n\t\t\treturn emptyResolutionConfig();\n\t\t}\n\t}\n\tif (typeof source !== 'object' || source === null || Array.isArray(source)) {\n\t\treturn emptyResolutionConfig();\n\t}\n\tconst raw = source as Record<string, unknown>;\n\tconst config = emptyResolutionConfig();\n\tif (typeof raw.waitSeconds === 'number' && Number.isFinite(raw.waitSeconds)) {\n\t\tconfig.waitSeconds = raw.waitSeconds;\n\t}\n\tif (typeof raw.urlArgs === 'string' && raw.urlArgs) config.urlArgs = raw.urlArgs;\n\tif (typeof raw.paths === 'object' && raw.paths !== null && !Array.isArray(raw.paths)) {\n\t\tfor (const [id, path] of Object.entries(raw.paths as Record<string, unknown>)) {\n\t\t\tconst primary = Array.isArray(path) ? path[0] : path;\n\t\t\tif (typeof id === 'string' && id && typeof primary === 'string' && primary) {\n\t\t\t\tconfig.paths[id] = primary;\n\t\t\t}\n\t\t}\n\t}\n\tif (typeof raw.shim === 'object' && raw.shim !== null && !Array.isArray(raw.shim)) {\n\t\tfor (const [id, shim] of Object.entries(raw.shim as Record<string, unknown>)) {\n\t\t\tif (typeof id !== 'string' || !id || typeof shim !== 'object' || shim === null) continue;\n\t\t\tconst entry = shim as Record<string, unknown>;\n\t\t\tconst resolved: PciResolutionShim = {};\n\t\t\tif (Array.isArray(entry.deps)) {\n\t\t\t\tconst deps = entry.deps.filter((dep): dep is string => typeof dep === 'string');\n\t\t\t\tif (deps.length > 0) resolved.deps = deps;\n\t\t\t}\n\t\t\tif (typeof entry.exports === 'string' && entry.exports) resolved.exports = entry.exports;\n\t\t\tconfig.shim[id] = resolved;\n\t\t}\n\t}\n\treturn config;\n}\n"]}
@@ -0,0 +1,78 @@
1
+ import type { PciLoadContext, PciModuleSession } from '../moduleSession.js';
2
+ import type { ExtractedPci, PciFrameConnector, PciModulePolicy, PciSandboxConfiguration, QtiPciConfiguration, QtiPciInstance } from '../types.js';
3
+ export interface SandboxedSessionOptions {
4
+ sandbox: PciSandboxConfiguration;
5
+ data: ExtractedPci;
6
+ baseUrl: string;
7
+ /** Policy gate applied to module URLs before anything is handed to the frame. */
8
+ modulePolicy?: PciModulePolicy;
9
+ /** The page origin the runner locks to; injectable for tests. */
10
+ parentOrigin?: () => string;
11
+ /** Frame connection factory; defaults to a real sandboxed iframe. */
12
+ frameConnector?: PciFrameConnector;
13
+ }
14
+ type RemoteReportHandler = (report: {
15
+ state?: unknown;
16
+ }) => void;
17
+ type ErrorHandler = (error: Error) => void;
18
+ /**
19
+ * The sandboxed engine: the module runs in a cross-origin runner frame
20
+ * (`@pie-qti/pci-runner` deployed on a cookieless origin) and every contract
21
+ * call crosses the postMessage bridge.
22
+ *
23
+ * Nothing here evaluates module code. Module URLs are resolved against the
24
+ * package base, checked against the optional policy, and handed to the runner,
25
+ * which loads them in its own opaque-origin document. `getResponse()` stays
26
+ * synchronous for `PciHost` by answering from a cache the runner maintains:
27
+ * pushes on every observed change, plus a bounded poll as the freshness floor.
28
+ */
29
+ export declare class SandboxedPciSession implements PciModuleSession {
30
+ private readonly runnerUrl;
31
+ private readonly handshakeTimeoutMs;
32
+ private readonly pollIntervalMs;
33
+ private readonly registrationTimeoutMs;
34
+ private readonly data;
35
+ private readonly baseUrl;
36
+ private readonly modulePolicy;
37
+ private readonly parentOrigin;
38
+ private readonly connector;
39
+ private connection;
40
+ private pendingInit;
41
+ private handshook;
42
+ private moduleReady;
43
+ private handshakeTimer;
44
+ private queuedInstantiate;
45
+ private currentConfiguration;
46
+ /** The proxy `PciHost`'s state machine talks to; reads answer from the cache. */
47
+ private proxy;
48
+ private readonly cache;
49
+ private readonly reportHandlers;
50
+ private readonly errorHandlers;
51
+ private stopMessages;
52
+ private disposed;
53
+ constructor(options: SandboxedSessionOptions);
54
+ /** {@inheritdoc PciModuleSession.load} */
55
+ load(_context: PciLoadContext): Promise<void>;
56
+ /** {@inheritdoc PciModuleSession.instantiate} */
57
+ instantiate(dom: HTMLElement, configuration: QtiPciConfiguration, state: unknown): QtiPciInstance | undefined;
58
+ /** {@inheritdoc PciModuleSession.destroyInstance} */
59
+ destroyInstance(_instance: QtiPciInstance): void;
60
+ /** {@inheritdoc PciModuleSession.dispose} */
61
+ dispose(): void;
62
+ /** {@inheritdoc PciModuleSession.onRemoteReport} */
63
+ onRemoteReport(handler: RemoteReportHandler): () => void;
64
+ /** {@inheritdoc PciModuleSession.onError} */
65
+ onError(handler: ErrorHandler): () => void;
66
+ private buildInitPayload;
67
+ /** Resolve one authored path and run the policy gate on the absolute URL. */
68
+ private resolveChecked;
69
+ private resolveUrl;
70
+ private post;
71
+ private resetConnection;
72
+ private armHandshakeTimeout;
73
+ private emitError;
74
+ private handleMessage;
75
+ /** Take a bridge snapshot into the cache the proxy reads from. */
76
+ private applySnapshot;
77
+ }
78
+ export {};