gdc-sdk-client-ts 1.0.3 → 1.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 (318) hide show
  1. package/README.md +8 -9
  2. package/dist/ClientSDK.d.ts +56 -0
  3. package/dist/ClientSDK.js +202 -0
  4. package/dist/JobManager.d.ts +39 -0
  5. package/dist/JobManager.js +258 -0
  6. package/dist/ProfileManager.d.ts +72 -0
  7. package/dist/ProfileManager.js +113 -0
  8. package/dist/ProfileRegistry.d.ts +14 -0
  9. package/dist/ProfileRegistry.js +38 -0
  10. package/dist/SmartTokenManager.d.ts +62 -0
  11. package/dist/SmartTokenManager.js +223 -0
  12. package/dist/VerifierService.d.ts +39 -0
  13. package/dist/VerifierService.js +116 -0
  14. package/dist/frontend-services/BaseApiService.d.ts +73 -0
  15. package/dist/frontend-services/BaseApiService.js +205 -0
  16. package/dist/frontend-services/base/BaseProfessionalService.d.ts +22 -0
  17. package/dist/frontend-services/base/BaseProfessionalService.js +44 -0
  18. package/dist/frontend-services/capabilities/AppointmentService.d.ts +29 -0
  19. package/dist/frontend-services/capabilities/AppointmentService.js +32 -0
  20. package/dist/frontend-services/capabilities/MedicationService.d.ts +25 -0
  21. package/dist/frontend-services/capabilities/MedicationService.js +62 -0
  22. package/dist/frontend-services/capabilities/TaskService.d.ts +21 -0
  23. package/dist/frontend-services/capabilities/TaskService.js +40 -0
  24. package/dist/frontend-services/common/CommonAuthService.d.ts +36 -0
  25. package/dist/frontend-services/common/CommonAuthService.js +158 -0
  26. package/dist/frontend-services/family-admin/FamilyAdminService.d.ts +39 -0
  27. package/dist/frontend-services/family-admin/FamilyAdminService.js +74 -0
  28. package/dist/frontend-services/family-admin/FamilyItService.d.ts +24 -0
  29. package/dist/frontend-services/family-admin/FamilyItService.js +34 -0
  30. package/dist/frontend-services/individual/IndividualService.d.ts +18 -0
  31. package/dist/frontend-services/individual/IndividualService.js +33 -0
  32. package/dist/frontend-services/org-admin/OrgAdminService.d.ts +56 -0
  33. package/dist/frontend-services/org-admin/OrgAdminService.js +107 -0
  34. package/dist/frontend-services/org-admin/OrgItService.d.ts +25 -0
  35. package/dist/frontend-services/org-admin/OrgItService.js +39 -0
  36. package/dist/frontend-services/professional/emergencies/ParamedicService.d.ts +12 -0
  37. package/dist/frontend-services/professional/emergencies/ParamedicService.js +15 -0
  38. package/dist/frontend-services/professional/health-care/PhysicianService.d.ts +33 -0
  39. package/dist/frontend-services/professional/health-care/PhysicianService.js +35 -0
  40. package/dist/index.d.ts +16 -0
  41. package/{src/index.ts → dist/index.js} +6 -14
  42. package/dist/interfaces/IJobManager.d.ts +23 -0
  43. package/dist/interfaces/IJobManager.js +3 -0
  44. package/{src/interfaces/IParams.ts → dist/interfaces/IParams.d.ts} +20 -29
  45. package/dist/interfaces/IParams.js +3 -0
  46. package/dist/interfaces/IProfile.d.ts +15 -0
  47. package/dist/interfaces/IProfile.js +3 -0
  48. package/{src/interfaces/ISchemaorg.ts → dist/interfaces/ISchemaorg.d.ts} +23 -115
  49. package/dist/interfaces/ISchemaorg.js +184 -0
  50. package/dist/interfaces/ISmartTokenManager.d.ts +38 -0
  51. package/dist/interfaces/ISmartTokenManager.js +3 -0
  52. package/dist/interfaces/ITrustRegistry.d.ts +39 -0
  53. package/dist/interfaces/ITrustRegistry.js +3 -0
  54. package/dist/interfaces/IVaultRepository.d.ts +35 -0
  55. package/dist/interfaces/IVaultRepository.js +14 -0
  56. package/{src/interfaces/index.ts → dist/interfaces/index.d.ts} +0 -5
  57. package/dist/interfaces/index.js +10 -0
  58. package/dist/interfaces/others.d.ts +91 -0
  59. package/dist/interfaces/others.js +3 -0
  60. package/dist/models/claims/ClaimsAllergyIntolerance.model.d.ts +51 -0
  61. package/dist/models/claims/ClaimsAllergyIntolerance.model.js +15 -0
  62. package/dist/models/claims/ClaimsBase.common.model.d.ts +32 -0
  63. package/dist/models/claims/ClaimsBase.common.model.js +14 -0
  64. package/dist/models/claims/ClaimsCondition.model.d.ts +45 -0
  65. package/dist/models/claims/ClaimsCondition.model.js +14 -0
  66. package/dist/models/claims/ClaimsConsent.model.d.ts +118 -0
  67. package/dist/models/claims/ClaimsConsent.model.js +40 -0
  68. package/dist/models/claims/ClaimsDevice.model.d.ts +79 -0
  69. package/dist/models/claims/ClaimsDevice.model.js +39 -0
  70. package/dist/models/claims/ClaimsDeviceAssociation.model.d.ts +67 -0
  71. package/dist/models/claims/ClaimsDeviceAssociation.model.js +32 -0
  72. package/dist/models/claims/ClaimsDeviceUsage.model.d.ts +77 -0
  73. package/dist/models/claims/ClaimsDeviceUsage.model.js +37 -0
  74. package/dist/models/claims/ClaimsMedicationStatement.model.d.ts +45 -0
  75. package/dist/models/claims/ClaimsMedicationStatement.model.js +14 -0
  76. package/dist/models/claims/ClaimsObservation.model.d.ts +45 -0
  77. package/dist/models/claims/ClaimsObservation.model.js +14 -0
  78. package/dist/models/claims/ClaimsRelatedPerson.model.d.ts +52 -0
  79. package/dist/models/claims/ClaimsRelatedPerson.model.js +16 -0
  80. package/{src/models/claims/index.ts → dist/models/claims/index.d.ts} +0 -4
  81. package/dist/models/claims/index.js +11 -0
  82. package/dist/models/hl7-personal-relationship.d.ts +6 -0
  83. package/dist/models/hl7-personal-relationship.js +217 -0
  84. package/{src/models/index.ts → dist/models/index.d.ts} +0 -2
  85. package/dist/models/index.js +5 -0
  86. package/dist/models/profileRegistry.d.ts +12 -0
  87. package/dist/models/profileRegistry.js +3 -0
  88. package/dist/models/roleIsco.d.ts +32 -0
  89. package/dist/models/roleIsco.js +41 -0
  90. package/dist/models/rolesHL7.d.ts +26 -0
  91. package/dist/models/rolesHL7.js +33 -0
  92. package/dist/roleRegistry.d.ts +55 -0
  93. package/dist/roleRegistry.js +77 -0
  94. package/dist/serviceSelectorRegistry.d.ts +50 -0
  95. package/dist/serviceSelectorRegistry.js +278 -0
  96. package/dist/uhc-fhir-utils-ts/models/AtcModel.d.ts +15 -0
  97. package/dist/uhc-fhir-utils-ts/models/AtcModel.js +2 -0
  98. package/dist/uhc-fhir-utils-ts/models/CommonModels.d.ts +70 -0
  99. package/dist/uhc-fhir-utils-ts/models/CommonModels.js +55 -0
  100. package/dist/uhc-fhir-utils-ts/models/DicomModels.d.ts +29 -0
  101. package/dist/uhc-fhir-utils-ts/models/DicomModels.js +2 -0
  102. package/{src/uhc-fhir-utils-ts/models/FhirModels.ts → dist/uhc-fhir-utils-ts/models/FhirModels.d.ts} +23 -33
  103. package/dist/uhc-fhir-utils-ts/models/FhirModels.js +34 -0
  104. package/dist/uhc-fhir-utils-ts/models/LoincModels.d.ts +24 -0
  105. package/dist/uhc-fhir-utils-ts/models/LoincModels.js +2 -0
  106. package/dist/uhc-fhir-utils-ts/models/SnomedModels.d.ts +13 -0
  107. package/dist/uhc-fhir-utils-ts/models/SnomedModels.js +2 -0
  108. package/{src/uhc-fhir-utils-ts/models/index.ts → dist/uhc-fhir-utils-ts/models/index.d.ts} +2 -5
  109. package/dist/uhc-fhir-utils-ts/models/index.js +8 -0
  110. package/dist/uhc-fhir-utils-ts/models/params/AdverseEvent.params.model.d.ts +14 -0
  111. package/dist/uhc-fhir-utils-ts/models/params/AdverseEvent.params.model.js +16 -0
  112. package/dist/uhc-fhir-utils-ts/models/params/AllergyIntolerance.params.model.d.ts +24 -0
  113. package/dist/uhc-fhir-utils-ts/models/params/AllergyIntolerance.params.model.js +27 -0
  114. package/dist/uhc-fhir-utils-ts/models/params/Appointment.params.model.d.ts +12 -0
  115. package/dist/uhc-fhir-utils-ts/models/params/Appointment.params.model.js +14 -0
  116. package/dist/uhc-fhir-utils-ts/models/params/ClinicalImpression.params.model.d.ts +14 -0
  117. package/dist/uhc-fhir-utils-ts/models/params/ClinicalImpression.params.model.js +15 -0
  118. package/dist/uhc-fhir-utils-ts/models/params/Condition.params.model.d.ts +16 -0
  119. package/dist/uhc-fhir-utils-ts/models/params/Condition.params.model.js +17 -0
  120. package/dist/uhc-fhir-utils-ts/models/params/DetectedIssue.params.model.d.ts +9 -0
  121. package/dist/uhc-fhir-utils-ts/models/params/DetectedIssue.params.model.js +11 -0
  122. package/dist/uhc-fhir-utils-ts/models/params/DiagnosticReport.params.model.d.ts +13 -0
  123. package/dist/uhc-fhir-utils-ts/models/params/DiagnosticReport.params.model.js +14 -0
  124. package/dist/uhc-fhir-utils-ts/models/params/Encounter.params.model.d.ts +15 -0
  125. package/dist/uhc-fhir-utils-ts/models/params/Encounter.params.model.js +17 -0
  126. package/dist/uhc-fhir-utils-ts/models/params/Immunization.params.model.d.ts +14 -0
  127. package/dist/uhc-fhir-utils-ts/models/params/Immunization.params.model.js +16 -0
  128. package/dist/uhc-fhir-utils-ts/models/params/Medication.params.model.d.ts +35 -0
  129. package/dist/uhc-fhir-utils-ts/models/params/Medication.params.model.js +45 -0
  130. package/dist/uhc-fhir-utils-ts/models/params/Observation.params.model.d.ts +320 -0
  131. package/dist/uhc-fhir-utils-ts/models/params/Observation.params.model.js +239 -0
  132. package/dist/uhc-fhir-utils-ts/models/params/Procedure.params.model.d.ts +15 -0
  133. package/dist/uhc-fhir-utils-ts/models/params/Procedure.params.model.js +17 -0
  134. package/dist/uhc-fhir-utils-ts/models/params/Search.params.model.d.ts +75 -0
  135. package/dist/uhc-fhir-utils-ts/models/params/Search.params.model.js +69 -0
  136. package/dist/uhc-fhir-utils-ts/models/params/ServiceRequest.params.model.d.ts +14 -0
  137. package/dist/uhc-fhir-utils-ts/models/params/ServiceRequest.params.model.js +16 -0
  138. package/dist/uhc-fhir-utils-ts/models/params/Specimen.params.model.d.ts +10 -0
  139. package/dist/uhc-fhir-utils-ts/models/params/Specimen.params.model.js +12 -0
  140. package/dist/uhc-fhir-utils-ts/models/params/index.d.ts +15 -0
  141. package/dist/uhc-fhir-utils-ts/models/params/index.js +15 -0
  142. package/{src/uhc-fhir-utils-ts/models/templates/AdverseEvent.template.model.ts → dist/uhc-fhir-utils-ts/models/templates/AdverseEvent.template.model.d.ts} +2 -10
  143. package/dist/uhc-fhir-utils-ts/models/templates/AdverseEvent.template.model.js +2 -0
  144. package/dist/uhc-fhir-utils-ts/models/templates/AllergyIntolerance.template.model.d.ts +24 -0
  145. package/dist/uhc-fhir-utils-ts/models/templates/AllergyIntolerance.template.model.js +1 -0
  146. package/dist/uhc-fhir-utils-ts/models/templates/Appointment.template.model.d.ts +13 -0
  147. package/dist/uhc-fhir-utils-ts/models/templates/Appointment.template.model.js +1 -0
  148. package/dist/uhc-fhir-utils-ts/models/templates/ClinicalImpression.template.model.d.ts +16 -0
  149. package/dist/uhc-fhir-utils-ts/models/templates/ClinicalImpression.template.model.js +1 -0
  150. package/dist/uhc-fhir-utils-ts/models/templates/Condition.template.model.d.ts +18 -0
  151. package/dist/uhc-fhir-utils-ts/models/templates/Condition.template.model.js +1 -0
  152. package/dist/uhc-fhir-utils-ts/models/templates/DetectedIssue.template.model.d.ts +11 -0
  153. package/dist/uhc-fhir-utils-ts/models/templates/DetectedIssue.template.model.js +1 -0
  154. package/dist/uhc-fhir-utils-ts/models/templates/DiagnosticReport.template.model.d.ts +15 -0
  155. package/dist/uhc-fhir-utils-ts/models/templates/DiagnosticReport.template.model.js +1 -0
  156. package/dist/uhc-fhir-utils-ts/models/templates/Encounter.template.model.d.ts +17 -0
  157. package/dist/uhc-fhir-utils-ts/models/templates/Encounter.template.model.js +1 -0
  158. package/dist/uhc-fhir-utils-ts/models/templates/Immunization.template.model.d.ts +18 -0
  159. package/dist/uhc-fhir-utils-ts/models/templates/Immunization.template.model.js +2 -0
  160. package/dist/uhc-fhir-utils-ts/models/templates/Medication.template.model.d.ts +37 -0
  161. package/dist/uhc-fhir-utils-ts/models/templates/Medication.template.model.js +1 -0
  162. package/dist/uhc-fhir-utils-ts/models/templates/Observation.template.model.d.ts +34 -0
  163. package/dist/uhc-fhir-utils-ts/models/templates/Observation.template.model.js +1 -0
  164. package/dist/uhc-fhir-utils-ts/models/templates/Procedure.template.model.d.ts +17 -0
  165. package/dist/uhc-fhir-utils-ts/models/templates/Procedure.template.model.js +1 -0
  166. package/dist/uhc-fhir-utils-ts/models/templates/ServiceRequest.template.model.d.ts +16 -0
  167. package/dist/uhc-fhir-utils-ts/models/templates/ServiceRequest.template.model.js +1 -0
  168. package/dist/uhc-fhir-utils-ts/models/templates/Specimen.template.model.d.ts +12 -0
  169. package/dist/uhc-fhir-utils-ts/models/templates/Specimen.template.model.js +1 -0
  170. package/dist/uhc-fhir-utils-ts/models/templates/index.d.ts +14 -0
  171. package/dist/uhc-fhir-utils-ts/models/templates/index.js +14 -0
  172. package/dist/uhc-fhir-utils-ts/utils/fhirRelatedPerson.d.ts +8 -0
  173. package/dist/uhc-fhir-utils-ts/utils/fhirRelatedPerson.js +57 -0
  174. package/dist/uhc-fhir-utils-ts/utils/fhirToken.d.ts +12 -0
  175. package/dist/uhc-fhir-utils-ts/utils/fhirToken.js +32 -0
  176. package/dist/uhc-fhir-utils-ts/utils/index.js +3 -0
  177. package/dist/uhc-fhir-utils-ts/utils/telecom.d.ts +2 -0
  178. package/dist/uhc-fhir-utils-ts/utils/telecom.js +12 -0
  179. package/dist/utils/capabilityMapper.d.ts +20 -0
  180. package/dist/utils/capabilityMapper.js +124 -0
  181. package/dist/utils/deriveObservations.d.ts +42 -0
  182. package/dist/utils/deriveObservations.js +21 -0
  183. package/dist/utils/entitlements.d.ts +10 -0
  184. package/dist/utils/entitlements.js +21 -0
  185. package/dist/utils/index.d.ts +4 -0
  186. package/dist/utils/index.js +7 -0
  187. package/dist/utils/mockData.d.ts +23 -0
  188. package/dist/utils/mockData.js +68 -0
  189. package/dist/utils/rule.d.ts +12 -0
  190. package/dist/utils/rule.js +45 -0
  191. package/dist/utils/scopeBuilder.d.ts +20 -0
  192. package/dist/utils/scopeBuilder.js +89 -0
  193. package/package.json +19 -4
  194. package/__tests__/BaseApiService.test.ts +0 -158
  195. package/__tests__/BaseProfessionalService.test.ts +0 -26
  196. package/__tests__/ClientSDK.test.ts +0 -114
  197. package/__tests__/CommonAuthService.test.ts +0 -170
  198. package/__tests__/ConversationToObservations.test.ts +0 -231
  199. package/__tests__/IStorageAdapter.ts +0 -39
  200. package/__tests__/IVaultRepository-backend.ts +0 -55
  201. package/__tests__/IndividualService.test.ts +0 -126
  202. package/__tests__/JobManager.test.ts +0 -338
  203. package/__tests__/OrgAdminService.test.ts +0 -157
  204. package/__tests__/ProfileManager.test.ts +0 -137
  205. package/__tests__/Services.test.ts +0 -148
  206. package/__tests__/SmartTokenManager.test.ts +0 -110
  207. package/__tests__/StorageAdapter-mem.ts +0 -46
  208. package/__tests__/VaultRepository-mem-frontend.ts +0 -95
  209. package/__tests__/VaultRepository.mem.ts +0 -122
  210. package/__tests__/VerifierService.test.ts +0 -89
  211. package/__tests__/capabilityMapper.test.ts +0 -67
  212. package/__tests__/integration/apiIntegratorsGuide.e2e.test.ts +0 -215
  213. package/__tests__/mockData.test.ts +0 -43
  214. package/__tests__/repository.ts +0 -14
  215. package/__tests__/rule.test.ts +0 -23
  216. package/__tests__/scopeBuilder.test.ts +0 -72
  217. package/__tests__/stubs/multibasehash.ts +0 -8
  218. package/__tests__/stubs/stablelib-base64.ts +0 -40
  219. package/__tests__/stubs/stablelib-utf8.ts +0 -23
  220. package/__tests__/testUtils.ts +0 -94
  221. package/babel.config.cjs +0 -6
  222. package/data/demo/credential.data.ts +0 -89
  223. package/data/demo/didProvider.data.ts +0 -68
  224. package/data/demo/entityKeys.data.ts +0 -15
  225. package/data/demo/example-payloads.data.ts +0 -369
  226. package/data/demo/offer.data.ts +0 -19
  227. package/data/demo/org-base.data.ts +0 -118
  228. package/data/demo/trust.registry.data.ts +0 -56
  229. package/data/demo/urn.data.ts +0 -10
  230. package/jest.config.ts +0 -27
  231. package/scripts/run-e2e-external.sh +0 -60
  232. package/src/ClientSDK.ts +0 -265
  233. package/src/JobManager.ts +0 -315
  234. package/src/ProfileManager.ts +0 -177
  235. package/src/ProfileRegistry.ts +0 -59
  236. package/src/SmartTokenManager.ts +0 -288
  237. package/src/VerifierService.ts +0 -140
  238. package/src/frontend-services/BaseApiService.ts +0 -282
  239. package/src/frontend-services/base/BaseProfessionalService.ts +0 -67
  240. package/src/frontend-services/capabilities/AppointmentService.ts +0 -58
  241. package/src/frontend-services/capabilities/MedicationService.ts +0 -88
  242. package/src/frontend-services/capabilities/TaskService.ts +0 -66
  243. package/src/frontend-services/common/CommonAuthService.ts +0 -217
  244. package/src/frontend-services/family-admin/FamilyAdminService.ts +0 -124
  245. package/src/frontend-services/family-admin/FamilyItService.ts +0 -53
  246. package/src/frontend-services/individual/IndividualService.ts +0 -46
  247. package/src/frontend-services/org-admin/OrgAdminService.ts +0 -131
  248. package/src/frontend-services/org-admin/OrgItService.ts +0 -59
  249. package/src/frontend-services/professional/emergencies/ParamedicService.ts +0 -28
  250. package/src/frontend-services/professional/health-care/PhysicianService.ts +0 -56
  251. package/src/interfaces/IJobManager.ts +0 -31
  252. package/src/interfaces/IProfile.ts +0 -23
  253. package/src/interfaces/ISmartTokenManager.ts +0 -44
  254. package/src/interfaces/ITrustRegistry.ts +0 -48
  255. package/src/interfaces/IVaultRepository.ts +0 -47
  256. package/src/interfaces/others.ts +0 -100
  257. package/src/models/claims/ClaimsAllergyIntolerance.model.ts +0 -62
  258. package/src/models/claims/ClaimsBase.common.model.ts +0 -37
  259. package/src/models/claims/ClaimsCondition.model.ts +0 -55
  260. package/src/models/claims/ClaimsConsent.model.ts +0 -148
  261. package/src/models/claims/ClaimsDevice.model.ts +0 -93
  262. package/src/models/claims/ClaimsDeviceAssociation.model.ts +0 -78
  263. package/src/models/claims/ClaimsDeviceUsage.model.ts +0 -93
  264. package/src/models/claims/ClaimsMedicationStatement.model.ts +0 -55
  265. package/src/models/claims/ClaimsObservation.model.ts +0 -55
  266. package/src/models/claims/ClaimsRelatedPerson.model.ts +0 -63
  267. package/src/models/hl7-personal-relationship.ts +0 -227
  268. package/src/models/profileRegistry.ts +0 -16
  269. package/src/models/roleIsco.ts +0 -45
  270. package/src/models/rolesHL7.ts +0 -36
  271. package/src/roleRegistry.ts +0 -120
  272. package/src/serviceSelectorRegistry.ts +0 -297
  273. package/src/uhc-fhir-utils-ts/models/AtcModel.ts +0 -20
  274. package/src/uhc-fhir-utils-ts/models/CommonModels.ts +0 -82
  275. package/src/uhc-fhir-utils-ts/models/DicomModels.ts +0 -36
  276. package/src/uhc-fhir-utils-ts/models/LoincModels.ts +0 -30
  277. package/src/uhc-fhir-utils-ts/models/SnomedModels.ts +0 -13
  278. package/src/uhc-fhir-utils-ts/models/params/AdverseEvent.params.model.ts +0 -16
  279. package/src/uhc-fhir-utils-ts/models/params/AllergyIntolerance.params.model.ts +0 -27
  280. package/src/uhc-fhir-utils-ts/models/params/Appointment.params.model.ts +0 -14
  281. package/src/uhc-fhir-utils-ts/models/params/ClinicalImpression.params.model.ts +0 -15
  282. package/src/uhc-fhir-utils-ts/models/params/Condition.params.model.ts +0 -17
  283. package/src/uhc-fhir-utils-ts/models/params/DetectedIssue.params.model.ts +0 -13
  284. package/src/uhc-fhir-utils-ts/models/params/DiagnosticReport.params.model.ts +0 -14
  285. package/src/uhc-fhir-utils-ts/models/params/Encounter.params.model.ts +0 -19
  286. package/src/uhc-fhir-utils-ts/models/params/Immunization.params.model.ts +0 -17
  287. package/src/uhc-fhir-utils-ts/models/params/Medication.params.model.ts +0 -45
  288. package/src/uhc-fhir-utils-ts/models/params/Observation.params.model.ts +0 -399
  289. package/src/uhc-fhir-utils-ts/models/params/Procedure.params.model.ts +0 -17
  290. package/src/uhc-fhir-utils-ts/models/params/Search.params.model.ts +0 -164
  291. package/src/uhc-fhir-utils-ts/models/params/ServiceRequest.params.model.ts +0 -16
  292. package/src/uhc-fhir-utils-ts/models/params/Specimen.params.model.ts +0 -12
  293. package/src/uhc-fhir-utils-ts/models/params/index.ts +0 -16
  294. package/src/uhc-fhir-utils-ts/models/templates/AllergyIntolerance.template.model.ts +0 -28
  295. package/src/uhc-fhir-utils-ts/models/templates/Appointment.template.model.ts +0 -17
  296. package/src/uhc-fhir-utils-ts/models/templates/ClinicalImpression.template.model.ts +0 -19
  297. package/src/uhc-fhir-utils-ts/models/templates/Condition.template.model.ts +0 -20
  298. package/src/uhc-fhir-utils-ts/models/templates/DetectedIssue.template.model.ts +0 -14
  299. package/src/uhc-fhir-utils-ts/models/templates/DiagnosticReport.template.model.ts +0 -19
  300. package/src/uhc-fhir-utils-ts/models/templates/Encounter.template.model.ts +0 -20
  301. package/src/uhc-fhir-utils-ts/models/templates/Immunization.template.model.ts +0 -21
  302. package/src/uhc-fhir-utils-ts/models/templates/Medication.template.model.ts +0 -52
  303. package/src/uhc-fhir-utils-ts/models/templates/Observation.template.model.ts +0 -53
  304. package/src/uhc-fhir-utils-ts/models/templates/Procedure.template.model.ts +0 -20
  305. package/src/uhc-fhir-utils-ts/models/templates/ServiceRequest.template.model.ts +0 -19
  306. package/src/uhc-fhir-utils-ts/models/templates/Specimen.template.model.ts +0 -15
  307. package/src/uhc-fhir-utils-ts/models/templates/index.ts +0 -15
  308. package/src/uhc-fhir-utils-ts/utils/fhirRelatedPerson.ts +0 -59
  309. package/src/uhc-fhir-utils-ts/utils/fhirToken.ts +0 -34
  310. package/src/uhc-fhir-utils-ts/utils/telecom.ts +0 -12
  311. package/src/utils/capabilityMapper.ts +0 -137
  312. package/src/utils/deriveObservations.ts +0 -73
  313. package/src/utils/index.ts +0 -7
  314. package/src/utils/mockData.ts +0 -88
  315. package/src/utils/rule.ts +0 -55
  316. package/src/utils/scopeBuilder.ts +0 -109
  317. package/tsconfig.json +0 -13
  318. /package/{src/uhc-fhir-utils-ts/utils/index.ts → dist/uhc-fhir-utils-ts/utils/index.d.ts} +0 -0
package/README.md CHANGED
@@ -141,14 +141,14 @@ The `SmartTokenManager` within the SDK handles this flow automatically. API serv
141
141
 
142
142
  1. **The `API_INTEGRATORS_GUIDE.md` is the Source of Truth:** All API method implementations, service selectors, and payload structures **must** be based on the official documentation available at `https://raw.githubusercontent.com/Global-DataCare/docs/refs/heads/main/API_INTEGRATORS_GUIDE.md`. The SDK should not invent or assume logic.
143
143
  2. **Test Data is the Second Source of Truth:** The mock data files in `client-sdk-ts/__tests__/data/` are sourced from the backend's own test suite and documentation. They represent the ground truth for API responses and **must** be used for all Jest tests and for the in-app `DEMO_MODE`.
144
- 3. **Specific Methods are Simple, The Engine is Smart:** A specific API method (e.g., `createOrganization`) is responsible for knowing the "what" (the endpoint selector, the payload). The `BaseApiService` engine (`resolveAndExecute`) is responsible for the "how" (DID resolution, message construction, job submission).
144
+ 3. **Specific Methods are Simple, The Engine is Smart:** A specific API method (e.g., `startOrganizationRegistration`) is responsible for knowing the "what" (the endpoint selector, the payload). The `BaseApiService` engine (`resolveAndExecute`) is responsible for the "how" (DID resolution, message construction, job submission).
145
145
 
146
146
  ## End-to-End Onboarding Flow
147
147
 
148
148
  The SDK is designed to follow a specific, multi-step business process for onboarding a new organization.
149
149
 
150
- 1. **`orgAdmin.admin.createOrganization()`**: A legal representative, authenticated with an external OIDC `id_token`, submits the organization's details to the **Host Provider's DID**. The async response will contain an `Offer`.
151
- 2. **`orgAdmin.admin.confirmOrder()`**: The representative accepts the offer by submitting an order, again to the **Host Provider's DID**. The async response will contain a set of license codes.
150
+ 1. **`orgAdmin.admin.startOrganizationRegistration()`**: A legal representative, authenticated with an external OIDC `id_token`, submits the organization's details. The SDK automatically resolves and targets the operator host DID for this onboarding call. The async response will contain an `Offer`.
151
+ 2. **`orgAdmin.admin.confirmOrganizationRegistration()`**: The representative accepts the offer by submitting an order. The SDK again resolves the operator host DID automatically. The async response will contain a set of license codes.
152
152
  3. **Payment (External)**: If required, the user completes the payment flow.
153
153
  4. **`common.auth.activateDevice()`**: The representative (or another employee) uses a valid license code to register their device. This is a DCR (Dynamic Client Registration) call made to the **Gateway's (Tenant's) DID**. This call creates the `client_id` (`did:web`) for the device and marks it as active.
154
154
  5. **`smartToken` Acquisition**: From this point forward, all API calls are authorized (Post-DCR) and must acquire a `smartToken`. The SDK handles this automatically using the device's identity (via `private_key_jwt`) and the user's `id_token`.
@@ -316,16 +316,15 @@ const session = await sdk.initializeSession({
316
316
  const orgAdminService = session.orgAdmin.admin;
317
317
 
318
318
  // --- Step 2: Create the Organization ---
319
- // This call is directed at the HOST's DID.
320
- const hostDid = 'did:web:provider.example.com';
319
+ // The SDK derives the operator host DID from `providerDid`.
321
320
  const orgClaims = { /* ... organization registration data ... */ };
322
- const { thid: createOrgThid } = await orgAdminService.createOrganization(orgClaims, hostDid, legalRepIdToken);
321
+ const { thid: createOrgThid } = await orgAdminService.startOrganizationRegistration(orgClaims, legalRepIdToken);
323
322
  // Poll for the result, which will contain an Offer...
324
323
 
325
324
  // --- Step 3: Confirm the Order ---
326
- // The user accepts the offer. This call is also to the HOST's DID.
325
+ // The user accepts the offer. The SDK keeps targeting the operator host DID internally.
327
326
  const offerId = '...'; // From the result of the previous step
328
- const { thid: confirmOrderThid } = await orgAdminService.confirmOrder(offerId, hostDid, legalRepIdToken);
327
+ const { thid: confirmOrderThid } = await orgAdminService.confirmOrganizationRegistration(offerId, legalRepIdToken);
329
328
  // Poll for the result, which will contain a license code...
330
329
 
331
330
  // --- Step 4: Activate the First Device ---
@@ -337,7 +336,7 @@ const { thid: activateThid } = await commonAuthService.activateDevice(licenseCod
337
336
  ```
338
337
 
339
338
  ### Note on Production vs. Test Onboarding
340
- The self-service `createOrganization` flow detailed above is intended for the **`test-network`**. Onboarding a new organization in the **production** environment involves a manual verification process by the host provider to ensure the legitimacy of the legal entity.
339
+ The self-service `startOrganizationRegistration` flow detailed above is intended for the **`test-network`**. Onboarding a new organization in the **production** environment involves a manual verification process by the host provider to ensure the legitimacy of the legal entity.
341
340
 
342
341
  ## Testing
343
342
 
@@ -0,0 +1,56 @@
1
+ import { IWallet } from 'gdc-common-utils-ts/interfaces/IWallet';
2
+ import { IVaultRepository } from './interfaces/IVaultRepository';
3
+ import { ProfileManager } from './ProfileManager';
4
+ import { SdkConfig } from './interfaces/others';
5
+ import { DidDocument } from 'gdc-common-utils-ts/models/did';
6
+ import { IVerifier } from './interfaces/ITrustRegistry';
7
+ import { AppInfo } from './interfaces/others';
8
+ import { ProfileRegistry } from './ProfileRegistry';
9
+ /**
10
+ * The parameters required to initialize a user session.
11
+ */
12
+ export interface InitializeSessionParams {
13
+ profileId?: string;
14
+ email: string;
15
+ role: string;
16
+ providerDid: string;
17
+ appType?: AppInfo['appType'];
18
+ familyId?: string;
19
+ }
20
+ /**
21
+ * @class ClientSDK
22
+ * The main entry point for the client-side SDK.
23
+ */
24
+ export declare class ClientSDK {
25
+ private sdkConfig;
26
+ private appInfo;
27
+ private wallet;
28
+ private verifier;
29
+ private icaDid;
30
+ private _fetch;
31
+ currentSession: ProfileManager | null;
32
+ profileRegistry: ProfileRegistry | null;
33
+ get operationMode(): string;
34
+ /**
35
+ * Dynamically adds a mock DID Document to the SDK's configuration for DEMO mode.
36
+ * This allows the UI to inject mock data at runtime to bypass network failures.
37
+ * @param did The DID to mock.
38
+ * @param didDoc The DID Document to return when the DID is resolved.
39
+ */
40
+ addMockDidDocument(did: string, didDoc: DidDocument): void;
41
+ constructor(sdkConfig: SdkConfig, appInfo: AppInfo, wallet: IWallet, verifier: IVerifier, icaDid: string);
42
+ /**
43
+ * The single, unified method for creating a new user session.
44
+ * This method orchestrates the entire trust verification and session creation flow.
45
+ */
46
+ initializeSession(params: InitializeSessionParams, createVault: (profileId: string) => IVaultRepository): Promise<ProfileManager>;
47
+ private _createProfileManager;
48
+ /**
49
+ * Shuts down the currently active session.
50
+ */
51
+ initializeProfileRegistry(createVault: (registryId: string) => IVaultRepository, registryId?: string): Promise<ProfileRegistry>;
52
+ shutdownSession(): void;
53
+ private normalizeRoleCodeForDid;
54
+ private constructEmployeeDid;
55
+ private constructIndividualDid;
56
+ }
@@ -0,0 +1,202 @@
1
+ // Copyright 2025 Antifraud Services Inc. under the Apache License, Version 2.0.
2
+ // File: client-sdk-ts/src/ClientSDK.ts
3
+ import { ProfileManager } from './ProfileManager.js';
4
+ import { getBaseUrlFromDidWeb, normalizeDidWeb } from 'gdc-common-utils-ts/utils/did';
5
+ import { ProfileRegistry } from './ProfileRegistry.js';
6
+ /**
7
+ * @class ClientSDK
8
+ * The main entry point for the client-side SDK.
9
+ */
10
+ export class ClientSDK {
11
+ get operationMode() {
12
+ return this.sdkConfig.api.operationMode;
13
+ }
14
+ /**
15
+ * Dynamically adds a mock DID Document to the SDK's configuration for DEMO mode.
16
+ * This allows the UI to inject mock data at runtime to bypass network failures.
17
+ * @param did The DID to mock.
18
+ * @param didDoc The DID Document to return when the DID is resolved.
19
+ */
20
+ addMockDidDocument(did, didDoc) {
21
+ if (!this.sdkConfig.mockOptions) {
22
+ this.sdkConfig.mockOptions = {};
23
+ }
24
+ if (!this.sdkConfig.mockOptions.resolvedDidDocs) {
25
+ this.sdkConfig.mockOptions.resolvedDidDocs = {};
26
+ }
27
+ this.sdkConfig.mockOptions.resolvedDidDocs[did] = didDoc;
28
+ console.log(`[SDK-MOCK] Injected mock for DID: ${did}`);
29
+ }
30
+ constructor(sdkConfig, appInfo, wallet, verifier, icaDid) {
31
+ var _a;
32
+ this.currentSession = null;
33
+ this.profileRegistry = null;
34
+ if (!sdkConfig || !appInfo || !wallet || !verifier || !icaDid) {
35
+ throw new Error("ClientSDK requires sdkConfig, appInfo, wallet, verifier, and an icaDid.");
36
+ }
37
+ this.sdkConfig = Object.assign({}, sdkConfig);
38
+ this.appInfo = appInfo;
39
+ this.wallet = wallet;
40
+ this.verifier = verifier;
41
+ this.icaDid = icaDid;
42
+ // --- Mockable Fetcher Initialization (Remains the same) ---
43
+ if ((_a = this.sdkConfig.mockOptions) === null || _a === void 0 ? void 0 : _a.apiResponse) {
44
+ console.warn("SDK is in MOCK API mode. Real network calls will be bypassed.");
45
+ const mock = this.sdkConfig.mockOptions.apiResponse;
46
+ this._fetch = async (url, options) => {
47
+ var _a;
48
+ console.log(`[MOCK FETCH] Intercepted call to: ${url}`);
49
+ if ((_a = options === null || options === void 0 ? void 0 : options.body) === null || _a === void 0 ? void 0 : _a.includes('thid=')) {
50
+ console.log(`[MOCK FETCH] Simulating FINAL polling response with status: ${mock.finalPolledStatus || 200}`);
51
+ return new Response(JSON.stringify(mock.body || {}), {
52
+ status: mock.finalPolledStatus || 200,
53
+ headers: { 'Content-Type': 'application/json' },
54
+ });
55
+ }
56
+ console.log(`[MOCK FETCH] Simulating INITIAL response with status: ${mock.status}`);
57
+ const headers = new Headers({ 'Content-Type': 'application/json' });
58
+ if (mock.status === 202) {
59
+ headers.set('Location', 'https://mock.example.com/poll/12345');
60
+ }
61
+ return new Response(mock.status === 202 ? '' : JSON.stringify(mock.body || {}), {
62
+ status: mock.status,
63
+ headers: headers,
64
+ });
65
+ };
66
+ }
67
+ else {
68
+ this._fetch = this.sdkConfig.fetcher;
69
+ }
70
+ this.sdkConfig.fetcher = this._fetch;
71
+ }
72
+ /**
73
+ * The single, unified method for creating a new user session.
74
+ * This method orchestrates the entire trust verification and session creation flow.
75
+ */
76
+ async initializeSession(params, createVault) {
77
+ var _a, _b, _c, _d;
78
+ this.shutdownSession();
79
+ // The entry point is the DID. The SDK resolves it to a URL for fetching.
80
+ const { providerDid } = params;
81
+ const providerUrl = getBaseUrlFromDidWeb(providerDid);
82
+ // --- STEP 0: CHECK FOR MOCK OVERRIDE ---
83
+ // The key for mock resolution is always the providerDid.
84
+ const mockDidDocs = (_a = this.sdkConfig.mockOptions) === null || _a === void 0 ? void 0 : _a.resolvedDidDocs;
85
+ if (mockDidDocs && mockDidDocs[providerDid]) {
86
+ console.warn(`[MOCK] Bypassing trust verification. Using mocked DID Document for ${providerDid}`);
87
+ const trustedDidDoc = mockDidDocs[providerDid];
88
+ return this._createProfileManager(params, trustedDidDoc, createVault);
89
+ }
90
+ // --- STEP 1: FETCH THE GOVERNANCE PROOF (vc.json) ---
91
+ const vcUrl = new URL('.well-known/vc.json', providerUrl).href;
92
+ const vcResponse = await this._fetch(vcUrl);
93
+ if (!vcResponse.ok)
94
+ throw new Error(`Failed to fetch assurance VC from ${vcUrl}`);
95
+ const assuranceVC = await vcResponse.json();
96
+ // --- STEP 2: VERIFY THE ISSUER ---
97
+ // The issuer of the VC MUST match the configured, trusted ICA DID.
98
+ if (assuranceVC.issuer !== this.icaDid) {
99
+ throw new Error(`Assurance VC issuer '${assuranceVC.issuer}' does not match the configured trusted ICA '${this.icaDid}'.`);
100
+ }
101
+ // --- STEP 3: VERIFY THE CREDENTIAL'S CHAIN OF TRUST ---
102
+ const isVCSignatureValid = await this.verifier.verifyCredential(assuranceVC);
103
+ if (!isVCSignatureValid)
104
+ throw new Error("Assurance VC signature is invalid or the trust chain is broken.");
105
+ // --- STEP 3: SECURELY FETCH AND VERIFY THE DID DOCUMENT ---
106
+ const evidence = (_b = assuranceVC.evidence) === null || _b === void 0 ? void 0 : _b[0];
107
+ const attachment = (_c = evidence === null || evidence === void 0 ? void 0 : evidence.attachments) === null || _c === void 0 ? void 0 : _c[0];
108
+ if (!attachment || !((_d = attachment.digest) === null || _d === void 0 ? void 0 : _d.value) || !attachment.url) {
109
+ throw new Error("Assurance VC is missing valid integrity evidence for the DID Document.");
110
+ }
111
+ const didDocUrl = attachment.url;
112
+ const didDocResponse = await this._fetch(didDocUrl);
113
+ if (!didDocResponse.ok)
114
+ throw new Error(`Failed to fetch DID Document from ${didDocUrl}`);
115
+ const didDocText = await didDocResponse.text();
116
+ const calculatedHash = await this.sdkConfig.crypto.digestString(didDocText, 'SHA-256');
117
+ if (calculatedHash !== attachment.digest.value) {
118
+ throw new Error("Man-in-the-middle attack detected! DID Document hash does not match the hash in the trusted assurance VC.");
119
+ }
120
+ const trustedDidDoc = JSON.parse(didDocText);
121
+ // --- STEP 4: PROCEED WITH SESSION CREATION ---
122
+ return this._createProfileManager(params, trustedDidDoc, createVault);
123
+ }
124
+ // --- Private Helper for the final creation step ---
125
+ async _createProfileManager(params, orgDidDoc, createVault) {
126
+ const { email, role } = params;
127
+ const providerDid = orgDidDoc.id; // The authoritative DID from the trusted doc
128
+ const appType = params.appType || this.appInfo.appType;
129
+ const appInfoForSession = Object.assign(Object.assign({}, this.appInfo), { appType });
130
+ const finalProfileId = params.profileId || this.sdkConfig.crypto.randomUUID();
131
+ const userDid = appType === 'Organization'
132
+ ? this.constructEmployeeDid(providerDid, email, role)
133
+ : await this.constructIndividualDid(providerDid, finalProfileId, email, role, params.familyId);
134
+ const publicKeys = await this.wallet.provisionKeys(finalProfileId);
135
+ const newProfile = {
136
+ id: finalProfileId,
137
+ isAnonymous: false,
138
+ createdAt: new Date().toISOString(),
139
+ status: 'pending',
140
+ keys: publicKeys,
141
+ email: email,
142
+ role: role,
143
+ did: userDid,
144
+ appType: appType,
145
+ providerDid: providerDid,
146
+ };
147
+ const vault = createVault(finalProfileId);
148
+ const manager = new ProfileManager({
149
+ profile: newProfile,
150
+ orgDidDoc: orgDidDoc,
151
+ wallet: this.wallet,
152
+ vault: vault,
153
+ sdkConfig: this.sdkConfig,
154
+ appInfo: appInfoForSession, // Pass session app type down
155
+ });
156
+ await manager.initialize();
157
+ await vault.put('profile', newProfile);
158
+ this.currentSession = manager;
159
+ return manager;
160
+ }
161
+ /**
162
+ * Shuts down the currently active session.
163
+ */
164
+ async initializeProfileRegistry(createVault, registryId = 'profile-registry') {
165
+ const vault = createVault(registryId);
166
+ const registry = new ProfileRegistry(vault);
167
+ await registry.initialize();
168
+ this.profileRegistry = registry;
169
+ return registry;
170
+ }
171
+ shutdownSession() {
172
+ if (this.currentSession) {
173
+ this.currentSession.shutdown();
174
+ this.currentSession = null;
175
+ }
176
+ }
177
+ normalizeRoleCodeForDid(role, fallback = 'unknown-role') {
178
+ const raw = (role || '').trim();
179
+ if (!raw)
180
+ return fallback;
181
+ const parts = raw.split('|');
182
+ if (parts.length === 2) {
183
+ return (parts[1] || '').trim() || fallback;
184
+ }
185
+ return raw;
186
+ }
187
+ constructEmployeeDid(connectorDid, email, role) {
188
+ const roleCode = this.normalizeRoleCodeForDid(role, 'invalid-role');
189
+ const rawDid = `${connectorDid}:employee:${email}:${roleCode}`;
190
+ // Normalize it to ensure canonical representation
191
+ return normalizeDidWeb(rawDid);
192
+ }
193
+ async constructIndividualDid(connectorDid, profileId, email, role, familyId) {
194
+ const normalizedEmail = (email || '').trim().toLowerCase();
195
+ const emailHash = await this.sdkConfig.crypto.digestString(normalizedEmail, 'SHA-256');
196
+ const multibaseEmailHash = `z${emailHash}`;
197
+ const normalizedFamilyId = (familyId || `profile-${profileId}`).trim();
198
+ const normalizedRole = this.normalizeRoleCodeForDid(role, 'ONESELF').toUpperCase();
199
+ const rawDid = `${connectorDid}:family:${normalizedFamilyId}:${multibaseEmailHash}:${normalizedRole}`;
200
+ return normalizeDidWeb(rawDid);
201
+ }
202
+ }
@@ -0,0 +1,39 @@
1
+ import { IWallet } from 'gdc-common-utils-ts/interfaces/IWallet';
2
+ import { IProfile } from './interfaces/IProfile';
3
+ import { IVaultRepository, VaultQuery } from './interfaces/IVaultRepository';
4
+ import { SdkConfig } from './interfaces/others';
5
+ import { IDecodedDidcommPayload } from 'gdc-common-utils-ts/models/confidential-message';
6
+ import { IJobManager } from './interfaces/IJobManager';
7
+ import { JobStatus, JobRequest } from 'gdc-common-utils-ts/models/confidential-job';
8
+ import { ServiceEndpointSelector } from 'gdc-common-utils-ts/models/did';
9
+ interface JobManagerConfig {
10
+ profile: IProfile;
11
+ wallet: IWallet;
12
+ vault: IVaultRepository;
13
+ sdkConfig: SdkConfig;
14
+ }
15
+ declare class JobManager implements IJobManager {
16
+ profile: IProfile;
17
+ wallet: IWallet;
18
+ vault: IVaultRepository;
19
+ private sdkConfig;
20
+ private listener;
21
+ private pollingIntervalId;
22
+ isInitialized: boolean;
23
+ constructor(config: JobManagerConfig);
24
+ setListener(listener: () => void): void;
25
+ initialize(): Promise<void>;
26
+ shutdown(): void;
27
+ createJob(content: IDecodedDidcommPayload, selector: ServiceEndpointSelector): Promise<JobRequest>;
28
+ findDraftJobByFormType(formType: string): Promise<JobRequest | null>;
29
+ createOrUpdateDraftJob(content: IDecodedDidcommPayload, selector: ServiceEndpointSelector): Promise<JobRequest>;
30
+ submitJob(job: JobRequest): Promise<void>;
31
+ pollSentJobs(): Promise<void>;
32
+ sealJobWithToken(job: JobRequest, token: string): Promise<JobRequest | null>;
33
+ sync(idToken: string): Promise<void>;
34
+ updateJobStatus(jobId: string, newStatus: JobStatus, additionalData?: object): Promise<JobRequest>;
35
+ queryJobs(query: VaultQuery): Promise<JobRequest[]>;
36
+ getJobResponseByThid(thid: string): Promise<any | null>;
37
+ generateId(): string;
38
+ }
39
+ export default JobManager;
@@ -0,0 +1,258 @@
1
+ // Copyright 2025 Antifraud Services Inc. under the Apache License, Version 2.0.
2
+ // File: client-sdk-ts/src/JobManager.ts
3
+ var __rest = (this && this.__rest) || function (s, e) {
4
+ var t = {};
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
6
+ t[p] = s[p];
7
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
8
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
9
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
10
+ t[p[i]] = s[p[i]];
11
+ }
12
+ return t;
13
+ };
14
+ import { normalizeDidcommPayloadForId } from 'gdc-common-utils-ts/utils/normalize';
15
+ import { JobStatus } from 'gdc-common-utils-ts/models/confidential-job';
16
+ class JobManager {
17
+ constructor(config) {
18
+ if (!config || !config.profile || !config.wallet || !config.vault || !config.sdkConfig) {
19
+ throw new Error("JobManager requires a configuration object with 'profile', 'wallet', 'vault', and 'sdkConfig'.");
20
+ }
21
+ this.profile = config.profile;
22
+ this.wallet = config.wallet;
23
+ this.vault = config.vault;
24
+ this.sdkConfig = config.sdkConfig;
25
+ this.listener = () => { };
26
+ this.pollingIntervalId = null;
27
+ this.isInitialized = false;
28
+ }
29
+ setListener(listener) { this.listener = listener; }
30
+ async initialize() {
31
+ if (this.isInitialized)
32
+ return;
33
+ await this.vault.initialize();
34
+ this.pollingIntervalId = setInterval(() => this.pollSentJobs(), 8000);
35
+ this.isInitialized = true;
36
+ }
37
+ shutdown() {
38
+ if (this.pollingIntervalId)
39
+ clearInterval(this.pollingIntervalId);
40
+ this.isInitialized = false;
41
+ }
42
+ async createJob(content, selector) {
43
+ const jti = this.generateId();
44
+ const now = Date.now();
45
+ const versionHash = await this.sdkConfig.crypto.digestString(normalizeDidcommPayloadForId(content), 'SHA-256');
46
+ const finalContent = Object.assign(Object.assign({}, content), { id: versionHash, jti: jti, thid: content.thid || this.generateId() });
47
+ const unprotectedDoc = Object.assign({ id: jti, thid: finalContent.thid, versionId: versionHash, status: JobStatus.DRAFT, vaultId: this.profile.id, createdAtTimestamp: now, sequence: now, content: finalContent }, selector);
48
+ const protectedDoc = await this.wallet.protectConfidentialData(unprotectedDoc, this.profile.id);
49
+ await this.vault.put('jobs', protectedDoc);
50
+ this.listener();
51
+ return protectedDoc;
52
+ }
53
+ async findDraftJobByFormType(formType) {
54
+ if (!this.isInitialized)
55
+ return null;
56
+ const draftJobs = await this.vault.query('jobs', {
57
+ where: [
58
+ { attribute: 'status', equals: JobStatus.DRAFT },
59
+ { attribute: 'content.type', equals: formType },
60
+ { attribute: 'vaultId', equals: this.profile.id }
61
+ ]
62
+ });
63
+ return draftJobs.length > 0 ? draftJobs[0] : null;
64
+ }
65
+ async createOrUpdateDraftJob(content, selector) {
66
+ const existingDraft = await this.findDraftJobByFormType(content.type);
67
+ if (existingDraft) {
68
+ const unprotected = await this.wallet.unprotectConfidentialData(existingDraft, this.profile.id);
69
+ if (!unprotected.content)
70
+ throw new Error(`Job ${existingDraft.id} is invalid.`);
71
+ const newContentBody = Object.assign(Object.assign({}, unprotected.content), { body: content.body });
72
+ const newVersionHash = await this.sdkConfig.crypto.digestString(normalizeDidcommPayloadForId(newContentBody), 'SHA-256');
73
+ newContentBody.id = newVersionHash;
74
+ const now = Date.now();
75
+ const docToReEncrypt = Object.assign(Object.assign(Object.assign({}, unprotected), { versionId: newVersionHash, thid: newContentBody.thid, sequence: now, previousSequence: unprotected.sequence, content: newContentBody }), selector);
76
+ const reProtectedDoc = await this.wallet.protectConfidentialData(docToReEncrypt, this.profile.id);
77
+ await this.vault.put('jobs', reProtectedDoc);
78
+ this.listener();
79
+ return reProtectedDoc;
80
+ }
81
+ else {
82
+ return this.createJob(content, selector);
83
+ }
84
+ }
85
+ async submitJob(job) {
86
+ var _a, _b, _c;
87
+ await this.updateJobStatus(job.id, JobStatus.SUBMITTING);
88
+ try {
89
+ const unprotected = await this.wallet.unprotectConfidentialData(job, this.profile.id);
90
+ const { content } = unprotected;
91
+ if (!content || !content.aud)
92
+ throw new Error("Job is missing 'aud' property.");
93
+ const { operationMode, legacyFhirEnabled } = this.sdkConfig.api;
94
+ const { fetcher } = this.sdkConfig;
95
+ const { id: versionId } = content, contentForSending = __rest(content, ["id"]);
96
+ const idToken = (_b = (_a = contentForSending === null || contentForSending === void 0 ? void 0 : contentForSending.meta) === null || _a === void 0 ? void 0 : _a.bearer) === null || _b === void 0 ? void 0 : _b.compact;
97
+ const recipientDid = (_c = contentForSending.to) === null || _c === void 0 ? void 0 : _c[0];
98
+ const submissionUrl = contentForSending.aud;
99
+ let requestBody;
100
+ let contentType;
101
+ if (operationMode === 'FAPI') {
102
+ if (!recipientDid)
103
+ throw new Error("Recipient DID is missing for FAPI mode.");
104
+ const packedMessage = await this.wallet.packForRecipient(contentForSending, recipientDid);
105
+ requestBody = new URLSearchParams({ request: packedMessage }).toString();
106
+ contentType = 'application/x-www-form-urlencoded';
107
+ }
108
+ else {
109
+ requestBody = (submissionUrl.includes('fhir') && legacyFhirEnabled)
110
+ ? JSON.stringify(contentForSending.body)
111
+ : JSON.stringify(contentForSending);
112
+ contentType = (submissionUrl.includes('fhir') && legacyFhirEnabled)
113
+ ? 'application/fhir+json'
114
+ : 'application/json';
115
+ }
116
+ const headers = { 'Content-Type': contentType };
117
+ if (idToken)
118
+ headers['Authorization'] = `Bearer ${idToken}`;
119
+ const response = await fetcher(submissionUrl, { method: 'POST', headers, body: requestBody });
120
+ if (response.status === 202) {
121
+ const locationUrl = response.headers.get('Location');
122
+ const absoluteLocationUrl = locationUrl ? new URL(locationUrl, submissionUrl).href : undefined;
123
+ await this.updateJobStatus(job.id, JobStatus.SENT, { locationUrl: absoluteLocationUrl });
124
+ }
125
+ else if (response.ok) {
126
+ const result = await response.text();
127
+ await this.updateJobStatus(job.id, JobStatus.COMPLETED, { result });
128
+ }
129
+ else {
130
+ const errorBody = await response.text();
131
+ const errorMessage = `Server responded with status ${response.status}: ${errorBody}`;
132
+ const finalStatus = response.status >= 500 ? JobStatus.ERROR_RETRYABLE : JobStatus.FAILED;
133
+ await this.updateJobStatus(job.id, finalStatus, { errorMessage, retryCount: (job.retryCount || 0) + 1 });
134
+ }
135
+ }
136
+ catch (error) {
137
+ const errorMessage = error instanceof Error ? error.message : String(error);
138
+ await this.updateJobStatus(job.id, JobStatus.ERROR_RETRYABLE, { errorMessage, retryCount: (job.retryCount || 0) + 1 });
139
+ }
140
+ }
141
+ async pollSentJobs() {
142
+ var _a, _b, _c, _d, _e;
143
+ const sentJobs = await this.vault.query('jobs', { where: [{ attribute: 'status', equals: JobStatus.SENT }] });
144
+ if (sentJobs.length === 0)
145
+ return;
146
+ for (const job of sentJobs) {
147
+ if (!job.locationUrl)
148
+ continue;
149
+ try {
150
+ const unprotected = await this.wallet.unprotectConfidentialData(job, this.profile.id);
151
+ const thid = (_a = unprotected.content) === null || _a === void 0 ? void 0 : _a.thid;
152
+ const idToken = (_d = (_c = (_b = unprotected.content) === null || _b === void 0 ? void 0 : _b.meta) === null || _c === void 0 ? void 0 : _c.bearer) === null || _d === void 0 ? void 0 : _d.compact;
153
+ if (!thid) {
154
+ await this.updateJobStatus(job.id, JobStatus.FAILED, { errorMessage: 'Cannot poll job: thid is missing.' });
155
+ continue;
156
+ }
157
+ const headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
158
+ if (idToken)
159
+ headers['Authorization'] = `Bearer ${idToken}`;
160
+ const body = new URLSearchParams({ thid }).toString();
161
+ const pollResponse = await this.sdkConfig.fetcher(job.locationUrl, { method: 'POST', headers, body });
162
+ if (pollResponse.status === 202)
163
+ continue;
164
+ const rawResponseBody = await pollResponse.text();
165
+ if (!rawResponseBody) {
166
+ await this.updateJobStatus(job.id, JobStatus.FAILED, { errorMessage: `Polling returned ${pollResponse.status} with empty body.` });
167
+ continue;
168
+ }
169
+ if (!this.wallet.unpack)
170
+ throw new Error("Wallet does not support 'unpack' method.");
171
+ const { content: unpackedContent } = await this.wallet.unpack(rawResponseBody);
172
+ const responseId = this.sdkConfig.crypto.randomUUID();
173
+ await this.vault.put('messages', {
174
+ id: responseId,
175
+ thid: (_e = unprotected.content) === null || _e === void 0 ? void 0 : _e.thid,
176
+ statusCode: pollResponse.status,
177
+ content: unpackedContent,
178
+ });
179
+ const finalJobStatus = (pollResponse.ok || pollResponse.status === 409) ? JobStatus.COMPLETED : JobStatus.FAILED;
180
+ await this.updateJobStatus(job.id, finalJobStatus, { responseMessageId: responseId });
181
+ }
182
+ catch (error) {
183
+ const pollErrorMessage = error instanceof Error ? error.message : String(error);
184
+ await this.updateJobStatus(job.id, job.status, { errorMessage: `Polling network error: ${pollErrorMessage}` });
185
+ }
186
+ }
187
+ }
188
+ async sealJobWithToken(job, token) {
189
+ var _a, _b;
190
+ if (!job)
191
+ return null;
192
+ const unprotected = await this.wallet.unprotectConfidentialData(job, this.profile.id);
193
+ if (!unprotected.content)
194
+ return job;
195
+ if ((_b = (_a = unprotected.content.meta) === null || _a === void 0 ? void 0 : _a.bearer) === null || _b === void 0 ? void 0 : _b.compact)
196
+ return job;
197
+ if (!unprotected.content.meta)
198
+ unprotected.content.meta = {};
199
+ if (!unprotected.content.meta.bearer)
200
+ unprotected.content.meta.bearer = { jwt: {} };
201
+ unprotected.content.meta.bearer.compact = token;
202
+ const reProtectedDoc = await this.wallet.protectConfidentialData(unprotected, this.profile.id);
203
+ await this.vault.put('jobs', reProtectedDoc);
204
+ return reProtectedDoc;
205
+ }
206
+ async sync(idToken) {
207
+ var _a;
208
+ if (((_a = this.sdkConfig.mockOptions) === null || _a === void 0 ? void 0 : _a.networkStatus) === 'offline') {
209
+ return;
210
+ }
211
+ const isOnline = await this.sdkConfig.network.isConnected();
212
+ if (!isOnline)
213
+ return;
214
+ const jobsToSync = await this.vault.query('jobs', {
215
+ where: [{ attribute: 'status', in: [JobStatus.DRAFT, JobStatus.ERROR_RETRYABLE] }]
216
+ });
217
+ if (jobsToSync.length > 0) {
218
+ const sealedJobs = await Promise.all(jobsToSync.map((job) => this.sealJobWithToken(job, idToken)));
219
+ const validJobs = sealedJobs.filter((job) => job !== null);
220
+ await Promise.all(validJobs.map((job) => this.submitJob(job)));
221
+ }
222
+ }
223
+ async updateJobStatus(jobId, newStatus, additionalData = {}) {
224
+ const originalJob = await this.vault.get('jobs', jobId);
225
+ if (!originalJob)
226
+ throw new Error(`Job with id ${jobId} not found for update.`);
227
+ const now = Date.now();
228
+ const updateData = Object.assign(Object.assign({}, additionalData), { status: newStatus, sequence: now, previousSequence: originalJob.sequence });
229
+ const docToUpdate = Object.assign(Object.assign({}, originalJob), updateData);
230
+ await this.vault.put('jobs', docToUpdate);
231
+ this.listener();
232
+ return docToUpdate;
233
+ }
234
+ async queryJobs(query) {
235
+ if (!this.isInitialized)
236
+ return [];
237
+ return this.vault.query('jobs', query);
238
+ }
239
+ async getJobResponseByThid(thid) {
240
+ var _a;
241
+ if (!this.isInitialized)
242
+ return null;
243
+ const jobs = await this.vault.query('jobs', {
244
+ where: [{ attribute: 'thid', equals: thid }],
245
+ orderBy: { attribute: 'sequence', direction: 'desc' },
246
+ limit: 1,
247
+ });
248
+ const job = jobs === null || jobs === void 0 ? void 0 : jobs[0];
249
+ if (!job || !job.responseMessageId)
250
+ return null;
251
+ const message = await this.vault.get('messages', job.responseMessageId);
252
+ return (_a = message === null || message === void 0 ? void 0 : message.content) !== null && _a !== void 0 ? _a : null;
253
+ }
254
+ generateId() {
255
+ return this.sdkConfig.crypto.randomUUID();
256
+ }
257
+ }
258
+ export default JobManager;