@c15t/backend 0.0.1-rc.10

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 (521) hide show
  1. package/.turbo/turbo-build.log +11 -0
  2. package/.turbo/turbo-check-types.log +5 -0
  3. package/.turbo/turbo-fmt.log +7 -0
  4. package/.turbo/turbo-lint.log +6 -0
  5. package/.turbo/turbo-test.log +26 -0
  6. package/README-next.md +223 -0
  7. package/README.md +164 -0
  8. package/dist/api/call.d.ts +176 -0
  9. package/dist/api/call.d.ts.map +1 -0
  10. package/dist/api/index.d.ts +935 -0
  11. package/dist/api/index.d.ts.map +1 -0
  12. package/dist/api/middlewares/index.d.ts +39 -0
  13. package/dist/api/middlewares/index.d.ts.map +1 -0
  14. package/dist/api/middlewares/origin-check.d.ts +82 -0
  15. package/dist/api/middlewares/origin-check.d.ts.map +1 -0
  16. package/dist/api/middlewares/validate-context.d.ts +38 -0
  17. package/dist/api/middlewares/validate-context.d.ts.map +1 -0
  18. package/dist/api/routes/__tests__/consent.test.d.ts +2 -0
  19. package/dist/api/routes/__tests__/consent.test.d.ts.map +1 -0
  20. package/dist/api/routes/__tests__/status.test.d.ts +2 -0
  21. package/dist/api/routes/__tests__/status.test.d.ts.map +1 -0
  22. package/dist/api/routes/error.d.ts +57 -0
  23. package/dist/api/routes/error.d.ts.map +1 -0
  24. package/dist/api/routes/generate-consent-receipt.d.ts +130 -0
  25. package/dist/api/routes/generate-consent-receipt.d.ts.map +1 -0
  26. package/dist/api/routes/get-consent-history.d.ts +133 -0
  27. package/dist/api/routes/get-consent-history.d.ts.map +1 -0
  28. package/dist/api/routes/get-consent-policy.d.ts +164 -0
  29. package/dist/api/routes/get-consent-policy.d.ts.map +1 -0
  30. package/dist/api/routes/get-consent.d.ts +148 -0
  31. package/dist/api/routes/get-consent.d.ts.map +1 -0
  32. package/dist/api/routes/index.d.ts +339 -0
  33. package/dist/api/routes/index.d.ts.map +1 -0
  34. package/dist/api/routes/ok.d.ts +87 -0
  35. package/dist/api/routes/ok.d.ts.map +1 -0
  36. package/dist/api/routes/set-consent.d.ts +245 -0
  37. package/dist/api/routes/set-consent.d.ts.map +1 -0
  38. package/dist/api/routes/show-consent-banner.d.ts +127 -0
  39. package/dist/api/routes/show-consent-banner.d.ts.map +1 -0
  40. package/dist/api/routes/status.d.ts +61 -0
  41. package/dist/api/routes/status.d.ts.map +1 -0
  42. package/dist/api/routes/verify-consent.d.ts +179 -0
  43. package/dist/api/routes/verify-consent.d.ts.map +1 -0
  44. package/dist/api/routes/withdraw-consent.d.ts +194 -0
  45. package/dist/api/routes/withdraw-consent.d.ts.map +1 -0
  46. package/dist/api/to-endpoints.d.ts +35 -0
  47. package/dist/api/to-endpoints.d.ts.map +1 -0
  48. package/dist/client/index.cjs +139 -0
  49. package/dist/client/index.d.ts +203 -0
  50. package/dist/client/index.d.ts.map +1 -0
  51. package/dist/client/index.js +106 -0
  52. package/dist/client/types.d.ts +431 -0
  53. package/dist/client/types.d.ts.map +1 -0
  54. package/dist/core.d.ts +124 -0
  55. package/dist/core.d.ts.map +1 -0
  56. package/dist/core.test.d.ts +2 -0
  57. package/dist/core.test.d.ts.map +1 -0
  58. package/dist/db/adapters/drizzle-adapter/drizzle-adapter.d.ts +122 -0
  59. package/dist/db/adapters/drizzle-adapter/drizzle-adapter.d.ts.map +1 -0
  60. package/dist/db/adapters/drizzle-adapter/index.d.ts +2 -0
  61. package/dist/db/adapters/drizzle-adapter/index.d.ts.map +1 -0
  62. package/dist/db/adapters/drizzle.cjs +1531 -0
  63. package/dist/db/adapters/drizzle.js +1489 -0
  64. package/dist/db/adapters/kysely-adapter/dialect.d.ts +72 -0
  65. package/dist/db/adapters/kysely-adapter/dialect.d.ts.map +1 -0
  66. package/dist/db/adapters/kysely-adapter/index.d.ts +4 -0
  67. package/dist/db/adapters/kysely-adapter/index.d.ts.map +1 -0
  68. package/dist/db/adapters/kysely-adapter/kysely-adapter.d.ts +98 -0
  69. package/dist/db/adapters/kysely-adapter/kysely-adapter.d.ts.map +1 -0
  70. package/dist/db/adapters/kysely-adapter/types.d.ts +281 -0
  71. package/dist/db/adapters/kysely-adapter/types.d.ts.map +1 -0
  72. package/dist/db/adapters/kysely.cjs +1551 -0
  73. package/dist/db/adapters/kysely.js +1508 -0
  74. package/dist/db/adapters/memory-adapter/index.d.ts +2 -0
  75. package/dist/db/adapters/memory-adapter/index.d.ts.map +1 -0
  76. package/dist/db/adapters/memory-adapter/memory-adapter.d.ts +56 -0
  77. package/dist/db/adapters/memory-adapter/memory-adapter.d.ts.map +1 -0
  78. package/dist/db/adapters/memory.cjs +1391 -0
  79. package/dist/db/adapters/memory.js +1349 -0
  80. package/dist/db/adapters/prisma-adapter/index.d.ts +2 -0
  81. package/dist/db/adapters/prisma-adapter/index.d.ts.map +1 -0
  82. package/dist/db/adapters/prisma-adapter/prisma-adapter.d.ts +143 -0
  83. package/dist/db/adapters/prisma-adapter/prisma-adapter.d.ts.map +1 -0
  84. package/dist/db/adapters/prisma.cjs +1503 -0
  85. package/dist/db/adapters/prisma.js +1461 -0
  86. package/dist/db/adapters/types.d.ts +154 -0
  87. package/dist/db/adapters/types.d.ts.map +1 -0
  88. package/dist/db/adapters/utils.d.ts +36 -0
  89. package/dist/db/adapters/utils.d.ts.map +1 -0
  90. package/dist/db/core/fields/field-factory.d.ts +383 -0
  91. package/dist/db/core/fields/field-factory.d.ts.map +1 -0
  92. package/dist/db/core/fields/field-inference.d.ts +218 -0
  93. package/dist/db/core/fields/field-inference.d.ts.map +1 -0
  94. package/dist/db/core/fields/field-options-integration.d.ts +90 -0
  95. package/dist/db/core/fields/field-options-integration.d.ts.map +1 -0
  96. package/dist/db/core/fields/field-types.d.ts +182 -0
  97. package/dist/db/core/fields/field-types.d.ts.map +1 -0
  98. package/dist/db/core/fields/id-generator.d.ts +19 -0
  99. package/dist/db/core/fields/id-generator.d.ts.map +1 -0
  100. package/dist/db/core/fields/index.d.ts +8 -0
  101. package/dist/db/core/fields/index.d.ts.map +1 -0
  102. package/dist/db/core/fields/superjson-utils.d.ts +34 -0
  103. package/dist/db/core/fields/superjson-utils.d.ts.map +1 -0
  104. package/dist/db/core/fields/zod-fields.d.ts +1011 -0
  105. package/dist/db/core/fields/zod-fields.d.ts.map +1 -0
  106. package/dist/db/core/get-schema.d.ts +36 -0
  107. package/dist/db/core/get-schema.d.ts.map +1 -0
  108. package/dist/db/core/types.d.ts +41 -0
  109. package/dist/db/core/types.d.ts.map +1 -0
  110. package/dist/db/create-registry.d.ts +760 -0
  111. package/dist/db/create-registry.d.ts.map +1 -0
  112. package/dist/db/hooks/create-hooks.d.ts +32 -0
  113. package/dist/db/hooks/create-hooks.d.ts.map +1 -0
  114. package/dist/db/hooks/index.d.ts +40 -0
  115. package/dist/db/hooks/index.d.ts.map +1 -0
  116. package/dist/db/hooks/types.d.ts +133 -0
  117. package/dist/db/hooks/types.d.ts.map +1 -0
  118. package/dist/db/hooks/update-hooks.d.ts +33 -0
  119. package/dist/db/hooks/update-hooks.d.ts.map +1 -0
  120. package/dist/db/hooks/update-many-hooks.d.ts +55 -0
  121. package/dist/db/hooks/update-many-hooks.d.ts.map +1 -0
  122. package/dist/db/hooks/utils.d.ts +62 -0
  123. package/dist/db/hooks/utils.d.ts.map +1 -0
  124. package/dist/db/hooks/with-hooks-factory.d.ts +33 -0
  125. package/dist/db/hooks/with-hooks-factory.d.ts.map +1 -0
  126. package/dist/db/index.cjs +2458 -0
  127. package/dist/db/index.d.ts +11 -0
  128. package/dist/db/index.d.ts.map +1 -0
  129. package/dist/db/index.js +2404 -0
  130. package/dist/db/migration/get-migration.d.ts +32 -0
  131. package/dist/db/migration/get-migration.d.ts.map +1 -0
  132. package/dist/db/migration/get-schema/get-schema.d.ts +27 -0
  133. package/dist/db/migration/get-schema/get-schema.d.ts.map +1 -0
  134. package/dist/db/migration/get-schema/index.d.ts +21 -0
  135. package/dist/db/migration/get-schema/index.d.ts.map +1 -0
  136. package/dist/db/migration/get-schema/process-fields.d.ts +16 -0
  137. package/dist/db/migration/get-schema/process-fields.d.ts.map +1 -0
  138. package/dist/db/migration/get-schema/process-tables.d.ts +13 -0
  139. package/dist/db/migration/get-schema/process-tables.d.ts.map +1 -0
  140. package/dist/db/migration/get-schema/types.d.ts +17 -0
  141. package/dist/db/migration/get-schema/types.d.ts.map +1 -0
  142. package/dist/db/migration/index.cjs +1613 -0
  143. package/dist/db/migration/index.d.ts +14 -0
  144. package/dist/db/migration/index.d.ts.map +1 -0
  145. package/dist/db/migration/index.js +1571 -0
  146. package/dist/db/migration/migration-builders.d.ts +28 -0
  147. package/dist/db/migration/migration-builders.d.ts.map +1 -0
  148. package/dist/db/migration/migration-execution.d.ts +12 -0
  149. package/dist/db/migration/migration-execution.d.ts.map +1 -0
  150. package/dist/db/migration/schema-comparison.d.ts +54 -0
  151. package/dist/db/migration/schema-comparison.d.ts.map +1 -0
  152. package/dist/db/migration/type-mapping.d.ts +86 -0
  153. package/dist/db/migration/type-mapping.d.ts.map +1 -0
  154. package/dist/db/migration/types.d.ts +37 -0
  155. package/dist/db/migration/types.d.ts.map +1 -0
  156. package/dist/db/schema/audit-log/index.d.ts +4 -0
  157. package/dist/db/schema/audit-log/index.d.ts.map +1 -0
  158. package/dist/db/schema/audit-log/registry.d.ts +128 -0
  159. package/dist/db/schema/audit-log/registry.d.ts.map +1 -0
  160. package/dist/db/schema/audit-log/schema.d.ts +67 -0
  161. package/dist/db/schema/audit-log/schema.d.ts.map +1 -0
  162. package/dist/db/schema/audit-log/table.d.ts +175 -0
  163. package/dist/db/schema/audit-log/table.d.ts.map +1 -0
  164. package/dist/db/schema/audit-log/types.d.ts +29 -0
  165. package/dist/db/schema/audit-log/types.d.ts.map +1 -0
  166. package/dist/db/schema/consent/index.d.ts +4 -0
  167. package/dist/db/schema/consent/index.d.ts.map +1 -0
  168. package/dist/db/schema/consent/registry.d.ts +318 -0
  169. package/dist/db/schema/consent/registry.d.ts.map +1 -0
  170. package/dist/db/schema/consent/schema.d.ts +135 -0
  171. package/dist/db/schema/consent/schema.d.ts.map +1 -0
  172. package/dist/db/schema/consent/table.d.ts +245 -0
  173. package/dist/db/schema/consent/table.d.ts.map +1 -0
  174. package/dist/db/schema/consent/types.d.ts +37 -0
  175. package/dist/db/schema/consent/types.d.ts.map +1 -0
  176. package/dist/db/schema/consent-geo-location/index.d.ts +4 -0
  177. package/dist/db/schema/consent-geo-location/index.d.ts.map +1 -0
  178. package/dist/db/schema/consent-geo-location/registry.d.ts +96 -0
  179. package/dist/db/schema/consent-geo-location/registry.d.ts.map +1 -0
  180. package/dist/db/schema/consent-geo-location/schema.d.ts +71 -0
  181. package/dist/db/schema/consent-geo-location/schema.d.ts.map +1 -0
  182. package/dist/db/schema/consent-geo-location/table.d.ts +167 -0
  183. package/dist/db/schema/consent-geo-location/table.d.ts.map +1 -0
  184. package/dist/db/schema/consent-geo-location/types.d.ts +21 -0
  185. package/dist/db/schema/consent-geo-location/types.d.ts.map +1 -0
  186. package/dist/db/schema/consent-policy/index.d.ts +4 -0
  187. package/dist/db/schema/consent-policy/index.d.ts.map +1 -0
  188. package/dist/db/schema/consent-policy/registry.d.ts +186 -0
  189. package/dist/db/schema/consent-policy/registry.d.ts.map +1 -0
  190. package/dist/db/schema/consent-policy/schema.d.ts +68 -0
  191. package/dist/db/schema/consent-policy/schema.d.ts.map +1 -0
  192. package/dist/db/schema/consent-policy/table.d.ts +147 -0
  193. package/dist/db/schema/consent-policy/table.d.ts.map +1 -0
  194. package/dist/db/schema/consent-policy/types.d.ts +28 -0
  195. package/dist/db/schema/consent-policy/types.d.ts.map +1 -0
  196. package/dist/db/schema/consent-purpose/index.d.ts +4 -0
  197. package/dist/db/schema/consent-purpose/index.d.ts.map +1 -0
  198. package/dist/db/schema/consent-purpose/registry.d.ts +136 -0
  199. package/dist/db/schema/consent-purpose/registry.d.ts.map +1 -0
  200. package/dist/db/schema/consent-purpose/schema.d.ts +79 -0
  201. package/dist/db/schema/consent-purpose/schema.d.ts.map +1 -0
  202. package/dist/db/schema/consent-purpose/table.d.ts +161 -0
  203. package/dist/db/schema/consent-purpose/table.d.ts.map +1 -0
  204. package/dist/db/schema/consent-purpose/types.d.ts +16 -0
  205. package/dist/db/schema/consent-purpose/types.d.ts.map +1 -0
  206. package/dist/db/schema/consent-purpose-junction/index.d.ts +4 -0
  207. package/dist/db/schema/consent-purpose-junction/index.d.ts.map +1 -0
  208. package/dist/db/schema/consent-purpose-junction/registry.d.ts +109 -0
  209. package/dist/db/schema/consent-purpose-junction/registry.d.ts.map +1 -0
  210. package/dist/db/schema/consent-purpose-junction/schema.d.ts +57 -0
  211. package/dist/db/schema/consent-purpose-junction/schema.d.ts.map +1 -0
  212. package/dist/db/schema/consent-purpose-junction/table.d.ts +138 -0
  213. package/dist/db/schema/consent-purpose-junction/table.d.ts.map +1 -0
  214. package/dist/db/schema/consent-purpose-junction/types.d.ts +14 -0
  215. package/dist/db/schema/consent-purpose-junction/types.d.ts.map +1 -0
  216. package/dist/db/schema/consent-record/index.d.ts +4 -0
  217. package/dist/db/schema/consent-record/index.d.ts.map +1 -0
  218. package/dist/db/schema/consent-record/registry.d.ts +119 -0
  219. package/dist/db/schema/consent-record/registry.d.ts.map +1 -0
  220. package/dist/db/schema/consent-record/schema.d.ts +57 -0
  221. package/dist/db/schema/consent-record/schema.d.ts.map +1 -0
  222. package/dist/db/schema/consent-record/table.d.ts +123 -0
  223. package/dist/db/schema/consent-record/table.d.ts.map +1 -0
  224. package/dist/db/schema/consent-record/types.d.ts +21 -0
  225. package/dist/db/schema/consent-record/types.d.ts.map +1 -0
  226. package/dist/db/schema/consent-withdrawal/index.d.ts +4 -0
  227. package/dist/db/schema/consent-withdrawal/index.d.ts.map +1 -0
  228. package/dist/db/schema/consent-withdrawal/registry.d.ts +134 -0
  229. package/dist/db/schema/consent-withdrawal/registry.d.ts.map +1 -0
  230. package/dist/db/schema/consent-withdrawal/schema.d.ts +67 -0
  231. package/dist/db/schema/consent-withdrawal/schema.d.ts.map +1 -0
  232. package/dist/db/schema/consent-withdrawal/table.d.ts +170 -0
  233. package/dist/db/schema/consent-withdrawal/table.d.ts.map +1 -0
  234. package/dist/db/schema/consent-withdrawal/types.d.ts +28 -0
  235. package/dist/db/schema/consent-withdrawal/types.d.ts.map +1 -0
  236. package/dist/db/schema/definition.d.ts +1100 -0
  237. package/dist/db/schema/definition.d.ts.map +1 -0
  238. package/dist/db/schema/domain/index.d.ts +4 -0
  239. package/dist/db/schema/domain/index.d.ts.map +1 -0
  240. package/dist/db/schema/domain/registry.d.ts +169 -0
  241. package/dist/db/schema/domain/registry.d.ts.map +1 -0
  242. package/dist/db/schema/domain/schema.d.ts +60 -0
  243. package/dist/db/schema/domain/schema.d.ts.map +1 -0
  244. package/dist/db/schema/domain/table.d.ts +140 -0
  245. package/dist/db/schema/domain/table.d.ts.map +1 -0
  246. package/dist/db/schema/domain/types.d.ts +27 -0
  247. package/dist/db/schema/domain/types.d.ts.map +1 -0
  248. package/dist/db/schema/geo-location/index.d.ts +4 -0
  249. package/dist/db/schema/geo-location/index.d.ts.map +1 -0
  250. package/dist/db/schema/geo-location/registry.d.ts +114 -0
  251. package/dist/db/schema/geo-location/registry.d.ts.map +1 -0
  252. package/dist/db/schema/geo-location/schema.d.ts +58 -0
  253. package/dist/db/schema/geo-location/schema.d.ts.map +1 -0
  254. package/dist/db/schema/geo-location/table.d.ts +132 -0
  255. package/dist/db/schema/geo-location/table.d.ts.map +1 -0
  256. package/dist/db/schema/geo-location/types.d.ts +17 -0
  257. package/dist/db/schema/geo-location/types.d.ts.map +1 -0
  258. package/dist/db/schema/index.d.ts +85 -0
  259. package/dist/db/schema/index.d.ts.map +1 -0
  260. package/dist/db/schema/parser.d.ts +183 -0
  261. package/dist/db/schema/parser.d.ts.map +1 -0
  262. package/dist/db/schema/schemas.d.ts +383 -0
  263. package/dist/db/schema/schemas.d.ts.map +1 -0
  264. package/dist/db/schema/subject/index.d.ts +4 -0
  265. package/dist/db/schema/subject/index.d.ts.map +1 -0
  266. package/dist/db/schema/subject/registry.d.ts +141 -0
  267. package/dist/db/schema/subject/registry.d.ts.map +1 -0
  268. package/dist/db/schema/subject/schema.d.ts +56 -0
  269. package/dist/db/schema/subject/schema.d.ts.map +1 -0
  270. package/dist/db/schema/subject/table.d.ts +136 -0
  271. package/dist/db/schema/subject/table.d.ts.map +1 -0
  272. package/dist/db/schema/subject/types.d.ts +22 -0
  273. package/dist/db/schema/subject/types.d.ts.map +1 -0
  274. package/dist/db/schema/types.d.ts +136 -0
  275. package/dist/db/schema/types.d.ts.map +1 -0
  276. package/dist/db/utils/adapter-factory.d.ts +21 -0
  277. package/dist/db/utils/adapter-factory.d.ts.map +1 -0
  278. package/dist/db/utils/index.d.ts +10 -0
  279. package/dist/db/utils/index.d.ts.map +1 -0
  280. package/dist/db/utils.d.ts +4 -0
  281. package/dist/db/utils.d.ts.map +1 -0
  282. package/dist/error/codes.cjs +68 -0
  283. package/dist/error/codes.d.ts +175 -0
  284. package/dist/error/codes.d.ts.map +1 -0
  285. package/dist/error/codes.js +35 -0
  286. package/dist/error/error.d.ts +79 -0
  287. package/dist/error/error.d.ts.map +1 -0
  288. package/dist/error/index.cjs +172 -0
  289. package/dist/error/index.d.ts +9 -0
  290. package/dist/error/index.d.ts.map +1 -0
  291. package/dist/error/index.js +129 -0
  292. package/dist/error/logging.d.ts +25 -0
  293. package/dist/error/logging.d.ts.map +1 -0
  294. package/dist/error/pipeline.d.ts +19 -0
  295. package/dist/error/pipeline.d.ts.map +1 -0
  296. package/dist/error/recovery.d.ts +22 -0
  297. package/dist/error/recovery.d.ts.map +1 -0
  298. package/dist/error/results.d.ts +56 -0
  299. package/dist/error/results.d.ts.map +1 -0
  300. package/dist/index.cjs +4777 -0
  301. package/dist/index.d.ts +46 -0
  302. package/dist/index.d.ts.map +1 -0
  303. package/dist/index.js +4708 -0
  304. package/dist/init.d.ts +52 -0
  305. package/dist/init.d.ts.map +1 -0
  306. package/dist/init.test.d.ts +2 -0
  307. package/dist/init.test.d.ts.map +1 -0
  308. package/dist/integrations/index.cjs +281 -0
  309. package/dist/integrations/index.d.ts +7 -0
  310. package/dist/integrations/index.d.ts.map +1 -0
  311. package/dist/integrations/index.js +248 -0
  312. package/dist/integrations/next.cjs +131 -0
  313. package/dist/integrations/next.d.ts +29 -0
  314. package/dist/integrations/next.d.ts.map +1 -0
  315. package/dist/integrations/next.js +99 -0
  316. package/dist/integrations/react.cjs +182 -0
  317. package/dist/integrations/react.d.ts +257 -0
  318. package/dist/integrations/react.d.ts.map +1 -0
  319. package/dist/integrations/react.js +150 -0
  320. package/dist/plugins/geo/index.d.ts +2 -0
  321. package/dist/plugins/geo/index.d.ts.map +1 -0
  322. package/dist/test/utils.d.ts +65 -0
  323. package/dist/test/utils.d.ts.map +1 -0
  324. package/dist/types/api.d.ts +89 -0
  325. package/dist/types/api.d.ts.map +1 -0
  326. package/dist/types/context.d.ts +205 -0
  327. package/dist/types/context.d.ts.map +1 -0
  328. package/dist/types/helper.d.ts +78 -0
  329. package/dist/types/helper.d.ts.map +1 -0
  330. package/dist/types/index.cjs +19 -0
  331. package/dist/types/index.d.ts +6 -0
  332. package/dist/types/index.d.ts.map +1 -0
  333. package/dist/types/index.js +0 -0
  334. package/dist/types/options.d.ts +172 -0
  335. package/dist/types/options.d.ts.map +1 -0
  336. package/dist/types/plugins.d.ts +442 -0
  337. package/dist/types/plugins.d.ts.map +1 -0
  338. package/dist/utils/env.d.ts +77 -0
  339. package/dist/utils/env.d.ts.map +1 -0
  340. package/dist/utils/hide-metadata.d.ts +22 -0
  341. package/dist/utils/hide-metadata.d.ts.map +1 -0
  342. package/dist/utils/index.cjs +268 -0
  343. package/dist/utils/index.d.ts +18 -0
  344. package/dist/utils/index.d.ts.map +1 -0
  345. package/dist/utils/index.js +210 -0
  346. package/dist/utils/ip.d.ts +10 -0
  347. package/dist/utils/ip.d.ts.map +1 -0
  348. package/dist/utils/json.d.ts +14 -0
  349. package/dist/utils/json.d.ts.map +1 -0
  350. package/dist/utils/logger.d.ts +108 -0
  351. package/dist/utils/logger.d.ts.map +1 -0
  352. package/dist/utils/url.d.ts +87 -0
  353. package/dist/utils/url.d.ts.map +1 -0
  354. package/dist/utils/wildcard.d.ts +46 -0
  355. package/dist/utils/wildcard.d.ts.map +1 -0
  356. package/knip.json +37 -0
  357. package/package.json +146 -0
  358. package/rslib.config.ts +104 -0
  359. package/src/api/call.ts +177 -0
  360. package/src/api/index.ts +303 -0
  361. package/src/api/middlewares/index.ts +38 -0
  362. package/src/api/middlewares/origin-check.ts +260 -0
  363. package/src/api/middlewares/validate-context.ts +175 -0
  364. package/src/api/routes/__tests__/consent.test.ts +270 -0
  365. package/src/api/routes/__tests__/status.test.ts +36 -0
  366. package/src/api/routes/error.ts +130 -0
  367. package/src/api/routes/generate-consent-receipt.ts +244 -0
  368. package/src/api/routes/get-consent-history.ts +128 -0
  369. package/src/api/routes/get-consent-policy.ts +327 -0
  370. package/src/api/routes/get-consent.ts +230 -0
  371. package/src/api/routes/index.ts +12 -0
  372. package/src/api/routes/ok.ts +45 -0
  373. package/src/api/routes/set-consent.ts +328 -0
  374. package/src/api/routes/show-consent-banner.ts +149 -0
  375. package/src/api/routes/status.ts +62 -0
  376. package/src/api/routes/verify-consent.ts +272 -0
  377. package/src/api/routes/withdraw-consent.ts +293 -0
  378. package/src/api/to-endpoints.ts +371 -0
  379. package/src/client/index.ts +471 -0
  380. package/src/client/types.ts +458 -0
  381. package/src/core.test.ts +303 -0
  382. package/src/core.ts +267 -0
  383. package/src/db/adapters/drizzle-adapter/drizzle-adapter.ts +711 -0
  384. package/src/db/adapters/drizzle-adapter/index.ts +1 -0
  385. package/src/db/adapters/kysely-adapter/dialect.ts +192 -0
  386. package/src/db/adapters/kysely-adapter/index.ts +3 -0
  387. package/src/db/adapters/kysely-adapter/kysely-adapter.ts +1168 -0
  388. package/src/db/adapters/kysely-adapter/types.ts +307 -0
  389. package/src/db/adapters/memory-adapter/index.ts +1 -0
  390. package/src/db/adapters/memory-adapter/memory-adapter.ts +648 -0
  391. package/src/db/adapters/prisma-adapter/index.ts +1 -0
  392. package/src/db/adapters/prisma-adapter/prisma-adapter.ts +586 -0
  393. package/src/db/adapters/types.ts +203 -0
  394. package/src/db/adapters/utils.ts +51 -0
  395. package/src/db/core/fields/field-factory.ts +804 -0
  396. package/src/db/core/fields/field-inference.ts +298 -0
  397. package/src/db/core/fields/field-options-integration.ts +135 -0
  398. package/src/db/core/fields/field-types.ts +233 -0
  399. package/src/db/core/fields/id-generator.ts +57 -0
  400. package/src/db/core/fields/index.ts +56 -0
  401. package/src/db/core/fields/superjson-utils.ts +155 -0
  402. package/src/db/core/fields/zod-fields.ts +269 -0
  403. package/src/db/core/get-schema.ts +102 -0
  404. package/src/db/core/types.ts +52 -0
  405. package/src/db/create-registry.ts +31 -0
  406. package/src/db/hooks/create-hooks.ts +88 -0
  407. package/src/db/hooks/index.ts +39 -0
  408. package/src/db/hooks/types.ts +164 -0
  409. package/src/db/hooks/update-hooks.ts +91 -0
  410. package/src/db/hooks/update-many-hooks.ts +176 -0
  411. package/src/db/hooks/utils.ts +151 -0
  412. package/src/db/hooks/with-hooks-factory.ts +68 -0
  413. package/src/db/index.ts +32 -0
  414. package/src/db/migration/get-migration.ts +89 -0
  415. package/src/db/migration/get-schema/get-schema.ts +44 -0
  416. package/src/db/migration/get-schema/index.ts +20 -0
  417. package/src/db/migration/get-schema/process-fields.ts +66 -0
  418. package/src/db/migration/get-schema/process-tables.ts +68 -0
  419. package/src/db/migration/get-schema/types.ts +18 -0
  420. package/src/db/migration/index.ts +18 -0
  421. package/src/db/migration/migration-builders.ts +170 -0
  422. package/src/db/migration/migration-execution.ts +79 -0
  423. package/src/db/migration/schema-comparison.ts +216 -0
  424. package/src/db/migration/type-mapping.ts +255 -0
  425. package/src/db/migration/types.ts +46 -0
  426. package/src/db/schema/audit-log/index.ts +3 -0
  427. package/src/db/schema/audit-log/registry.ts +228 -0
  428. package/src/db/schema/audit-log/schema.ts +46 -0
  429. package/src/db/schema/audit-log/table.ts +185 -0
  430. package/src/db/schema/audit-log/types.ts +29 -0
  431. package/src/db/schema/consent/index.ts +3 -0
  432. package/src/db/schema/consent/registry.ts +381 -0
  433. package/src/db/schema/consent/schema.ts +65 -0
  434. package/src/db/schema/consent/table.ts +220 -0
  435. package/src/db/schema/consent/types.ts +39 -0
  436. package/src/db/schema/consent-geo-location/index.ts +3 -0
  437. package/src/db/schema/consent-geo-location/registry.ts +124 -0
  438. package/src/db/schema/consent-geo-location/schema.ts +51 -0
  439. package/src/db/schema/consent-geo-location/table.ts +169 -0
  440. package/src/db/schema/consent-geo-location/types.ts +21 -0
  441. package/src/db/schema/consent-policy/index.ts +3 -0
  442. package/src/db/schema/consent-policy/registry.ts +313 -0
  443. package/src/db/schema/consent-policy/schema.ts +47 -0
  444. package/src/db/schema/consent-policy/table.ts +141 -0
  445. package/src/db/schema/consent-policy/types.ts +28 -0
  446. package/src/db/schema/consent-purpose/index.ts +3 -0
  447. package/src/db/schema/consent-purpose/registry.ts +188 -0
  448. package/src/db/schema/consent-purpose/schema.ts +58 -0
  449. package/src/db/schema/consent-purpose/table.ts +154 -0
  450. package/src/db/schema/consent-purpose/types.ts +16 -0
  451. package/src/db/schema/consent-purpose-junction/index.ts +3 -0
  452. package/src/db/schema/consent-purpose-junction/registry.ts +189 -0
  453. package/src/db/schema/consent-purpose-junction/schema.ts +49 -0
  454. package/src/db/schema/consent-purpose-junction/table.ts +142 -0
  455. package/src/db/schema/consent-purpose-junction/types.ts +14 -0
  456. package/src/db/schema/consent-record/index.ts +3 -0
  457. package/src/db/schema/consent-record/registry.ts +209 -0
  458. package/src/db/schema/consent-record/schema.ts +42 -0
  459. package/src/db/schema/consent-record/table.ts +124 -0
  460. package/src/db/schema/consent-record/types.ts +21 -0
  461. package/src/db/schema/consent-withdrawal/index.ts +3 -0
  462. package/src/db/schema/consent-withdrawal/registry.ts +219 -0
  463. package/src/db/schema/consent-withdrawal/schema.ts +48 -0
  464. package/src/db/schema/consent-withdrawal/table.ts +181 -0
  465. package/src/db/schema/consent-withdrawal/types.ts +29 -0
  466. package/src/db/schema/definition.ts +196 -0
  467. package/src/db/schema/domain/index.ts +3 -0
  468. package/src/db/schema/domain/registry.ts +272 -0
  469. package/src/db/schema/domain/schema.ts +43 -0
  470. package/src/db/schema/domain/table.ts +137 -0
  471. package/src/db/schema/domain/types.ts +27 -0
  472. package/src/db/schema/geo-location/index.ts +3 -0
  473. package/src/db/schema/geo-location/registry.ts +159 -0
  474. package/src/db/schema/geo-location/schema.ts +45 -0
  475. package/src/db/schema/geo-location/table.ts +148 -0
  476. package/src/db/schema/geo-location/types.ts +18 -0
  477. package/src/db/schema/index.ts +96 -0
  478. package/src/db/schema/parser.ts +417 -0
  479. package/src/db/schema/schemas.ts +35 -0
  480. package/src/db/schema/subject/index.ts +3 -0
  481. package/src/db/schema/subject/registry.ts +371 -0
  482. package/src/db/schema/subject/schema.ts +41 -0
  483. package/src/db/schema/subject/table.ts +139 -0
  484. package/src/db/schema/subject/types.ts +22 -0
  485. package/src/db/schema/types.ts +154 -0
  486. package/src/db/utils/adapter-factory.ts +64 -0
  487. package/src/db/utils/index.ts +10 -0
  488. package/src/db/utils.ts +42 -0
  489. package/src/docs/ADVANCED_JSON_HANDLING.md +99 -0
  490. package/src/docs/neverthrow.md +171 -0
  491. package/src/error/codes.ts +201 -0
  492. package/src/error/error.ts +145 -0
  493. package/src/error/index.ts +23 -0
  494. package/src/error/logging.ts +52 -0
  495. package/src/error/pipeline.ts +57 -0
  496. package/src/error/recovery.ts +45 -0
  497. package/src/error/results.ts +100 -0
  498. package/src/index.ts +79 -0
  499. package/src/init.test.ts +235 -0
  500. package/src/init.ts +261 -0
  501. package/src/integrations/index.ts +10 -0
  502. package/src/integrations/next.ts +136 -0
  503. package/src/integrations/react.ts +567 -0
  504. package/src/plugins/geo/index.ts +563 -0
  505. package/src/test/utils.ts +244 -0
  506. package/src/types/api.ts +101 -0
  507. package/src/types/context.ts +235 -0
  508. package/src/types/helper.ts +87 -0
  509. package/src/types/index.ts +5 -0
  510. package/src/types/options.ts +189 -0
  511. package/src/types/plugins.ts +538 -0
  512. package/src/utils/env.ts +103 -0
  513. package/src/utils/hide-metadata.ts +21 -0
  514. package/src/utils/index.ts +17 -0
  515. package/src/utils/ip.ts +45 -0
  516. package/src/utils/json.ts +19 -0
  517. package/src/utils/logger.ts +252 -0
  518. package/src/utils/url.ts +194 -0
  519. package/src/utils/wildcard.ts +253 -0
  520. package/tsconfig.json +12 -0
  521. package/vitest.config.ts +14 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,4777 @@
1
+ var __webpack_modules__ = {
2
+ "./src/client/index.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
3
+ "use strict";
4
+ __webpack_require__.d(__webpack_exports__, {
5
+ D: ()=>createConsentClient,
6
+ G: ()=>c15tClient
7
+ });
8
+ class c15tClient {
9
+ baseURL;
10
+ headers;
11
+ customFetch;
12
+ constructor(options){
13
+ this.baseURL = options.baseURL.endsWith('/') ? options.baseURL.slice(0, -1) : options.baseURL;
14
+ this.headers = {
15
+ 'Content-Type': 'application/json',
16
+ ...options.headers
17
+ };
18
+ this.customFetch = options.fetchOptions?.customFetchImpl;
19
+ }
20
+ async fetcher(path, options = {}) {
21
+ try {
22
+ const url = new URL(path, this.baseURL);
23
+ if (options.query) {
24
+ for (const [key, value] of Object.entries(options.query))if (void 0 !== value) {
25
+ if (Array.isArray(value)) for (const v of value)url.searchParams.append(key, String(v));
26
+ else url.searchParams.append(key, String(value));
27
+ }
28
+ }
29
+ const fetchOptions = {
30
+ method: options.method || 'GET',
31
+ headers: {
32
+ ...this.headers,
33
+ ...options.headers
34
+ }
35
+ };
36
+ if (options.body && 'GET' !== fetchOptions.method) fetchOptions.body = JSON.stringify(options.body);
37
+ const fetchImpl = this.customFetch || fetch;
38
+ const response = await fetchImpl(url.toString(), fetchOptions);
39
+ let data = null;
40
+ let error = null;
41
+ if (204 !== response.status) try {
42
+ data = await response.json();
43
+ } catch (err) {
44
+ if (response.ok) data = null;
45
+ else error = new Error(`Failed to parse response: ${err.message}`);
46
+ }
47
+ const context = {
48
+ data,
49
+ response,
50
+ error: error ? {
51
+ message: error.message,
52
+ status: response.status
53
+ } : null,
54
+ ok: response.ok
55
+ };
56
+ if (response.ok) {
57
+ if (options.onSuccess) await options.onSuccess(context);
58
+ } else {
59
+ if (options.onError) await options.onError(context);
60
+ if (options.throw) {
61
+ const error = new Error(`Request failed with status ${response.status}`);
62
+ Object.assign(error, {
63
+ status: response.status,
64
+ data
65
+ });
66
+ throw error;
67
+ }
68
+ }
69
+ return context;
70
+ } catch (error) {
71
+ if (options.onError) {
72
+ const errorObj = error;
73
+ const context = {
74
+ data: null,
75
+ error: {
76
+ message: errorObj.message || 'Request failed',
77
+ status: error.status || 500,
78
+ code: error.code
79
+ },
80
+ ok: false,
81
+ response: null
82
+ };
83
+ await options.onError(context);
84
+ if (options.throw) throw error;
85
+ return context;
86
+ }
87
+ if (options.throw) throw error;
88
+ return {
89
+ data: null,
90
+ error: {
91
+ message: error.message || 'Request failed',
92
+ status: error.status || 500,
93
+ code: error.code
94
+ },
95
+ ok: false,
96
+ response: null
97
+ };
98
+ }
99
+ }
100
+ async listPurposes(options) {
101
+ return this.fetcher('/list-purposes', {
102
+ method: 'GET',
103
+ ...options
104
+ });
105
+ }
106
+ async $fetch(path, options) {
107
+ return this.fetcher(path, options);
108
+ }
109
+ }
110
+ function createConsentClient(options) {
111
+ return new c15tClient(options);
112
+ }
113
+ },
114
+ "./src/client/types.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
115
+ "use strict";
116
+ __webpack_require__.r(__webpack_exports__);
117
+ },
118
+ "./src/core.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
119
+ "use strict";
120
+ __webpack_require__.d(__webpack_exports__, {
121
+ w: ()=>c15tInstance
122
+ });
123
+ const external_better_call_namespaceObject = require("better-call");
124
+ var env = __webpack_require__("./src/utils/env.ts");
125
+ function getIp(req, options) {
126
+ if (options.advanced?.ipAddress?.disableIpTracking) return null;
127
+ const testIP = '127.0.0.1';
128
+ if (env.Y8) return testIP;
129
+ const ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders;
130
+ const keys = ipHeaders || [
131
+ 'x-client-ip',
132
+ 'x-forwarded-for',
133
+ 'cf-connecting-ip',
134
+ 'fastly-client-ip',
135
+ 'x-real-ip',
136
+ 'x-cluster-client-ip',
137
+ 'x-forwarded',
138
+ 'forwarded-for',
139
+ 'forwarded'
140
+ ];
141
+ const headers = req instanceof Request ? req.headers : req;
142
+ for (const key of keys){
143
+ const value = headers.get(key);
144
+ if (value) {
145
+ const ip = value.split(',')[0]?.trim();
146
+ if (ip) return ip;
147
+ }
148
+ }
149
+ return null;
150
+ }
151
+ var utils_logger = __webpack_require__("./src/utils/logger.ts");
152
+ var src_error = __webpack_require__("./src/error/index.ts");
153
+ var utils_url = __webpack_require__("./src/utils/url.ts");
154
+ function escapeRegExpChar(char) {
155
+ if ('-' === char || '^' === char || '$' === char || '+' === char || '.' === char || '(' === char || ')' === char || '|' === char || '[' === char || ']' === char || '{' === char || '}' === char || '*' === char || '?' === char || '\\' === char) return `\\${char}`;
156
+ return char;
157
+ }
158
+ function escapeRegExpString(str) {
159
+ let result = '';
160
+ for (const char of str)result += escapeRegExpChar(char);
161
+ return result;
162
+ }
163
+ function wildcard_transform(pattern, separator = true) {
164
+ if (Array.isArray(pattern)) {
165
+ const regExpPatterns = pattern.map((p)=>`^${wildcard_transform(p, separator)}$`);
166
+ return `(?:${regExpPatterns.join('|')})`;
167
+ }
168
+ let separatorSplitter = '';
169
+ let separatorMatcher = '';
170
+ let wildcard = './';
171
+ if (true === separator) {
172
+ separatorSplitter = '/';
173
+ separatorMatcher = '[/\\\\]';
174
+ wildcard = '[^/\\\\]';
175
+ } else if (separator) {
176
+ separatorSplitter = separator;
177
+ separatorMatcher = escapeRegExpString(separatorSplitter);
178
+ if (separatorMatcher.length > 1) {
179
+ separatorMatcher = `(?:${separatorMatcher})`;
180
+ wildcard = `((?!${separatorMatcher}).)`;
181
+ } else wildcard = `[^${separatorMatcher}]`;
182
+ }
183
+ const requiredSeparator = separator ? `${separatorMatcher}+?` : '';
184
+ const optionalSeparator = separator ? `${separatorMatcher}*?` : '';
185
+ const segments = separator ? pattern.split(separatorSplitter) : [
186
+ pattern
187
+ ];
188
+ let result = '';
189
+ for(let s = 0; s < segments.length; s++){
190
+ const segment = segments[s];
191
+ const nextSegment = segments[s + 1];
192
+ let currentSeparator = '';
193
+ if (!!segment || !(s > 0)) {
194
+ if (separator) currentSeparator = s === segments.length - 1 ? optionalSeparator : '**' !== nextSegment ? requiredSeparator : '';
195
+ if (separator && '**' === segment) {
196
+ if (currentSeparator) {
197
+ result += 0 === s ? '' : currentSeparator;
198
+ result += `(?:${wildcard}*?${currentSeparator})*?`;
199
+ }
200
+ continue;
201
+ }
202
+ if ('string' == typeof segment) {
203
+ for(let c = 0; c < segment.length; c++){
204
+ const char = segment[c];
205
+ if ('\\' === char) {
206
+ if (c < segment.length - 1) {
207
+ const nextChar = segment[c + 1];
208
+ if (void 0 !== nextChar) {
209
+ result += escapeRegExpChar(nextChar);
210
+ c++;
211
+ }
212
+ }
213
+ } else if ('?' === char) result += wildcard;
214
+ else if ('*' === char) result += `${wildcard}*?`;
215
+ else if (char) result += escapeRegExpChar(char);
216
+ }
217
+ result += currentSeparator;
218
+ }
219
+ }
220
+ }
221
+ return result;
222
+ }
223
+ function isMatch(regexp, sample) {
224
+ if ('string' != typeof sample) throw new TypeError(`Sample must be a string, but ${typeof sample} given`);
225
+ return regexp.test(sample);
226
+ }
227
+ function wildcard_wildcardMatch(pattern, options) {
228
+ if ('string' != typeof pattern && !Array.isArray(pattern)) throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof pattern} given`);
229
+ const opts = 'string' == typeof options || 'boolean' == typeof options ? {
230
+ separator: options
231
+ } : options;
232
+ if (opts && !(void 0 === options || 'object' == typeof options && null !== options && !Array.isArray(options))) throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof options} given`);
233
+ const normalizedOptions = opts || {};
234
+ if ('\\' === normalizedOptions.separator) throw new Error('\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead');
235
+ const regexpPattern = wildcard_transform(pattern, normalizedOptions.separator);
236
+ const regexp = new RegExp(`^${regexpPattern}$`, normalizedOptions.flags);
237
+ const fn = isMatch.bind(null, regexp);
238
+ fn.options = normalizedOptions;
239
+ fn.pattern = pattern;
240
+ fn.regexp = regexp;
241
+ return fn;
242
+ }
243
+ const optionsMiddleware = (0, external_better_call_namespaceObject.createMiddleware)(async ()=>({}));
244
+ const call_createAuthMiddleware = external_better_call_namespaceObject.createMiddleware.create({
245
+ use: [
246
+ optionsMiddleware,
247
+ (0, external_better_call_namespaceObject.createMiddleware)(async ()=>({}))
248
+ ]
249
+ });
250
+ const createAuthEndpoint = external_better_call_namespaceObject.createEndpoint.create({
251
+ use: [
252
+ optionsMiddleware
253
+ ]
254
+ });
255
+ const VALID_RELATIVE_URL_REGEX = /^\/(?!\/|\\|%2f|%5c)[\w\-./]*(?:\?[\w\-./=&%]*)?$/;
256
+ const originCheckMiddleware = call_createAuthMiddleware(async (ctx)=>{
257
+ if (ctx.request?.method !== 'POST' || !ctx.request) return;
258
+ const { body, query, context } = ctx;
259
+ const originHeader = ctx.headers?.get('origin') || ctx.headers?.get('referer') || '';
260
+ const callbackURL = body?.callbackURL || query?.callbackURL;
261
+ const redirectURL = body?.redirectTo;
262
+ const errorCallbackURL = body?.errorCallbackURL;
263
+ const newSubjectCallbackURL = body?.newSubjectCallbackURL;
264
+ const trustedOrigins = Array.isArray(context.options.trustedOrigins) ? context.trustedOrigins : [
265
+ ...context.trustedOrigins,
266
+ ...context.options.trustedOrigins?.(ctx.request) || []
267
+ ];
268
+ const usesCookies = ctx.headers?.has('cookie');
269
+ const matchesPattern = (url, pattern)=>{
270
+ if (url.startsWith('/')) return false;
271
+ if (pattern.includes('*')) return wildcard_wildcardMatch(pattern)((0, utils_url.XF)(url));
272
+ const protocol = (0, utils_url.Ev)(url);
273
+ return 'http:' !== protocol && 'https:' !== protocol && protocol ? url.startsWith(pattern) : pattern === (0, utils_url.P$)(url);
274
+ };
275
+ const validateURL = (url, label)=>{
276
+ if (!url) return;
277
+ const isTrustedOrigin = trustedOrigins.some((origin)=>matchesPattern(url, origin) || url?.startsWith('/') && 'origin' !== label && VALID_RELATIVE_URL_REGEX.test(url));
278
+ if (!isTrustedOrigin) {
279
+ ctx.context.logger.error(`Invalid ${label}: ${url}`);
280
+ ctx.context.logger.info(`If it's a valid URL, please add ${url} to trustedOrigins in your auth config\n`, `Current list of trustedOrigins: ${trustedOrigins}`);
281
+ throw new src_error.kO('The URL provided is not from a trusted origin. Please ensure the URL is correctly configured in the trusted origins list.', {
282
+ code: src_error.H8.FORBIDDEN,
283
+ status: 403,
284
+ data: {
285
+ url,
286
+ label,
287
+ trustedOrigins
288
+ }
289
+ });
290
+ }
291
+ };
292
+ if (usesCookies && !ctx.context.options.advanced?.disableCSRFCheck) validateURL(originHeader, 'origin');
293
+ callbackURL && validateURL(callbackURL, 'callbackURL');
294
+ redirectURL && validateURL(redirectURL, 'redirectURL');
295
+ errorCallbackURL && validateURL(errorCallbackURL, 'errorCallbackURL');
296
+ newSubjectCallbackURL && validateURL(newSubjectCallbackURL, 'newSubjectCallbackURL');
297
+ });
298
+ function redactContext(context) {
299
+ if (!context || 'object' != typeof context) return {
300
+ type: typeof context
301
+ };
302
+ const typedContext = context;
303
+ return {
304
+ baseURL: typedContext.baseURL,
305
+ storageType: typedContext.storage?.constructor.name,
306
+ pluginsCount: Array.isArray(typedContext.plugins) ? typedContext.plugins.length : 0,
307
+ hasOptions: !!typedContext.options,
308
+ hasLogger: !!typedContext.logger,
309
+ hasPlugins: !!typedContext.plugins
310
+ };
311
+ }
312
+ function validatePlugins(plugins, initializedPlugins) {
313
+ if (!plugins?.length) return null;
314
+ const initializedNames = new Set(initializedPlugins?.map((p)=>p.id) ?? []);
315
+ const failedPlugins = plugins.filter((p)=>!initializedNames.has(p.id)).map((p)=>p.id);
316
+ return failedPlugins.length > 0 ? failedPlugins : null;
317
+ }
318
+ const validateContextMiddleware = call_createAuthMiddleware(async (ctx)=>{
319
+ const { context } = ctx;
320
+ if (!context || 'object' != typeof context) throw new src_error.kO('The context configuration is incomplete. Please ensure all required configuration options are provided and properly formatted.', {
321
+ code: src_error.H8.INVALID_CONFIGURATION,
322
+ status: 500,
323
+ data: redactContext(context)
324
+ });
325
+ const typedContext = context;
326
+ if (!typedContext.options) throw new src_error.kO('The context configuration is missing required options. Please ensure the options object is properly configured.', {
327
+ code: src_error.H8.INVALID_CONFIGURATION,
328
+ status: 500
329
+ });
330
+ if (typedContext.storage) {
331
+ const storage = typedContext.storage;
332
+ const requiredMethods = [
333
+ 'subjects',
334
+ 'records',
335
+ 'policies'
336
+ ];
337
+ const missingMethods = requiredMethods.filter((method)=>!(method in storage));
338
+ if (missingMethods.length > 0) typedContext.logger?.warn?.('Storage adapter missing methods', {
339
+ missingMethods,
340
+ storageType: storage.constructor.name
341
+ });
342
+ }
343
+ if (!typedContext.logger && 'production' === process.env.NODE_ENV) throw new src_error.kO('Logger is required in production environment. Please configure a logger for your application.', {
344
+ code: src_error.H8.INVALID_CONFIGURATION,
345
+ status: 500,
346
+ data: {
347
+ environment: process.env.NODE_ENV
348
+ }
349
+ });
350
+ const failedPlugins = validatePlugins(typedContext.options.plugins, typedContext.plugins);
351
+ if (failedPlugins) throw new src_error.kO('Plugin initialization failed. Some plugins could not be initialized properly. Please check your plugin configuration.', {
352
+ code: src_error.H8.PLUGIN_INITIALIZATION_FAILED,
353
+ status: 500,
354
+ data: {
355
+ failedPlugins
356
+ }
357
+ });
358
+ typedContext.logger?.debug?.('Context validation successful', {
359
+ baseURL: typedContext.baseURL,
360
+ storageType: typedContext.storage?.constructor.name,
361
+ pluginsCount: Array.isArray(typedContext.plugins) ? typedContext.plugins.length : 0
362
+ });
363
+ return {
364
+ context: typedContext
365
+ };
366
+ });
367
+ const external_zod_namespaceObject = require("zod");
368
+ const ConsentType = external_zod_namespaceObject.z["enum"]([
369
+ 'cookie_banner',
370
+ 'privacy_policy',
371
+ 'dpa',
372
+ 'terms_of_service',
373
+ 'marketing_communications',
374
+ 'age_verification',
375
+ 'other'
376
+ ]);
377
+ const baseConsentSchema = external_zod_namespaceObject.z.object({
378
+ subjectId: external_zod_namespaceObject.z.string().optional(),
379
+ externalSubjectId: external_zod_namespaceObject.z.string().optional(),
380
+ domain: external_zod_namespaceObject.z.string(),
381
+ type: ConsentType,
382
+ metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional()
383
+ });
384
+ const cookieBannerSchema = baseConsentSchema.extend({
385
+ type: external_zod_namespaceObject.z.literal('cookie_banner'),
386
+ preferences: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.boolean())
387
+ });
388
+ const policyBasedSchema = baseConsentSchema.extend({
389
+ type: external_zod_namespaceObject.z["enum"]([
390
+ 'privacy_policy',
391
+ 'dpa',
392
+ 'terms_of_service'
393
+ ]),
394
+ policyId: external_zod_namespaceObject.z.string().optional(),
395
+ preferences: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.boolean()).optional()
396
+ });
397
+ const otherConsentSchema = baseConsentSchema.extend({
398
+ type: external_zod_namespaceObject.z["enum"]([
399
+ 'marketing_communications',
400
+ 'age_verification',
401
+ 'other'
402
+ ]),
403
+ preferences: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.boolean()).optional()
404
+ });
405
+ const setConsentSchema = external_zod_namespaceObject.z.discriminatedUnion('type', [
406
+ cookieBannerSchema,
407
+ policyBasedSchema,
408
+ otherConsentSchema
409
+ ]);
410
+ const setConsent = createAuthEndpoint('/consent/set', {
411
+ method: 'POST',
412
+ body: setConsentSchema
413
+ }, async (ctx)=>{
414
+ try {
415
+ const body = setConsentSchema.parse(ctx.body);
416
+ const { type, subjectId, externalSubjectId, domain, metadata } = body;
417
+ const { registry, adapter } = ctx.context;
418
+ const subject = await registry.findOrCreateSubject({
419
+ subjectId,
420
+ externalSubjectId,
421
+ ipAddress: ctx.context.ipAddress || 'unknown'
422
+ });
423
+ if (!subject) throw new src_error.kO('A valid Subject ID is required to proceed with the consent operation. Please provide a Subject ID.', {
424
+ code: src_error.H8.MISSING_REQUIRED_PARAMETER,
425
+ status: 400
426
+ });
427
+ const domainRecord = await registry.findOrCreateDomain(domain);
428
+ const now = new Date();
429
+ let policyId;
430
+ let purposeIds = [];
431
+ if ('policyId' in body) {
432
+ const { policyId: pid } = body;
433
+ policyId = pid;
434
+ if (!policyId) throw new src_error.kO('A valid Policy ID is required to proceed with the consent operation. Please provide a Policy ID.', {
435
+ code: src_error.H8.MISSING_REQUIRED_PARAMETER,
436
+ status: 400
437
+ });
438
+ const policy = await registry.findConsentPolicyById(policyId);
439
+ if (!policy) throw new src_error.kO('The specified consent policy could not be found. Please verify the policy ID and try again.', {
440
+ code: src_error.H8.NOT_FOUND,
441
+ status: 404
442
+ });
443
+ if (!policy.isActive) throw new src_error.kO('The consent policy is no longer active and cannot be used. Please use an active policy version.', {
444
+ code: src_error.H8.CONFLICT,
445
+ status: 409
446
+ });
447
+ } else {
448
+ const policy = await registry.findOrCreatePolicy(type.replace('_', ' '));
449
+ if (!policy) throw new src_error.kO('Failed to create or find the required policy. Please try again later or contact support if the issue persists.', {
450
+ code: src_error.H8.FAILED_TO_CREATE_PURPOSE,
451
+ status: 500
452
+ });
453
+ policyId = policy.id;
454
+ }
455
+ if ('preferences' in body && body.preferences) purposeIds = await Promise.all(Object.entries(body.preferences).filter(([_, isConsented])=>isConsented).map(async ([purposeCode])=>{
456
+ let existingPurpose = await registry.findConsentPurposeByCode(purposeCode);
457
+ if (!existingPurpose) existingPurpose = await registry.createConsentPurpose({
458
+ code: purposeCode,
459
+ name: purposeCode,
460
+ description: `Auto-created consentPurpose for ${purposeCode}`,
461
+ isActive: true,
462
+ isEssential: false,
463
+ dataCategory: 'functional',
464
+ legalBasis: 'consent',
465
+ createdAt: now,
466
+ updatedAt: now
467
+ });
468
+ return existingPurpose.id;
469
+ }));
470
+ const result = await adapter.transaction({
471
+ callback: async (tx)=>{
472
+ const consentRecord = await tx.create({
473
+ model: 'consent',
474
+ data: {
475
+ subjectId: subject.id,
476
+ domainId: domainRecord.id,
477
+ policyId,
478
+ purposeIds,
479
+ status: 'active',
480
+ isActive: true,
481
+ givenAt: now,
482
+ history: []
483
+ }
484
+ });
485
+ const record = await tx.create({
486
+ model: 'consentRecord',
487
+ data: {
488
+ subjectId: subject.id,
489
+ consentId: consentRecord.id,
490
+ actionType: 'consent_given',
491
+ details: metadata,
492
+ createdAt: now
493
+ }
494
+ });
495
+ await tx.create({
496
+ model: 'auditLog',
497
+ data: {
498
+ subjectId: subject.id,
499
+ entityType: 'consent',
500
+ entityId: consentRecord.id,
501
+ actionType: 'consent_given',
502
+ details: {
503
+ consentId: consentRecord.id,
504
+ type
505
+ },
506
+ timestamp: now
507
+ }
508
+ });
509
+ return {
510
+ consent: consentRecord,
511
+ record
512
+ };
513
+ }
514
+ });
515
+ if (!result || !result.consent || !result.record) throw new src_error.kO('Failed to create the consent record. Please try again later or contact support if the issue persists.', {
516
+ code: src_error.H8.FAILED_TO_CREATE_CONSENT,
517
+ status: 500
518
+ });
519
+ return {
520
+ id: result.consent.id,
521
+ subjectId: subject.id,
522
+ externalSubjectId: subject.externalId ?? void 0,
523
+ domainId: domainRecord.id,
524
+ domain: domainRecord.name,
525
+ type,
526
+ status: result.consent.status,
527
+ recordId: result.record.id,
528
+ metadata,
529
+ givenAt: result.consent.givenAt.toISOString()
530
+ };
531
+ } catch (error) {
532
+ const context = ctx.context;
533
+ context.logger?.error?.('Error setting consent:', error);
534
+ if (error instanceof src_error.kO) throw error;
535
+ if (error instanceof external_zod_namespaceObject.z.ZodError) throw new src_error.kO('The consent data provided is invalid. Please ensure all required fields are correctly filled and formatted.', {
536
+ code: src_error.H8.BAD_REQUEST,
537
+ status: 400,
538
+ data: {
539
+ details: error.errors
540
+ }
541
+ });
542
+ throw new src_error.kO('Failed to set consent. Please try again later or contact support if the issue persists.', {
543
+ code: src_error.H8.FAILED_TO_CREATE_CONSENT,
544
+ status: 500,
545
+ data: {
546
+ error: error instanceof Error ? error.message : String(error)
547
+ }
548
+ });
549
+ }
550
+ });
551
+ const status_status = createAuthEndpoint('/status', {
552
+ method: 'GET'
553
+ }, async (ctx)=>{
554
+ const response = {
555
+ status: 'ok',
556
+ version: '1.0.0',
557
+ timestamp: new Date().toISOString(),
558
+ storage: {
559
+ type: ctx.context?.adapter?.id ?? 'Unavailable',
560
+ available: !!ctx.context?.adapter
561
+ }
562
+ };
563
+ return response;
564
+ });
565
+ const show_consent_banner_showConsentBanner = createAuthEndpoint('/show-consent-banner', {
566
+ method: 'GET',
567
+ metadata: {
568
+ openapi: {
569
+ responses: {
570
+ 200: {
571
+ description: 'Cookie Banner Requirement',
572
+ content: {
573
+ 'application/json': {
574
+ schema: {
575
+ type: 'object',
576
+ properties: {
577
+ showConsentBanner: {
578
+ type: 'boolean'
579
+ },
580
+ jurisdiction: {
581
+ type: 'object',
582
+ properties: {
583
+ code: {
584
+ type: 'string'
585
+ },
586
+ message: {
587
+ type: 'string'
588
+ }
589
+ }
590
+ },
591
+ location: {
592
+ type: 'object',
593
+ properties: {
594
+ countryCode: {
595
+ type: 'string'
596
+ },
597
+ regionCode: {
598
+ type: 'string'
599
+ }
600
+ }
601
+ }
602
+ }
603
+ }
604
+ }
605
+ }
606
+ }
607
+ }
608
+ }
609
+ }
610
+ }, async (c)=>{
611
+ const countryCode = c.headers?.get('cf-ipcountry') || c.headers?.get('x-vercel-ip-country') || c.headers?.get('x-amz-cf-ipcountry') || c.headers?.get('x-country-code');
612
+ const regionCode = c.headers?.get('x-vercel-ip-country-region') || c.headers?.get('x-region-code');
613
+ const { showConsentBanner, jurisdictionCode, message } = checkJurisdiction(countryCode ?? null);
614
+ return {
615
+ showConsentBanner,
616
+ jurisdiction: {
617
+ code: jurisdictionCode,
618
+ message
619
+ },
620
+ location: {
621
+ countryCode,
622
+ regionCode
623
+ }
624
+ };
625
+ });
626
+ function checkJurisdiction(countryCode) {
627
+ const jurisdictions = {
628
+ EU: new Set([
629
+ 'AT',
630
+ 'BE',
631
+ 'BG',
632
+ 'HR',
633
+ 'CY',
634
+ 'CZ',
635
+ 'DK',
636
+ 'EE',
637
+ 'FI',
638
+ 'FR',
639
+ 'DE',
640
+ 'GR',
641
+ 'HU',
642
+ 'IE',
643
+ 'IT',
644
+ 'LV',
645
+ 'LT',
646
+ 'LU',
647
+ 'MT',
648
+ 'NL',
649
+ 'PL',
650
+ 'PT',
651
+ 'RO',
652
+ 'SK',
653
+ 'SI',
654
+ 'ES',
655
+ 'SE'
656
+ ]),
657
+ EEA: new Set([
658
+ 'IS',
659
+ 'NO',
660
+ 'LI'
661
+ ]),
662
+ UK: new Set([
663
+ 'GB'
664
+ ]),
665
+ CH: new Set([
666
+ 'CH'
667
+ ]),
668
+ BR: new Set([
669
+ 'BR'
670
+ ]),
671
+ CA: new Set([
672
+ 'CA'
673
+ ]),
674
+ AU: new Set([
675
+ 'AU'
676
+ ]),
677
+ JP: new Set([
678
+ 'JP'
679
+ ]),
680
+ KR: new Set([
681
+ 'KR'
682
+ ])
683
+ };
684
+ let showConsentBanner = false;
685
+ let jurisdictionCode = 'NONE';
686
+ let message = 'No specific requirements';
687
+ if (countryCode) {
688
+ if (jurisdictions.EU.has(countryCode) || jurisdictions.EEA.has(countryCode) || jurisdictions.UK.has(countryCode)) {
689
+ showConsentBanner = true;
690
+ jurisdictionCode = 'GDPR';
691
+ message = 'GDPR or equivalent regulations require a cookie banner.';
692
+ } else if (jurisdictions.CH.has(countryCode)) {
693
+ showConsentBanner = true;
694
+ jurisdictionCode = 'CH';
695
+ message = 'Switzerland requires similar data protection measures.';
696
+ } else if (jurisdictions.BR.has(countryCode)) {
697
+ showConsentBanner = true;
698
+ jurisdictionCode = 'BR';
699
+ message = "Brazil's LGPD requires consent for cookies.";
700
+ } else if (jurisdictions.CA.has(countryCode)) {
701
+ showConsentBanner = true;
702
+ jurisdictionCode = 'PIPEDA';
703
+ message = 'PIPEDA requires consent for data collection.';
704
+ } else if (jurisdictions.AU.has(countryCode)) {
705
+ showConsentBanner = true;
706
+ jurisdictionCode = 'AU';
707
+ message = "Australia's Privacy Act mandates transparency about data collection.";
708
+ } else if (jurisdictions.JP.has(countryCode)) {
709
+ showConsentBanner = true;
710
+ jurisdictionCode = 'APPI';
711
+ message = "Japan's APPI requires consent for data collection.";
712
+ } else if (jurisdictions.KR.has(countryCode)) {
713
+ showConsentBanner = true;
714
+ jurisdictionCode = 'PIPA';
715
+ message = "South Korea's PIPA requires consent for data collection.";
716
+ }
717
+ }
718
+ return {
719
+ showConsentBanner,
720
+ jurisdictionCode,
721
+ message
722
+ };
723
+ }
724
+ var hide_metadata = __webpack_require__("./src/utils/hide-metadata.ts");
725
+ function sanitize(input) {
726
+ return input.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
727
+ }
728
+ const html = (errorCode = 'Unknown')=>`<!DOCTYPE html>
729
+ <html lang="en">
730
+ <head>
731
+ <meta charset="UTF-8">
732
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
733
+ <title>Authentication Error</title>
734
+ <style>
735
+ :root {
736
+ --bg-color: #f8f9fa;
737
+ --text-color: #212529;
738
+ --accent-color: #000000;
739
+ --error-color: #dc3545;
740
+ --border-color: #e9ecef;
741
+ }
742
+ body {
743
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
744
+ background-color: var(--bg-color);
745
+ color: var(--text-color);
746
+ display: flex;
747
+ justify-content: center;
748
+ align-items: center;
749
+ height: 100vh;
750
+ margin: 0;
751
+ line-height: 1.5;
752
+ }
753
+ .error-container {
754
+ background-color: #ffffff;
755
+ border-radius: 12px;
756
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
757
+ padding: 2.5rem;
758
+ text-align: center;
759
+ max-width: 90%;
760
+ width: 400px;
761
+ }
762
+ h1 {
763
+ color: var(--error-color);
764
+ font-size: 1.75rem;
765
+ margin-bottom: 1rem;
766
+ font-weight: 600;
767
+ }
768
+ p {
769
+ margin-bottom: 1.5rem;
770
+ color: #495057;
771
+ }
772
+ .btn {
773
+ background-color: var(--accent-color);
774
+ color: #ffffff;
775
+ text-decoration: none;
776
+ padding: 0.75rem 1.5rem;
777
+ border-radius: 6px;
778
+ transition: all 0.3s ease;
779
+ display: inline-block;
780
+ font-weight: 500;
781
+ border: 2px solid var(--accent-color);
782
+ }
783
+ .btn:hover {
784
+ background-color: #131721;
785
+ }
786
+ .error-code {
787
+ font-size: 0.875rem;
788
+ color: #6c757d;
789
+ margin-top: 1.5rem;
790
+ padding-top: 1.5rem;
791
+ border-top: 1px solid var(--border-color);
792
+ }
793
+ .icon {
794
+ font-size: 3rem;
795
+ margin-bottom: 1rem;
796
+ }
797
+ </style>
798
+ </head>
799
+ <body>
800
+ <div class="error-container">
801
+ <div class="icon">⚠️</div>
802
+ <h1>C15T Error</h1>
803
+ <p>We encountered an issue while processing your request. Please try again or contact the application owner if the problem persists.</p>
804
+ <a href="/" id="returnLink" class="btn">Return to Application</a>
805
+ <div class="error-code">Error Code: <span id="errorCode">${sanitize(errorCode)}</span></div>
806
+ </div>
807
+ </body>
808
+ </html>`;
809
+ createAuthEndpoint('/error', {
810
+ method: 'GET',
811
+ metadata: {
812
+ ...hide_metadata.a,
813
+ openapi: {
814
+ description: 'Displays an error page',
815
+ responses: {
816
+ 400: {
817
+ description: 'Error page displayed',
818
+ content: {
819
+ 'text/html': {
820
+ schema: {
821
+ type: 'string'
822
+ }
823
+ }
824
+ }
825
+ }
826
+ }
827
+ }
828
+ }
829
+ }, async (c)=>{
830
+ const query = new URL(c.request?.url || '').searchParams.get('error') || 'Unknown';
831
+ return new Response(html(query), {
832
+ status: 400,
833
+ headers: {
834
+ 'Content-Type': 'text/html'
835
+ }
836
+ });
837
+ });
838
+ const ok = createAuthEndpoint('/ok', {
839
+ method: 'GET',
840
+ metadata: {
841
+ ...hide_metadata.a,
842
+ openapi: {
843
+ description: 'Check if the API is working',
844
+ responses: {
845
+ 200: {
846
+ description: 'Success',
847
+ content: {
848
+ 'application/json': {
849
+ schema: {
850
+ type: 'object',
851
+ properties: {
852
+ ok: {
853
+ type: 'boolean'
854
+ },
855
+ version: {
856
+ type: 'string'
857
+ },
858
+ timestamp: {
859
+ type: 'string'
860
+ }
861
+ }
862
+ }
863
+ }
864
+ }
865
+ }
866
+ }
867
+ }
868
+ }
869
+ }, async (ctx)=>ctx.json({
870
+ ok: true,
871
+ version: process.env.API_VERSION || '1.0.0',
872
+ timestamp: new Date().toISOString()
873
+ }));
874
+ const baseEndpoints = {
875
+ setConsent: setConsent,
876
+ showConsentBanner: show_consent_banner_showConsentBanner,
877
+ status: status_status
878
+ };
879
+ const external_defu_namespaceObject = require("defu");
880
+ var external_defu_default = /*#__PURE__*/ __webpack_require__.n(external_defu_namespaceObject);
881
+ function toEndpoints(endpoints, ctx) {
882
+ const api = {};
883
+ for (const [key, endpoint] of Object.entries(endpoints)){
884
+ api[key] = async (context)=>{
885
+ const C15TContext = await ctx;
886
+ let internalContext = {
887
+ ...context,
888
+ context: {
889
+ ...C15TContext,
890
+ returned: void 0,
891
+ responseHeaders: void 0,
892
+ session: null
893
+ },
894
+ path: endpoint.path,
895
+ headers: context?.headers ? new Headers(context?.headers) : void 0
896
+ };
897
+ const { beforeHooks, afterHooks } = getHooks(C15TContext);
898
+ const before = await runBeforeHooks(internalContext, beforeHooks);
899
+ if ('context' in before && before.context && 'object' == typeof before.context) {
900
+ const { headers, ...rest } = before.context;
901
+ if (headers) headers.forEach((value, key)=>{
902
+ internalContext.headers.set(key, value);
903
+ });
904
+ internalContext = external_defu_default()(rest, internalContext);
905
+ } else if (before) return before;
906
+ internalContext.asResponse = false;
907
+ internalContext.returnHeaders = true;
908
+ const result = await endpoint(internalContext).catch((e)=>{
909
+ if (e instanceof external_better_call_namespaceObject.APIError) return {
910
+ response: e,
911
+ headers: e.headers ? new Headers(e.headers) : null
912
+ };
913
+ throw e;
914
+ });
915
+ internalContext.context.returned = result.response;
916
+ internalContext.context.responseHeaders = result.headers;
917
+ const after = await runAfterHooks(internalContext, afterHooks);
918
+ if (after.response) result.response = after.response;
919
+ if (result.response instanceof external_better_call_namespaceObject.APIError && !context?.asResponse) throw result.response;
920
+ let response;
921
+ response = context?.asResponse ? (0, external_better_call_namespaceObject.toResponse)(result.response, {
922
+ headers: result.headers
923
+ }) : context?.returnHeaders ? {
924
+ headers: result.headers,
925
+ response: result.response
926
+ } : result.response;
927
+ return response;
928
+ };
929
+ api[key].path = endpoint.path;
930
+ api[key].options = endpoint.options;
931
+ }
932
+ return api;
933
+ }
934
+ async function runBeforeHooks(context, hooks) {
935
+ let modifiedContext = {};
936
+ for (const hook of hooks)if (hook.matcher(context)) {
937
+ const result = await hook.handler({
938
+ ...context,
939
+ returnHeaders: false
940
+ });
941
+ if (result && 'object' == typeof result) {
942
+ if ('context' in result && 'object' == typeof result.context) {
943
+ const { headers, ...rest } = result.context;
944
+ if (headers instanceof Headers) {
945
+ if (modifiedContext.headers) headers.forEach((value, key)=>{
946
+ modifiedContext.headers?.set(key, value);
947
+ });
948
+ else modifiedContext.headers = headers;
949
+ }
950
+ modifiedContext = external_defu_default()(rest, modifiedContext);
951
+ continue;
952
+ }
953
+ return result;
954
+ }
955
+ }
956
+ return {
957
+ context: modifiedContext
958
+ };
959
+ }
960
+ async function runAfterHooks(context, hooks) {
961
+ for (const hook of hooks)if (hook.matcher(context)) {
962
+ const result = await hook.handler(context).catch((e)=>{
963
+ if (e instanceof external_better_call_namespaceObject.APIError) return {
964
+ response: e,
965
+ headers: e.headers ? new Headers(e.headers) : null
966
+ };
967
+ throw e;
968
+ });
969
+ if (result.headers) result.headers.forEach((value, key)=>{
970
+ if (context.context.responseHeaders) {
971
+ if ('set-cookie' === key.toLowerCase()) context.context.responseHeaders.append(key, value);
972
+ else context.context.responseHeaders.set(key, value);
973
+ } else {
974
+ context.context.responseHeaders = new Headers();
975
+ context.context.responseHeaders.set(key, value);
976
+ }
977
+ });
978
+ if (result.response) context.context.returned = result.response;
979
+ }
980
+ return {
981
+ response: context.context.returned,
982
+ headers: context.context.responseHeaders
983
+ };
984
+ }
985
+ function getHooks(C15TContext) {
986
+ const plugins = C15TContext.options.plugins || [];
987
+ const beforeHooks = [];
988
+ const afterHooks = [];
989
+ if (C15TContext.options.hooks?.before) beforeHooks.push({
990
+ matcher: ()=>true,
991
+ handler: C15TContext.options.hooks.before
992
+ });
993
+ if (C15TContext.options.hooks?.after) afterHooks.push({
994
+ matcher: ()=>true,
995
+ handler: C15TContext.options.hooks.after
996
+ });
997
+ const pluginBeforeHooks = plugins.map((plugin)=>{
998
+ if (plugin.hooks?.before) return plugin.hooks.before;
999
+ }).filter((plugin)=>void 0 !== plugin).flat();
1000
+ const pluginAfterHooks = plugins.map((plugin)=>{
1001
+ if (plugin.hooks?.after) return plugin.hooks.after;
1002
+ }).filter((plugin)=>void 0 !== plugin).flat();
1003
+ pluginBeforeHooks.length && beforeHooks.push(...pluginBeforeHooks);
1004
+ pluginAfterHooks.length && afterHooks.push(...pluginAfterHooks);
1005
+ return {
1006
+ beforeHooks,
1007
+ afterHooks
1008
+ };
1009
+ }
1010
+ function getEndpoints(ctx, options) {
1011
+ const pluginEndpoints = options.plugins?.reduce((acc, plugin)=>{
1012
+ if (plugin.endpoints) Object.assign(acc, plugin.endpoints);
1013
+ return acc;
1014
+ }, {});
1015
+ const middlewares = options.plugins?.map((plugin)=>plugin.middlewares?.map((m)=>{
1016
+ const middleware = async (context)=>m.middleware({
1017
+ ...context,
1018
+ context: {
1019
+ ...ctx,
1020
+ ...context.context
1021
+ }
1022
+ });
1023
+ middleware.options = m.middleware.options;
1024
+ return {
1025
+ path: m.path,
1026
+ middleware
1027
+ };
1028
+ })).filter((plugin)=>void 0 !== plugin).flat() || [];
1029
+ const endpoints = {
1030
+ ...baseEndpoints,
1031
+ ...pluginEndpoints,
1032
+ ok: ok
1033
+ };
1034
+ const api = toEndpoints(endpoints, ctx);
1035
+ return {
1036
+ api: api,
1037
+ middlewares
1038
+ };
1039
+ }
1040
+ const router = (ctx, options)=>{
1041
+ const { api, middlewares } = getEndpoints(ctx, options);
1042
+ let basePath = '';
1043
+ try {
1044
+ if (ctx.baseURL) {
1045
+ const url = new URL(ctx.baseURL);
1046
+ basePath = url.pathname;
1047
+ }
1048
+ } catch {
1049
+ basePath = '/api/c15t';
1050
+ }
1051
+ if (!basePath || '/' === basePath) basePath = '/api/c15t';
1052
+ const routerInstance = (0, external_better_call_namespaceObject.createRouter)(api, {
1053
+ routerContext: ctx,
1054
+ openapi: {
1055
+ disabled: false
1056
+ },
1057
+ basePath,
1058
+ routerMiddleware: [
1059
+ {
1060
+ path: '/**',
1061
+ middleware: validateContextMiddleware
1062
+ },
1063
+ {
1064
+ path: '/**',
1065
+ middleware: originCheckMiddleware
1066
+ },
1067
+ ...middlewares
1068
+ ],
1069
+ async onRequest (req) {
1070
+ ctx.ipAddress = getIp(req, options);
1071
+ ctx.userAgent = req.headers.get('user-agent');
1072
+ for (const plugin of ctx.options.plugins || [])if (plugin.onRequest) {
1073
+ const response = await plugin.onRequest(req, ctx);
1074
+ if (response && 'response' in response) return response.response;
1075
+ }
1076
+ return req;
1077
+ },
1078
+ async onResponse (res) {
1079
+ for (const plugin of ctx.options.plugins || [])if (plugin.onResponse) {
1080
+ const response = await plugin.onResponse(res, ctx);
1081
+ if (response) return response.response;
1082
+ }
1083
+ return res;
1084
+ },
1085
+ onError (e) {
1086
+ if (e instanceof external_better_call_namespaceObject.APIError && 'FOUND' === e.status) return;
1087
+ if (options.onAPIError?.throw) throw e;
1088
+ if (options.onAPIError?.onError) {
1089
+ options.onAPIError.onError(e, ctx);
1090
+ return;
1091
+ }
1092
+ const optLogLevel = options.logger?.level;
1093
+ const log = 'error' === optLogLevel || 'warn' === optLogLevel || 'debug' === optLogLevel ? utils_logger.kg : void 0;
1094
+ if (options.logger?.disabled !== true) {
1095
+ if (e && 'object' == typeof e && 'message' in e && 'string' == typeof e.message && (e.message.includes('no column') || e.message.includes('column') || e.message.includes('relation') || e.message.includes('table') || e.message.includes('does not exist'))) {
1096
+ ctx.logger?.error(e.message);
1097
+ return;
1098
+ }
1099
+ if (e instanceof external_better_call_namespaceObject.APIError) {
1100
+ if ('INTERNAL_SERVER_ERROR' === e.status) ctx.logger.error(e.status, e);
1101
+ log?.error(e.message);
1102
+ } else ctx.logger?.error(e && 'object' == typeof e && 'name' in e ? e.name : '', e);
1103
+ }
1104
+ }
1105
+ });
1106
+ return routerInstance;
1107
+ };
1108
+ async function processHooks(data, model, operation, phase, hooks, context) {
1109
+ let currentData = {
1110
+ ...data
1111
+ };
1112
+ for (const hookSet of hooks){
1113
+ const modelHooks = hookSet[model];
1114
+ if (!modelHooks) continue;
1115
+ const operationHooks = modelHooks[operation];
1116
+ if (!operationHooks) continue;
1117
+ const hookFn = operationHooks[phase];
1118
+ if (!!hookFn) {
1119
+ if ('before' === phase) {
1120
+ const result = await hookFn(currentData, context);
1121
+ if (result && 'object' == typeof result && 'kind' in result) switch(result.kind){
1122
+ case 'abort':
1123
+ return null;
1124
+ case 'transform':
1125
+ {
1126
+ const transformData = result.data;
1127
+ currentData = {
1128
+ ...currentData,
1129
+ ...transformData
1130
+ };
1131
+ break;
1132
+ }
1133
+ default:
1134
+ break;
1135
+ }
1136
+ } else await hookFn(currentData, context);
1137
+ }
1138
+ }
1139
+ return currentData;
1140
+ }
1141
+ async function processAfterHooksForMany(records, model, hooks, context) {
1142
+ if (!records.length) return;
1143
+ for (const record of records)await processHooks(record, model, 'update', 'after', hooks, context);
1144
+ }
1145
+ async function createWithHook(adapter, ctx, props) {
1146
+ const { data, model, customFn, context } = props;
1147
+ const hooks = ctx.hooks || [];
1148
+ const transformedData = await processHooks(data, model, 'create', 'before', hooks, context);
1149
+ if (null === transformedData) return null;
1150
+ let created = null;
1151
+ if (customFn) {
1152
+ created = await customFn.fn(transformedData);
1153
+ if (!customFn.executeMainFn && created) return created;
1154
+ }
1155
+ if (!created) created = await adapter.create({
1156
+ model: model,
1157
+ data: transformedData
1158
+ });
1159
+ if (created) await processHooks(created, model, 'create', 'after', hooks, context);
1160
+ return created;
1161
+ }
1162
+ async function update_hooks_updateWithHooks(adapter, ctx, props) {
1163
+ const { data, where, model, customFn, context } = props;
1164
+ const hooks = ctx.hooks || [];
1165
+ const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
1166
+ if (null === transformedData) return null;
1167
+ let updated = null;
1168
+ if (customFn) {
1169
+ const result = await customFn.fn(transformedData);
1170
+ updated = result;
1171
+ if (!customFn.executeMainFn && updated) return updated;
1172
+ }
1173
+ if (!updated) updated = await adapter.update({
1174
+ model: model,
1175
+ update: transformedData,
1176
+ where
1177
+ });
1178
+ if (updated) await processHooks(updated, model, 'update', 'after', hooks, context);
1179
+ return updated;
1180
+ }
1181
+ async function executeCustomFunction(data, customFn) {
1182
+ if (!customFn) return {
1183
+ result: null,
1184
+ shouldContinue: true
1185
+ };
1186
+ const result = await customFn.fn(data);
1187
+ const shouldContinue = !result || !!customFn.executeMainFn;
1188
+ return {
1189
+ result,
1190
+ shouldContinue
1191
+ };
1192
+ }
1193
+ function processUpdateManyResult(result) {
1194
+ if (Array.isArray(result)) return result;
1195
+ if ('number' == typeof result && result > 0) return [];
1196
+ return null;
1197
+ }
1198
+ async function updateManyWithHooks(adapter, ctx, props) {
1199
+ const { data, where, model, customFn, context } = props;
1200
+ const hooks = ctx.hooks || [];
1201
+ const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
1202
+ if (null === transformedData) return null;
1203
+ const { result: customResult, shouldContinue } = await executeCustomFunction(transformedData, customFn);
1204
+ if (customResult && !shouldContinue) return customResult;
1205
+ let updated = customResult;
1206
+ if (!updated) {
1207
+ const adapterResult = await adapter.updateMany({
1208
+ model: model,
1209
+ update: transformedData,
1210
+ where
1211
+ });
1212
+ updated = processUpdateManyResult(adapterResult);
1213
+ }
1214
+ if (updated && updated.length > 0) await processAfterHooksForMany(updated, model, hooks, context);
1215
+ return updated;
1216
+ }
1217
+ function getWithHooks(adapter, ctx) {
1218
+ return {
1219
+ createWithHooks: ({ data, model, customFn, context })=>createWithHook(adapter, ctx, {
1220
+ data,
1221
+ model,
1222
+ customFn,
1223
+ context
1224
+ }),
1225
+ updateWithHooks: (props)=>update_hooks_updateWithHooks(adapter, ctx, props),
1226
+ updateManyWithHooks: (props)=>updateManyWithHooks(adapter, ctx, props)
1227
+ };
1228
+ }
1229
+ const definition_getConsentTables = (options)=>{
1230
+ const pluginSchema = options.plugins?.reduce((acc, plugin)=>{
1231
+ const schema = plugin.schema;
1232
+ if (!schema) return acc;
1233
+ for (const [key, value] of Object.entries(schema))acc[key] = {
1234
+ fields: {
1235
+ ...acc[key]?.fields,
1236
+ ...value.fields
1237
+ },
1238
+ entityName: value.entityName || key
1239
+ };
1240
+ return acc;
1241
+ }, {});
1242
+ const { subject, consentPurpose, consentPolicy, domain, geoLocation, consent, consentPurposeJunction, record, consentGeoLocation, consentWithdrawal, auditLog, ...pluginTables } = pluginSchema || {};
1243
+ return {
1244
+ subject: getSubjectTable(options, subject?.fields),
1245
+ consentPurpose: getPurposeTable(options, consentPurpose?.fields),
1246
+ consentPolicy: getConsentPolicyTable(options, consentPolicy?.fields),
1247
+ domain: getDomainTable(options, domain?.fields),
1248
+ consent: getConsentTable(options, consent?.fields),
1249
+ consentPurposeJunction: getPurposeJunctionTable(options, consentPurposeJunction?.fields),
1250
+ consentRecord: getConsentRecordTable(options, record?.fields),
1251
+ consentGeoLocation: getConsentGeoLocationTable(options, consentGeoLocation?.fields),
1252
+ consentWithdrawal: getConsentWithdrawalTable(options, consentWithdrawal?.fields),
1253
+ auditLog: getAuditLogTable(options, auditLog?.fields),
1254
+ geoLocation: getGeoLocationTable(options, geoLocation?.fields),
1255
+ ...pluginTables
1256
+ };
1257
+ };
1258
+ function validateEntityOutput(tableName, data, options) {
1259
+ const tables = definition_getConsentTables(options);
1260
+ const table = tables[tableName];
1261
+ if (!table) throw new Error(`Table ${tableName} not found`);
1262
+ return table.schema.parse(data);
1263
+ }
1264
+ function auditLogRegistry({ adapter, ...ctx }) {
1265
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1266
+ return {
1267
+ createAuditLog: async (auditLog, context)=>{
1268
+ const createdLog = await createWithHooks({
1269
+ data: {
1270
+ createdAt: new Date(),
1271
+ ...auditLog
1272
+ },
1273
+ model: 'auditLog',
1274
+ customFn: void 0,
1275
+ context
1276
+ });
1277
+ if (!createdLog) throw new Error('Failed to create consent audit log - operation returned null');
1278
+ return createdLog;
1279
+ },
1280
+ findAuditLogs: async (entityType, entityId, actionType, limit, offset)=>{
1281
+ const whereConditions = [];
1282
+ if (entityType) whereConditions.push({
1283
+ field: 'entityType',
1284
+ value: entityType
1285
+ });
1286
+ if (entityId) whereConditions.push({
1287
+ field: 'entityId',
1288
+ value: entityId
1289
+ });
1290
+ if (actionType) whereConditions.push({
1291
+ field: 'actionType',
1292
+ value: actionType
1293
+ });
1294
+ const logs = await adapter.findMany({
1295
+ model: 'auditLog',
1296
+ where: whereConditions,
1297
+ sortBy: {
1298
+ field: 'createdAt',
1299
+ direction: 'desc'
1300
+ },
1301
+ limit,
1302
+ offset
1303
+ });
1304
+ return logs.map((log)=>validateEntityOutput('auditLog', log, ctx.options));
1305
+ },
1306
+ findAuditLogById: async (auditLogId)=>{
1307
+ const log = await adapter.findOne({
1308
+ model: 'auditLog',
1309
+ where: [
1310
+ {
1311
+ field: 'id',
1312
+ value: auditLogId
1313
+ }
1314
+ ]
1315
+ });
1316
+ return log ? validateEntityOutput('auditLog', log, ctx.options) : null;
1317
+ },
1318
+ findAuditLogsByEntity: async (entityType, entityId, limit)=>{
1319
+ const logs = await adapter.findMany({
1320
+ model: 'auditLog',
1321
+ where: [
1322
+ {
1323
+ field: 'entityType',
1324
+ value: entityType
1325
+ },
1326
+ {
1327
+ field: 'entityId',
1328
+ value: entityId
1329
+ }
1330
+ ],
1331
+ sortBy: {
1332
+ field: 'createdAt',
1333
+ direction: 'desc'
1334
+ },
1335
+ limit
1336
+ });
1337
+ return logs.map((log)=>validateEntityOutput('auditLog', log, ctx.options));
1338
+ },
1339
+ countAuditLogs: async (entityType, entityId, actionType)=>{
1340
+ const whereConditions = [];
1341
+ if (entityType) whereConditions.push({
1342
+ field: 'entityType',
1343
+ value: entityType
1344
+ });
1345
+ if (entityId) whereConditions.push({
1346
+ field: 'entityId',
1347
+ value: entityId
1348
+ });
1349
+ if (actionType) whereConditions.push({
1350
+ field: 'actionType',
1351
+ value: actionType
1352
+ });
1353
+ return adapter.count({
1354
+ model: 'auditLog',
1355
+ where: whereConditions
1356
+ });
1357
+ }
1358
+ };
1359
+ }
1360
+ const auditLogSchema = external_zod_namespaceObject.z.object({
1361
+ id: external_zod_namespaceObject.z.string(),
1362
+ entityType: external_zod_namespaceObject.z.string(),
1363
+ entityId: external_zod_namespaceObject.z.string(),
1364
+ actionType: external_zod_namespaceObject.z.string(),
1365
+ subjectId: external_zod_namespaceObject.z.string().optional(),
1366
+ ipAddress: external_zod_namespaceObject.z.string().optional(),
1367
+ userAgent: external_zod_namespaceObject.z.string().optional(),
1368
+ changes: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
1369
+ metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
1370
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1371
+ });
1372
+ var external_superjson_ = __webpack_require__("superjson");
1373
+ var external_superjson_default = /*#__PURE__*/ __webpack_require__.n(external_superjson_);
1374
+ const fieldConfigSchema = external_zod_namespaceObject.z.object({
1375
+ required: external_zod_namespaceObject.z.boolean().default(true),
1376
+ returned: external_zod_namespaceObject.z.boolean().default(true),
1377
+ input: external_zod_namespaceObject.z.boolean().default(true),
1378
+ defaultValue: external_zod_namespaceObject.z.union([
1379
+ external_zod_namespaceObject.z.any(),
1380
+ external_zod_namespaceObject.z["function"]().returns(external_zod_namespaceObject.z.any())
1381
+ ]).optional(),
1382
+ transform: external_zod_namespaceObject.z.object({
1383
+ input: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
1384
+ external_zod_namespaceObject.z.any(),
1385
+ external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
1386
+ ])).optional(),
1387
+ output: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
1388
+ external_zod_namespaceObject.z.any(),
1389
+ external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
1390
+ ])).optional()
1391
+ }).optional(),
1392
+ validator: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
1393
+ external_zod_namespaceObject.z.string(),
1394
+ external_zod_namespaceObject.z["null"]()
1395
+ ])).optional(),
1396
+ unique: external_zod_namespaceObject.z.boolean().optional(),
1397
+ indexed: external_zod_namespaceObject.z.boolean().optional(),
1398
+ sortable: external_zod_namespaceObject.z.boolean().default(true),
1399
+ fieldName: external_zod_namespaceObject.z.string().optional(),
1400
+ bigint: external_zod_namespaceObject.z.boolean().default(false)
1401
+ });
1402
+ const stringFieldSchema = fieldConfigSchema.extend({
1403
+ type: external_zod_namespaceObject.z.literal('string'),
1404
+ minLength: external_zod_namespaceObject.z.number().optional(),
1405
+ maxLength: external_zod_namespaceObject.z.number().optional(),
1406
+ pattern: external_zod_namespaceObject.z.string().optional()
1407
+ });
1408
+ const numberFieldSchema = fieldConfigSchema.extend({
1409
+ type: external_zod_namespaceObject.z.literal('number'),
1410
+ min: external_zod_namespaceObject.z.number().optional(),
1411
+ max: external_zod_namespaceObject.z.number().optional()
1412
+ });
1413
+ const booleanFieldSchema = fieldConfigSchema.extend({
1414
+ type: external_zod_namespaceObject.z.literal('boolean')
1415
+ });
1416
+ const dateFieldSchema = fieldConfigSchema.extend({
1417
+ type: external_zod_namespaceObject.z.literal('date'),
1418
+ minDate: external_zod_namespaceObject.z.date().optional(),
1419
+ maxDate: external_zod_namespaceObject.z.date().optional(),
1420
+ dateOnly: external_zod_namespaceObject.z.boolean().default(false),
1421
+ format: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional()
1422
+ });
1423
+ const timezoneFieldSchema = fieldConfigSchema.extend({
1424
+ type: external_zod_namespaceObject.z.literal('timezone'),
1425
+ validateTimezone: external_zod_namespaceObject.z.boolean().default(true),
1426
+ suggestedValues: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional(),
1427
+ restrictToSuggestedValues: external_zod_namespaceObject.z.boolean().default(false)
1428
+ });
1429
+ const jsonFieldSchema = fieldConfigSchema.extend({
1430
+ type: external_zod_namespaceObject.z.literal('json'),
1431
+ validateJson: external_zod_namespaceObject.z.boolean().default(true)
1432
+ });
1433
+ const stringArrayFieldSchema = fieldConfigSchema.extend({
1434
+ type: external_zod_namespaceObject.z.literal('string[]')
1435
+ });
1436
+ const numberArrayFieldSchema = fieldConfigSchema.extend({
1437
+ type: external_zod_namespaceObject.z.literal('number[]')
1438
+ });
1439
+ external_zod_namespaceObject.z.discriminatedUnion('type', [
1440
+ stringFieldSchema,
1441
+ numberFieldSchema,
1442
+ booleanFieldSchema,
1443
+ dateFieldSchema,
1444
+ timezoneFieldSchema,
1445
+ jsonFieldSchema,
1446
+ stringArrayFieldSchema,
1447
+ numberArrayFieldSchema
1448
+ ]);
1449
+ const COMMON_TIMEZONES = {
1450
+ UTC: 'UTC',
1451
+ GMT: 'GMT',
1452
+ EASTERN: 'America/New_York',
1453
+ CENTRAL: 'America/Chicago',
1454
+ MOUNTAIN: 'America/Denver',
1455
+ PACIFIC: 'America/Los_Angeles',
1456
+ LONDON: 'Europe/London',
1457
+ PARIS: 'Europe/Paris',
1458
+ BERLIN: 'Europe/Berlin',
1459
+ TOKYO: 'Asia/Tokyo',
1460
+ SHANGHAI: 'Asia/Shanghai',
1461
+ SINGAPORE: 'Asia/Singapore',
1462
+ SYDNEY: 'Australia/Sydney',
1463
+ SAO_PAULO: 'America/Sao_Paulo'
1464
+ };
1465
+ const external_base_x_namespaceObject = require("base-x");
1466
+ var external_base_x_default = /*#__PURE__*/ __webpack_require__.n(external_base_x_namespaceObject);
1467
+ const b58 = external_base_x_default()('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
1468
+ function generateId(prefix) {
1469
+ const buf = crypto.getRandomValues(new Uint8Array(20));
1470
+ const EPOCH_TIMESTAMP = 1700000000000;
1471
+ const t = Date.now() - EPOCH_TIMESTAMP;
1472
+ const high = Math.floor(t / 0x100000000);
1473
+ const low = t >>> 0;
1474
+ buf[0] = high >>> 24 & 255;
1475
+ buf[1] = high >>> 16 & 255;
1476
+ buf[2] = high >>> 8 & 255;
1477
+ buf[3] = 255 & high;
1478
+ buf[4] = low >>> 24 & 255;
1479
+ buf[5] = low >>> 16 & 255;
1480
+ buf[6] = low >>> 8 & 255;
1481
+ buf[7] = 255 & low;
1482
+ return `${prefix}_${b58.encode(buf)}`;
1483
+ }
1484
+ function getAuditLogTable(options, auditLogFields) {
1485
+ const auditLogConfig = options.tables?.auditLog;
1486
+ const subjectConfig = options.tables?.subject;
1487
+ return {
1488
+ entityName: auditLogConfig?.entityName || 'auditLog',
1489
+ entityPrefix: auditLogConfig?.entityPrefix || 'log',
1490
+ schema: auditLogSchema,
1491
+ fields: {
1492
+ entityType: {
1493
+ type: 'string',
1494
+ required: true,
1495
+ fieldName: auditLogConfig?.fields?.entityType || 'entityType'
1496
+ },
1497
+ entityId: {
1498
+ type: 'string',
1499
+ required: true,
1500
+ fieldName: auditLogConfig?.fields?.entityId || 'entityId'
1501
+ },
1502
+ actionType: {
1503
+ type: 'string',
1504
+ required: true,
1505
+ fieldName: auditLogConfig?.fields?.actionType || 'actionType'
1506
+ },
1507
+ subjectId: {
1508
+ type: 'string',
1509
+ required: false,
1510
+ fieldName: auditLogConfig?.fields?.subjectId || 'subjectId',
1511
+ references: {
1512
+ model: subjectConfig?.entityName || 'subject',
1513
+ field: 'id'
1514
+ }
1515
+ },
1516
+ ipAddress: {
1517
+ type: 'string',
1518
+ required: false,
1519
+ fieldName: auditLogConfig?.fields?.ipAddress || 'ipAddress'
1520
+ },
1521
+ userAgent: {
1522
+ type: 'string',
1523
+ required: false,
1524
+ fieldName: auditLogConfig?.fields?.userAgent || 'userAgent'
1525
+ },
1526
+ changes: {
1527
+ type: 'json',
1528
+ required: false,
1529
+ fieldName: auditLogConfig?.fields?.changes || 'changes'
1530
+ },
1531
+ metadata: {
1532
+ type: 'json',
1533
+ required: false,
1534
+ fieldName: auditLogConfig?.fields?.metadata || 'metadata'
1535
+ },
1536
+ createdAt: {
1537
+ type: 'date',
1538
+ defaultValue: ()=>new Date(),
1539
+ required: true,
1540
+ fieldName: auditLogConfig?.fields?.createdAt || 'createdAt'
1541
+ },
1542
+ eventTimezone: {
1543
+ type: 'timezone',
1544
+ required: true,
1545
+ defaultValue: COMMON_TIMEZONES.UTC,
1546
+ fieldName: auditLogConfig?.fields?.eventTimezone || 'eventTimezone'
1547
+ },
1548
+ ...auditLogFields || {},
1549
+ ...auditLogConfig?.additionalFields || {}
1550
+ },
1551
+ indexes: [
1552
+ {
1553
+ name: 'entity_index',
1554
+ fields: [
1555
+ 'entityType',
1556
+ 'entityId'
1557
+ ]
1558
+ },
1559
+ {
1560
+ name: 'action_type_index',
1561
+ fields: [
1562
+ 'actionType'
1563
+ ]
1564
+ },
1565
+ {
1566
+ name: 'subject_id_index',
1567
+ fields: [
1568
+ 'subjectId'
1569
+ ]
1570
+ },
1571
+ {
1572
+ name: 'created_at_index',
1573
+ fields: [
1574
+ 'createdAt'
1575
+ ]
1576
+ }
1577
+ ],
1578
+ order: 5
1579
+ };
1580
+ }
1581
+ function consentGeoLocationRegistry({ adapter, ...ctx }) {
1582
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1583
+ return {
1584
+ createConsentGeoLocation: async (geoLocation, context)=>{
1585
+ const createdGeoLocation = await createWithHooks({
1586
+ data: {
1587
+ createdAt: new Date(),
1588
+ ...geoLocation
1589
+ },
1590
+ model: 'consentGeoLocation',
1591
+ customFn: void 0,
1592
+ context
1593
+ });
1594
+ if (!createdGeoLocation) throw new Error('Failed to create consent geo-location - operation returned null');
1595
+ return createdGeoLocation;
1596
+ },
1597
+ findConsentGeoLocationsByConsentId: async (consentId)=>{
1598
+ const geoLocations = await adapter.findMany({
1599
+ model: 'consentGeoLocation',
1600
+ where: [
1601
+ {
1602
+ field: 'consentId',
1603
+ value: consentId
1604
+ }
1605
+ ],
1606
+ sortBy: {
1607
+ field: 'createdAt',
1608
+ direction: 'desc'
1609
+ }
1610
+ });
1611
+ return geoLocations.map((geoLocation)=>validateEntityOutput('consentGeoLocation', geoLocation, ctx.options));
1612
+ },
1613
+ findConsentGeoLocationById: async (geoLocationId)=>{
1614
+ const geoLocation = await adapter.findOne({
1615
+ model: 'consentGeoLocation',
1616
+ where: [
1617
+ {
1618
+ field: 'id',
1619
+ value: geoLocationId
1620
+ }
1621
+ ]
1622
+ });
1623
+ return geoLocation ? validateEntityOutput('consentGeoLocation', geoLocation, ctx.options) : null;
1624
+ }
1625
+ };
1626
+ }
1627
+ const consentGeoLocationSchema = external_zod_namespaceObject.z.object({
1628
+ id: external_zod_namespaceObject.z.string(),
1629
+ consentId: external_zod_namespaceObject.z.string(),
1630
+ ip: external_zod_namespaceObject.z.string().ip(),
1631
+ country: external_zod_namespaceObject.z.string().optional(),
1632
+ region: external_zod_namespaceObject.z.string().optional(),
1633
+ city: external_zod_namespaceObject.z.string().optional(),
1634
+ latitude: external_zod_namespaceObject.z.number().min(-90).max(90).optional(),
1635
+ longitude: external_zod_namespaceObject.z.number().min(-180).max(180).optional(),
1636
+ timezone: external_zod_namespaceObject.z.string().regex(/^[A-Za-z_]+\/[A-Za-z_]+$/).optional(),
1637
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1638
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1639
+ });
1640
+ function getConsentGeoLocationTable(options, geoLocationFields) {
1641
+ const consentGeoLocationConfig = options.tables?.consentGeoLocation;
1642
+ const consentConfig = options.tables?.consent;
1643
+ return {
1644
+ entityName: consentGeoLocationConfig?.entityName || 'consentGeoLocation',
1645
+ entityPrefix: consentGeoLocationConfig?.entityPrefix || 'cgl',
1646
+ schema: consentGeoLocationSchema,
1647
+ fields: {
1648
+ consentId: {
1649
+ type: 'string',
1650
+ required: true,
1651
+ fieldName: consentGeoLocationConfig?.fields?.consentId || 'consentId',
1652
+ references: {
1653
+ model: consentConfig?.entityName || 'consent',
1654
+ field: 'id'
1655
+ }
1656
+ },
1657
+ ip: {
1658
+ type: 'string',
1659
+ required: true,
1660
+ fieldName: consentGeoLocationConfig?.fields?.ip || 'ip'
1661
+ },
1662
+ country: {
1663
+ type: 'string',
1664
+ required: false,
1665
+ fieldName: consentGeoLocationConfig?.fields?.country || 'country'
1666
+ },
1667
+ region: {
1668
+ type: 'string',
1669
+ required: false,
1670
+ fieldName: consentGeoLocationConfig?.fields?.region || 'region'
1671
+ },
1672
+ city: {
1673
+ type: 'string',
1674
+ required: false,
1675
+ fieldName: consentGeoLocationConfig?.fields?.city || 'city'
1676
+ },
1677
+ latitude: {
1678
+ type: 'number',
1679
+ required: false,
1680
+ fieldName: consentGeoLocationConfig?.fields?.latitude || 'latitude'
1681
+ },
1682
+ longitude: {
1683
+ type: 'number',
1684
+ required: false,
1685
+ fieldName: consentGeoLocationConfig?.fields?.longitude || 'longitude'
1686
+ },
1687
+ timezone: {
1688
+ type: 'string',
1689
+ required: false,
1690
+ fieldName: consentGeoLocationConfig?.fields?.timezone || 'timezone'
1691
+ },
1692
+ createdAt: {
1693
+ type: 'date',
1694
+ defaultValue: ()=>new Date(),
1695
+ required: true,
1696
+ fieldName: consentGeoLocationConfig?.fields?.createdAt || 'createdAt'
1697
+ },
1698
+ ...geoLocationFields || {},
1699
+ ...consentGeoLocationConfig?.additionalFields || {}
1700
+ },
1701
+ indexes: [
1702
+ {
1703
+ name: 'consent_id_index',
1704
+ fields: [
1705
+ 'consentId'
1706
+ ]
1707
+ },
1708
+ {
1709
+ name: 'country_index',
1710
+ fields: [
1711
+ 'country'
1712
+ ]
1713
+ },
1714
+ {
1715
+ name: 'created_at_index',
1716
+ fields: [
1717
+ 'createdAt'
1718
+ ]
1719
+ }
1720
+ ],
1721
+ order: 4
1722
+ };
1723
+ }
1724
+ const external_node_crypto_namespaceObject = require("node:crypto");
1725
+ function generatePolicyPlaceholder(name, date) {
1726
+ const content = `[PLACEHOLDER] This is an automatically generated version of the ${name} policy.\n\nThis placeholder content should be replaced with actual policy terms before being presented to users.\n\nGenerated on: ${date.toISOString()}`;
1727
+ const contentHash = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(content).digest('hex');
1728
+ return {
1729
+ content,
1730
+ contentHash
1731
+ };
1732
+ }
1733
+ function policyRegistry({ adapter, ...ctx }) {
1734
+ const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
1735
+ const registry = {
1736
+ createConsentPolicy: async (policy, context)=>{
1737
+ const createdPolicy = await createWithHooks({
1738
+ data: {
1739
+ createdAt: new Date(),
1740
+ ...policy
1741
+ },
1742
+ model: 'consentPolicy',
1743
+ context
1744
+ });
1745
+ if (!createdPolicy) throw new Error('Failed to create consent policy - operation returned null');
1746
+ return createdPolicy;
1747
+ },
1748
+ findPolicies: async (params = {})=>{
1749
+ const whereConditions = [];
1750
+ if (!params.includeInactive) whereConditions.push({
1751
+ field: 'isActive',
1752
+ value: true
1753
+ });
1754
+ if (params.domainId) whereConditions.push({
1755
+ field: 'id',
1756
+ value: params.domainId
1757
+ });
1758
+ if (params.version) whereConditions.push({
1759
+ field: 'version',
1760
+ value: params.version
1761
+ });
1762
+ const policies = await adapter.findMany({
1763
+ model: 'consentPolicy',
1764
+ where: whereConditions,
1765
+ sortBy: {
1766
+ field: 'effectiveDate',
1767
+ direction: 'desc'
1768
+ }
1769
+ });
1770
+ return policies.map((policy)=>validateEntityOutput('consentPolicy', policy, ctx.options));
1771
+ },
1772
+ findPolicy: async (domainId, version)=>{
1773
+ const policies = await registry.findPolicies({
1774
+ domainId,
1775
+ version
1776
+ });
1777
+ return policies[0] || null;
1778
+ },
1779
+ findActiveConsentPolicies: async ()=>{
1780
+ const policies = await adapter.findMany({
1781
+ model: 'consentPolicy',
1782
+ where: [
1783
+ {
1784
+ field: 'isActive',
1785
+ value: true
1786
+ }
1787
+ ],
1788
+ sortBy: {
1789
+ field: 'effectiveDate',
1790
+ direction: 'desc'
1791
+ }
1792
+ });
1793
+ return policies.map((policy)=>validateEntityOutput('consentPolicy', policy, ctx.options));
1794
+ },
1795
+ findConsentPolicyById: async (policyId)=>{
1796
+ const policy = await adapter.findOne({
1797
+ model: 'consentPolicy',
1798
+ where: [
1799
+ {
1800
+ field: 'id',
1801
+ value: policyId
1802
+ }
1803
+ ]
1804
+ });
1805
+ return policy ? validateEntityOutput('consentPolicy', policy, ctx.options) : null;
1806
+ },
1807
+ findConsentPolicyByVersion: async (version)=>{
1808
+ const policy = await adapter.findOne({
1809
+ model: 'consentPolicy',
1810
+ where: [
1811
+ {
1812
+ field: 'version',
1813
+ value: version
1814
+ }
1815
+ ]
1816
+ });
1817
+ return policy ? validateEntityOutput('consentPolicy', policy, ctx.options) : null;
1818
+ },
1819
+ updateConsentPolicy: async (policyId, data, context)=>{
1820
+ const policy = await updateWithHooks({
1821
+ data,
1822
+ where: [
1823
+ {
1824
+ field: 'id',
1825
+ value: policyId
1826
+ }
1827
+ ],
1828
+ model: 'consentPolicy',
1829
+ customFn: void 0,
1830
+ context
1831
+ });
1832
+ return policy ? validateEntityOutput('consentPolicy', policy, ctx.options) : null;
1833
+ },
1834
+ findOrCreatePolicy: async (name)=>{
1835
+ const normalizedSearchName = name.toLowerCase().trim();
1836
+ return adapter.transaction({
1837
+ callback: async (txAdapter)=>{
1838
+ const now = new Date();
1839
+ const txRegistry = policyRegistry({
1840
+ adapter: txAdapter,
1841
+ ...ctx
1842
+ });
1843
+ const matchingPolicies = await txAdapter.findMany({
1844
+ model: 'consentPolicy',
1845
+ where: [
1846
+ {
1847
+ field: 'isActive',
1848
+ value: true
1849
+ },
1850
+ {
1851
+ field: 'name',
1852
+ value: normalizedSearchName,
1853
+ operator: 'ilike'
1854
+ }
1855
+ ],
1856
+ sortBy: {
1857
+ field: 'effectiveDate',
1858
+ direction: 'desc'
1859
+ },
1860
+ limit: 1
1861
+ });
1862
+ const latestPolicy = matchingPolicies[0] ? validateEntityOutput('consentPolicy', matchingPolicies[0], ctx.options) : null;
1863
+ if (latestPolicy) return latestPolicy;
1864
+ const { content: defaultContent, contentHash } = generatePolicyPlaceholder(name, now);
1865
+ return txRegistry.createConsentPolicy({
1866
+ version: '1.0.0',
1867
+ name: normalizedSearchName,
1868
+ effectiveDate: now,
1869
+ content: defaultContent,
1870
+ contentHash,
1871
+ isActive: true,
1872
+ updatedAt: now,
1873
+ expirationDate: null
1874
+ });
1875
+ }
1876
+ });
1877
+ }
1878
+ };
1879
+ return registry;
1880
+ }
1881
+ const consentPolicySchema = external_zod_namespaceObject.z.object({
1882
+ id: external_zod_namespaceObject.z.string(),
1883
+ version: external_zod_namespaceObject.z.string(),
1884
+ name: external_zod_namespaceObject.z.string(),
1885
+ effectiveDate: external_zod_namespaceObject.z.date(),
1886
+ expirationDate: external_zod_namespaceObject.z.date().nullable().optional(),
1887
+ content: external_zod_namespaceObject.z.string(),
1888
+ contentHash: external_zod_namespaceObject.z.string(),
1889
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
1890
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1891
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1892
+ });
1893
+ function getConsentPolicyTable(options, policyFields) {
1894
+ const consentPolicyConfig = options.tables?.consentPolicy;
1895
+ return {
1896
+ entityName: consentPolicyConfig?.entityName || 'consentPolicy',
1897
+ entityPrefix: consentPolicyConfig?.entityPrefix || 'pol',
1898
+ schema: consentPolicySchema,
1899
+ fields: {
1900
+ version: {
1901
+ type: 'string',
1902
+ required: true,
1903
+ fieldName: consentPolicyConfig?.fields?.version || 'version'
1904
+ },
1905
+ name: {
1906
+ type: 'string',
1907
+ required: true,
1908
+ fieldName: consentPolicyConfig?.fields?.name || 'name'
1909
+ },
1910
+ effectiveDate: {
1911
+ type: 'date',
1912
+ required: true,
1913
+ fieldName: consentPolicyConfig?.fields?.effectiveDate || 'effectiveDate'
1914
+ },
1915
+ expirationDate: {
1916
+ type: 'date',
1917
+ required: false,
1918
+ fieldName: consentPolicyConfig?.fields?.expirationDate || 'expirationDate'
1919
+ },
1920
+ content: {
1921
+ type: 'string',
1922
+ required: true,
1923
+ fieldName: consentPolicyConfig?.fields?.content || 'content'
1924
+ },
1925
+ contentHash: {
1926
+ type: 'string',
1927
+ required: true,
1928
+ fieldName: consentPolicyConfig?.fields?.contentHash || 'contentHash'
1929
+ },
1930
+ isActive: {
1931
+ type: 'boolean',
1932
+ defaultValue: true,
1933
+ required: true,
1934
+ fieldName: consentPolicyConfig?.fields?.isActive || 'isActive'
1935
+ },
1936
+ createdAt: {
1937
+ type: 'date',
1938
+ defaultValue: ()=>new Date(),
1939
+ required: true,
1940
+ fieldName: consentPolicyConfig?.fields?.createdAt || 'createdAt'
1941
+ },
1942
+ ...policyFields || {},
1943
+ ...consentPolicyConfig?.additionalFields || {}
1944
+ },
1945
+ order: 2
1946
+ };
1947
+ }
1948
+ function consentPurposeJunctionRegistry({ adapter, ...ctx }) {
1949
+ const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
1950
+ return {
1951
+ createConsentPurposeJunction: async (junction, context)=>{
1952
+ const createdJunction = await createWithHooks({
1953
+ data: {
1954
+ createdAt: new Date(),
1955
+ ...junction,
1956
+ status: 'active'
1957
+ },
1958
+ model: 'consentPurposeJunction',
1959
+ customFn: void 0,
1960
+ context
1961
+ });
1962
+ if (!createdJunction) throw new Error('Failed to create consent-purpose junction - operation returned null');
1963
+ return createdJunction;
1964
+ },
1965
+ findConsentPurposesByConsentId: async (consentId)=>{
1966
+ const junctions = await adapter.findMany({
1967
+ model: 'consentPurposeJunction',
1968
+ where: [
1969
+ {
1970
+ field: 'consentId',
1971
+ value: consentId
1972
+ }
1973
+ ],
1974
+ sortBy: {
1975
+ field: 'createdAt',
1976
+ direction: 'desc'
1977
+ }
1978
+ });
1979
+ return junctions.map((junction)=>validateEntityOutput('consentPurposeJunction', junction, ctx.options));
1980
+ },
1981
+ findConsentPurposesByPurposeId: async (purposeId)=>{
1982
+ const junctions = await adapter.findMany({
1983
+ model: 'consentPurposeJunction',
1984
+ where: [
1985
+ {
1986
+ field: 'purposeId',
1987
+ value: purposeId
1988
+ }
1989
+ ],
1990
+ sortBy: {
1991
+ field: 'createdAt',
1992
+ direction: 'desc'
1993
+ }
1994
+ });
1995
+ return junctions.map((junction)=>validateEntityOutput('consentPurposeJunction', junction, ctx.options));
1996
+ },
1997
+ updateConsentPurposeJunction: async (junctionId, status, context)=>{
1998
+ const junction = await updateWithHooks({
1999
+ data: {
2000
+ status,
2001
+ updatedAt: new Date()
2002
+ },
2003
+ where: [
2004
+ {
2005
+ field: 'id',
2006
+ value: junctionId
2007
+ }
2008
+ ],
2009
+ model: 'consentPurposeJunction',
2010
+ customFn: void 0,
2011
+ context
2012
+ });
2013
+ return junction ? validateEntityOutput('consentPurposeJunction', junction, ctx.options) : null;
2014
+ },
2015
+ deleteConsentPurposeJunctionsByConsentId: async (consentId)=>{
2016
+ try {
2017
+ await adapter.deleteMany({
2018
+ model: 'consentPurposeJunction',
2019
+ where: [
2020
+ {
2021
+ field: 'consentId',
2022
+ value: consentId
2023
+ }
2024
+ ]
2025
+ });
2026
+ return true;
2027
+ } catch (error) {
2028
+ ctx.logger.error('Error deleting consent-purpose junctions:', error);
2029
+ return false;
2030
+ }
2031
+ }
2032
+ };
2033
+ }
2034
+ const consentPurposeJunctionSchema = external_zod_namespaceObject.z.object({
2035
+ id: external_zod_namespaceObject.z.string(),
2036
+ consentId: external_zod_namespaceObject.z.string(),
2037
+ consentPurposeId: external_zod_namespaceObject.z.string(),
2038
+ status: external_zod_namespaceObject.z["enum"]([
2039
+ 'active',
2040
+ 'withdrawn'
2041
+ ], {
2042
+ errorMap: ()=>({
2043
+ message: "Status must be either 'active' or 'withdrawn'"
2044
+ })
2045
+ }).default('active'),
2046
+ metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.union([
2047
+ external_zod_namespaceObject.z.string(),
2048
+ external_zod_namespaceObject.z.number(),
2049
+ external_zod_namespaceObject.z.boolean()
2050
+ ])).optional(),
2051
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
2052
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
2053
+ });
2054
+ function getPurposeJunctionTable(options, junctionFields) {
2055
+ const purposeJunctionConfig = options.tables?.consentPurposeJunction;
2056
+ const consentConfig = options.tables?.consent;
2057
+ const purposeConfig = options.tables?.consentPurpose;
2058
+ return {
2059
+ entityName: purposeJunctionConfig?.entityName || 'consentPurposeJunction',
2060
+ entityPrefix: purposeJunctionConfig?.entityPrefix || 'pjx',
2061
+ schema: consentPurposeJunctionSchema,
2062
+ fields: {
2063
+ consentId: {
2064
+ type: 'string',
2065
+ required: true,
2066
+ fieldName: purposeJunctionConfig?.fields?.consentId || 'consentId',
2067
+ references: {
2068
+ model: consentConfig?.entityName || 'consent',
2069
+ field: 'id'
2070
+ }
2071
+ },
2072
+ purposeId: {
2073
+ type: 'string',
2074
+ required: true,
2075
+ fieldName: purposeJunctionConfig?.fields?.purposeId || 'purposeId',
2076
+ references: {
2077
+ model: purposeConfig?.entityName || 'consentPurpose',
2078
+ field: 'id'
2079
+ }
2080
+ },
2081
+ status: {
2082
+ type: 'string',
2083
+ defaultValue: ()=>'active',
2084
+ required: true,
2085
+ fieldName: purposeJunctionConfig?.fields?.status || 'status'
2086
+ },
2087
+ metadata: {
2088
+ type: 'json',
2089
+ required: false,
2090
+ fieldName: purposeJunctionConfig?.fields?.metadata || 'metadata'
2091
+ },
2092
+ createdAt: {
2093
+ type: 'date',
2094
+ defaultValue: ()=>new Date(),
2095
+ required: true,
2096
+ fieldName: purposeJunctionConfig?.fields?.createdAt || 'createdAt'
2097
+ },
2098
+ updatedAt: {
2099
+ type: 'date',
2100
+ required: false,
2101
+ fieldName: purposeJunctionConfig?.fields?.updatedAt || 'updatedAt'
2102
+ },
2103
+ ...junctionFields || {},
2104
+ ...purposeJunctionConfig?.additionalFields || {}
2105
+ },
2106
+ uniqueConstraints: [
2107
+ {
2108
+ name: 'unique_consent_purpose',
2109
+ fields: [
2110
+ 'consentId',
2111
+ 'purposeId'
2112
+ ]
2113
+ }
2114
+ ],
2115
+ order: 4
2116
+ };
2117
+ }
2118
+ function consentPurposeRegistry({ adapter, ...ctx }) {
2119
+ const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
2120
+ return {
2121
+ createConsentPurpose: async (consentPurpose, context)=>{
2122
+ const createdPurpose = await createWithHooks({
2123
+ data: {
2124
+ id: consentPurpose.id || '',
2125
+ createdAt: new Date(),
2126
+ updatedAt: new Date(),
2127
+ ...consentPurpose
2128
+ },
2129
+ model: 'consentPurpose',
2130
+ context
2131
+ });
2132
+ if (!createdPurpose) throw new Error('Failed to create consent consentPurpose - operation returned null');
2133
+ return validateEntityOutput('consentPurpose', createdPurpose, ctx.options);
2134
+ },
2135
+ findConsentPurposes: async (includeInactive)=>{
2136
+ const whereConditions = [];
2137
+ if (!includeInactive) whereConditions.push({
2138
+ field: 'isActive',
2139
+ value: true
2140
+ });
2141
+ const purposes = await adapter.findMany({
2142
+ model: 'consentPurpose',
2143
+ where: whereConditions,
2144
+ sortBy: {
2145
+ field: 'createdAt',
2146
+ direction: 'asc'
2147
+ }
2148
+ });
2149
+ return purposes.map((consentPurpose)=>validateEntityOutput('consentPurpose', consentPurpose, ctx.options));
2150
+ },
2151
+ findConsentPurposeById: async (purposeId)=>{
2152
+ const consentPurpose = await adapter.findOne({
2153
+ model: 'consentPurpose',
2154
+ where: [
2155
+ {
2156
+ field: 'id',
2157
+ value: purposeId
2158
+ }
2159
+ ]
2160
+ });
2161
+ return consentPurpose ? validateEntityOutput('consentPurpose', consentPurpose, ctx.options) : null;
2162
+ },
2163
+ findConsentPurposeByCode: async (code)=>{
2164
+ const consentPurpose = await adapter.findOne({
2165
+ model: 'consentPurpose',
2166
+ where: [
2167
+ {
2168
+ field: 'code',
2169
+ value: code
2170
+ }
2171
+ ]
2172
+ });
2173
+ return consentPurpose ? validateEntityOutput('consentPurpose', consentPurpose, ctx.options) : null;
2174
+ },
2175
+ updateConsentPurpose: async (purposeId, data, context)=>{
2176
+ const consentPurpose = await updateWithHooks({
2177
+ data: {
2178
+ ...data,
2179
+ updatedAt: new Date()
2180
+ },
2181
+ where: [
2182
+ {
2183
+ field: 'id',
2184
+ value: purposeId
2185
+ }
2186
+ ],
2187
+ model: 'consentPurpose',
2188
+ context
2189
+ });
2190
+ return consentPurpose ? validateEntityOutput('consentPurpose', consentPurpose, ctx.options) : null;
2191
+ }
2192
+ };
2193
+ }
2194
+ const purposeSchema = external_zod_namespaceObject.z.object({
2195
+ id: external_zod_namespaceObject.z.string(),
2196
+ code: external_zod_namespaceObject.z.string(),
2197
+ name: external_zod_namespaceObject.z.string(),
2198
+ description: external_zod_namespaceObject.z.string(),
2199
+ isEssential: external_zod_namespaceObject.z.boolean().default(false),
2200
+ dataCategory: external_zod_namespaceObject.z.string().optional(),
2201
+ legalBasis: external_zod_namespaceObject.z.string().optional(),
2202
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
2203
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
2204
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
2205
+ });
2206
+ function getPurposeTable(options, purposeFields) {
2207
+ const purposeConfig = options.tables?.consentPurpose;
2208
+ return {
2209
+ entityName: purposeConfig?.entityName || 'consentPurpose',
2210
+ entityPrefix: purposeConfig?.entityPrefix || 'pur',
2211
+ schema: purposeSchema,
2212
+ fields: {
2213
+ code: {
2214
+ type: 'string',
2215
+ required: true,
2216
+ fieldName: purposeConfig?.fields?.code || 'code'
2217
+ },
2218
+ name: {
2219
+ type: 'string',
2220
+ required: true,
2221
+ fieldName: purposeConfig?.fields?.name || 'name'
2222
+ },
2223
+ description: {
2224
+ type: 'string',
2225
+ required: true,
2226
+ fieldName: purposeConfig?.fields?.description || "description"
2227
+ },
2228
+ isEssential: {
2229
+ type: 'boolean',
2230
+ defaultValue: ()=>false,
2231
+ required: true,
2232
+ fieldName: purposeConfig?.fields?.isEssential || 'isEssential'
2233
+ },
2234
+ dataCategory: {
2235
+ type: 'string',
2236
+ required: false,
2237
+ fieldName: purposeConfig?.fields?.dataCategory || 'dataCategory'
2238
+ },
2239
+ legalBasis: {
2240
+ type: 'string',
2241
+ required: false,
2242
+ fieldName: purposeConfig?.fields?.legalBasis || 'legalBasis'
2243
+ },
2244
+ isActive: {
2245
+ type: 'boolean',
2246
+ defaultValue: true,
2247
+ required: true,
2248
+ fieldName: purposeConfig?.fields?.isActive || 'isActive'
2249
+ },
2250
+ createdAt: {
2251
+ type: 'date',
2252
+ defaultValue: ()=>new Date(),
2253
+ required: true,
2254
+ fieldName: purposeConfig?.fields?.createdAt || 'createdAt'
2255
+ },
2256
+ updatedAt: {
2257
+ type: 'date',
2258
+ defaultValue: ()=>new Date(),
2259
+ required: true,
2260
+ fieldName: purposeConfig?.fields?.updatedAt || 'updatedAt'
2261
+ },
2262
+ ...purposeFields || {},
2263
+ ...purposeConfig?.additionalFields || {}
2264
+ },
2265
+ order: 1
2266
+ };
2267
+ }
2268
+ function consentRecordRegistry({ adapter, ...ctx }) {
2269
+ const { createWithHooks } = getWithHooks(adapter, ctx);
2270
+ return {
2271
+ createConsentRecord: async (record, context)=>{
2272
+ const createdRecord = await createWithHooks({
2273
+ data: {
2274
+ createdAt: record.createdAt || new Date(),
2275
+ updatedAt: record.updatedAt || new Date(),
2276
+ ...record
2277
+ },
2278
+ model: 'consentRecord',
2279
+ customFn: void 0,
2280
+ context
2281
+ });
2282
+ if (!createdRecord) throw new Error('Failed to create consent record - operation returned null');
2283
+ return createdRecord;
2284
+ },
2285
+ findConsentRecords: async (subjectId, consentId, actionType, limit)=>{
2286
+ const whereConditions = [];
2287
+ if (subjectId) whereConditions.push({
2288
+ field: 'subjectId',
2289
+ value: subjectId
2290
+ });
2291
+ if (consentId) whereConditions.push({
2292
+ field: 'consentId',
2293
+ value: consentId
2294
+ });
2295
+ if (actionType) whereConditions.push({
2296
+ field: 'actionType',
2297
+ value: actionType
2298
+ });
2299
+ const records = await adapter.findMany({
2300
+ model: 'consentRecord',
2301
+ where: whereConditions,
2302
+ sortBy: {
2303
+ field: 'createdAt',
2304
+ direction: 'desc'
2305
+ },
2306
+ limit
2307
+ });
2308
+ return records.map((record)=>validateEntityOutput('consentRecord', record, ctx.options));
2309
+ },
2310
+ findConsentRecordById: async (recordId)=>{
2311
+ const record = await adapter.findOne({
2312
+ model: 'consentRecord',
2313
+ where: [
2314
+ {
2315
+ field: 'id',
2316
+ value: recordId
2317
+ }
2318
+ ]
2319
+ });
2320
+ return record ? validateEntityOutput('consentRecord', record, ctx.options) : null;
2321
+ },
2322
+ findConsentRecordsBySubjectId: async (subjectId, limit)=>{
2323
+ const records = await adapter.findMany({
2324
+ model: 'consentRecord',
2325
+ where: [
2326
+ {
2327
+ field: 'subjectId',
2328
+ value: subjectId
2329
+ }
2330
+ ],
2331
+ sortBy: {
2332
+ field: 'createdAt',
2333
+ direction: 'desc'
2334
+ },
2335
+ limit
2336
+ });
2337
+ return records.map((record)=>validateEntityOutput('consentRecord', record, ctx.options));
2338
+ },
2339
+ findConsentRecordsByConsentId: async (consentId, limit)=>{
2340
+ const records = await adapter.findMany({
2341
+ model: 'consentRecord',
2342
+ where: [
2343
+ {
2344
+ field: 'consentId',
2345
+ value: consentId
2346
+ }
2347
+ ],
2348
+ sortBy: {
2349
+ field: 'createdAt',
2350
+ direction: 'desc'
2351
+ },
2352
+ limit
2353
+ });
2354
+ return records.map((record)=>validateEntityOutput('consentRecord', record, ctx.options));
2355
+ }
2356
+ };
2357
+ }
2358
+ const consentRecordSchema = external_zod_namespaceObject.z.object({
2359
+ id: external_zod_namespaceObject.z.string(),
2360
+ subjectId: external_zod_namespaceObject.z.string(),
2361
+ consentId: external_zod_namespaceObject.z.string().optional(),
2362
+ actionType: external_zod_namespaceObject.z.string(),
2363
+ details: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
2364
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
2365
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
2366
+ });
2367
+ function getConsentRecordTable(options, recordFields) {
2368
+ const recordConfig = options.tables?.record;
2369
+ const subjectConfig = options.tables?.subject;
2370
+ const consentConfig = options.tables?.consent;
2371
+ return {
2372
+ entityName: recordConfig?.entityName || 'consentRecord',
2373
+ entityPrefix: recordConfig?.entityPrefix || 'rec',
2374
+ schema: consentRecordSchema,
2375
+ fields: {
2376
+ subjectId: {
2377
+ type: 'string',
2378
+ required: true,
2379
+ fieldName: recordConfig?.fields?.subjectId || 'subjectId',
2380
+ references: {
2381
+ model: subjectConfig?.entityName || 'subject',
2382
+ field: 'id'
2383
+ }
2384
+ },
2385
+ consentId: {
2386
+ type: 'string',
2387
+ required: false,
2388
+ fieldName: recordConfig?.fields?.consentId || 'consentId',
2389
+ references: {
2390
+ model: consentConfig?.entityName || 'consent',
2391
+ field: 'id'
2392
+ }
2393
+ },
2394
+ actionType: {
2395
+ type: 'string',
2396
+ required: true,
2397
+ fieldName: recordConfig?.fields?.actionType || 'actionType'
2398
+ },
2399
+ details: {
2400
+ type: 'json',
2401
+ required: false,
2402
+ fieldName: recordConfig?.fields?.details || 'details'
2403
+ },
2404
+ createdAt: {
2405
+ type: 'date',
2406
+ defaultValue: ()=>new Date(),
2407
+ required: true,
2408
+ fieldName: recordConfig?.fields?.createdAt || 'createdAt'
2409
+ },
2410
+ ...recordFields || {},
2411
+ ...recordConfig?.additionalFields || {}
2412
+ },
2413
+ order: 4
2414
+ };
2415
+ }
2416
+ function consentWithdrawalRegistry({ adapter, ...ctx }) {
2417
+ const { createWithHooks } = getWithHooks(adapter, ctx);
2418
+ return {
2419
+ createConsentWithdrawal: async (consentWithdrawal, context)=>{
2420
+ const createdWithdrawal = await createWithHooks({
2421
+ data: {
2422
+ createdAt: new Date(),
2423
+ ...consentWithdrawal
2424
+ },
2425
+ model: 'consentWithdrawal',
2426
+ customFn: void 0,
2427
+ context
2428
+ });
2429
+ if (!createdWithdrawal) throw new Error('Failed to create consent withdrawal - operation returned null');
2430
+ return validateEntityOutput('consentWithdrawal', createdWithdrawal, ctx.options);
2431
+ },
2432
+ findConsentWithdrawals: async (subjectId, consentId, limit)=>{
2433
+ const whereConditions = [];
2434
+ if (subjectId) whereConditions.push({
2435
+ field: 'subjectId',
2436
+ value: subjectId
2437
+ });
2438
+ if (consentId) whereConditions.push({
2439
+ field: 'consentId',
2440
+ value: consentId
2441
+ });
2442
+ const consentWithdrawals = await adapter.findMany({
2443
+ model: 'consentWithdrawal',
2444
+ where: whereConditions,
2445
+ sortBy: {
2446
+ field: 'createdAt',
2447
+ direction: 'desc'
2448
+ },
2449
+ limit
2450
+ });
2451
+ return consentWithdrawals.map((consentWithdrawal)=>validateEntityOutput('consentWithdrawal', consentWithdrawal, ctx.options));
2452
+ },
2453
+ findConsentWithdrawalById: async (withdrawalId)=>{
2454
+ const consentWithdrawal = await adapter.findOne({
2455
+ model: 'consentWithdrawal',
2456
+ where: [
2457
+ {
2458
+ field: 'id',
2459
+ value: withdrawalId
2460
+ }
2461
+ ]
2462
+ });
2463
+ return consentWithdrawal ? validateEntityOutput('consentWithdrawal', consentWithdrawal, ctx.options) : null;
2464
+ },
2465
+ findConsentWithdrawalsBySubjectId: async (subjectId, limit)=>{
2466
+ const consentWithdrawals = await adapter.findMany({
2467
+ model: 'consentWithdrawal',
2468
+ where: [
2469
+ {
2470
+ field: 'subjectId',
2471
+ value: subjectId
2472
+ }
2473
+ ],
2474
+ sortBy: {
2475
+ field: 'createdAt',
2476
+ direction: 'desc'
2477
+ },
2478
+ limit
2479
+ });
2480
+ return consentWithdrawals.map((consentWithdrawal)=>validateEntityOutput('consentWithdrawal', consentWithdrawal, ctx.options));
2481
+ },
2482
+ findConsentWithdrawalByConsentId: async (consentId)=>{
2483
+ const consentWithdrawal = await adapter.findOne({
2484
+ model: 'consentWithdrawal',
2485
+ where: [
2486
+ {
2487
+ field: 'consentId',
2488
+ value: consentId
2489
+ }
2490
+ ],
2491
+ sortBy: {
2492
+ field: 'createdAt',
2493
+ direction: 'desc'
2494
+ }
2495
+ });
2496
+ return consentWithdrawal ? validateEntityOutput('consentWithdrawal', consentWithdrawal, ctx.options) : null;
2497
+ }
2498
+ };
2499
+ }
2500
+ const consentWithdrawalSchema = external_zod_namespaceObject.z.object({
2501
+ id: external_zod_namespaceObject.z.string(),
2502
+ consentId: external_zod_namespaceObject.z.string(),
2503
+ subjectId: external_zod_namespaceObject.z.string(),
2504
+ withdrawalReason: external_zod_namespaceObject.z.string().optional(),
2505
+ withdrawalMethod: external_zod_namespaceObject.z["enum"]([
2506
+ 'subject-initiated',
2507
+ 'automatic-expiry',
2508
+ 'admin',
2509
+ 'api',
2510
+ 'other'
2511
+ ]).default('subject-initiated'),
2512
+ ipAddress: external_zod_namespaceObject.z.string().optional(),
2513
+ userAgent: external_zod_namespaceObject.z.string().optional(),
2514
+ metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
2515
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
2516
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
2517
+ });
2518
+ function getConsentWithdrawalTable(options, withdrawalFields) {
2519
+ const consentWithdrawalConfig = options.tables?.consentWithdrawal;
2520
+ const consentConfig = options.tables?.consent;
2521
+ const subjectConfig = options.tables?.subject;
2522
+ return {
2523
+ entityName: consentWithdrawalConfig?.entityName || 'consentWithdrawal',
2524
+ entityPrefix: consentWithdrawalConfig?.entityPrefix || 'wdr',
2525
+ schema: consentWithdrawalSchema,
2526
+ fields: {
2527
+ consentId: {
2528
+ type: 'string',
2529
+ required: true,
2530
+ fieldName: consentWithdrawalConfig?.fields?.consentId || 'consentId',
2531
+ references: {
2532
+ model: consentConfig?.entityName || 'consent',
2533
+ field: 'id'
2534
+ }
2535
+ },
2536
+ subjectId: {
2537
+ type: 'string',
2538
+ required: true,
2539
+ fieldName: consentWithdrawalConfig?.fields?.subjectId || 'subjectId',
2540
+ references: {
2541
+ model: subjectConfig?.entityName || 'subject',
2542
+ field: 'id'
2543
+ }
2544
+ },
2545
+ withdrawalReason: {
2546
+ type: 'string',
2547
+ required: false,
2548
+ fieldName: consentWithdrawalConfig?.fields?.withdrawalReason || 'withdrawalReason'
2549
+ },
2550
+ withdrawalMethod: {
2551
+ type: 'string',
2552
+ defaultValue: ()=>'subject-initiated',
2553
+ required: true,
2554
+ fieldName: consentWithdrawalConfig?.fields?.withdrawalMethod || 'withdrawalMethod'
2555
+ },
2556
+ ipAddress: {
2557
+ type: 'string',
2558
+ required: false,
2559
+ fieldName: consentWithdrawalConfig?.fields?.ipAddress || 'ipAddress'
2560
+ },
2561
+ userAgent: {
2562
+ type: 'string',
2563
+ required: false,
2564
+ fieldName: consentWithdrawalConfig?.fields?.userAgent || 'userAgent'
2565
+ },
2566
+ metadata: {
2567
+ type: 'json',
2568
+ required: false,
2569
+ fieldName: consentWithdrawalConfig?.fields?.metadata || 'metadata'
2570
+ },
2571
+ createdAt: {
2572
+ type: 'date',
2573
+ defaultValue: ()=>new Date(),
2574
+ required: true,
2575
+ fieldName: consentWithdrawalConfig?.fields?.createdAt || 'createdAt'
2576
+ },
2577
+ ...withdrawalFields || {},
2578
+ ...consentWithdrawalConfig?.additionalFields || {}
2579
+ },
2580
+ uniqueConstraints: consentWithdrawalConfig?.preventMultipleWithdrawals !== false ? [
2581
+ {
2582
+ name: 'unique_consent_withdrawal',
2583
+ fields: [
2584
+ 'consentId'
2585
+ ]
2586
+ }
2587
+ ] : [],
2588
+ indexes: [
2589
+ {
2590
+ name: 'subject_id_index',
2591
+ fields: [
2592
+ 'subjectId'
2593
+ ]
2594
+ },
2595
+ {
2596
+ name: 'created_at_index',
2597
+ fields: [
2598
+ 'createdAt'
2599
+ ]
2600
+ }
2601
+ ],
2602
+ order: 4
2603
+ };
2604
+ }
2605
+ function consentRegistry({ adapter, ...ctx }) {
2606
+ const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
2607
+ const registry = {
2608
+ createConsent: async (consent, context)=>{
2609
+ const createdConsent = await createWithHooks({
2610
+ data: {
2611
+ createdAt: new Date(),
2612
+ ...consent
2613
+ },
2614
+ model: 'consent',
2615
+ context
2616
+ });
2617
+ if (!createdConsent) throw new Error('Failed to create consent - operation returned null');
2618
+ return createdConsent;
2619
+ },
2620
+ findConsents: async (params = {})=>{
2621
+ const whereConditions = [];
2622
+ if (!params.includeInactive) whereConditions.push({
2623
+ field: 'isActive',
2624
+ value: true
2625
+ });
2626
+ if (params.subjectId) whereConditions.push({
2627
+ field: 'subjectId',
2628
+ value: params.subjectId
2629
+ });
2630
+ if (params.domainId) whereConditions.push({
2631
+ field: 'domainId',
2632
+ value: params.domainId
2633
+ });
2634
+ if (params.status) whereConditions.push({
2635
+ field: 'status',
2636
+ value: params.status
2637
+ });
2638
+ if (params.purposeIds && params.purposeIds.length > 0) whereConditions.push({
2639
+ field: 'purposeIds',
2640
+ operator: 'contains',
2641
+ value: params.purposeIds
2642
+ });
2643
+ const consents = await adapter.findMany({
2644
+ model: 'consent',
2645
+ where: whereConditions,
2646
+ sortBy: {
2647
+ field: 'givenAt',
2648
+ direction: 'desc'
2649
+ }
2650
+ });
2651
+ return consents.map((consent)=>validateEntityOutput('consent', consent, ctx.options));
2652
+ },
2653
+ findConsentById: async (consentId)=>{
2654
+ const consent = await adapter.findOne({
2655
+ model: 'consent',
2656
+ where: [
2657
+ {
2658
+ field: 'id',
2659
+ value: consentId
2660
+ }
2661
+ ]
2662
+ });
2663
+ return consent ? validateEntityOutput('consent', consent, ctx.options) : null;
2664
+ },
2665
+ findConsentsBySubjectId: async (subjectId)=>{
2666
+ const consents = await adapter.findMany({
2667
+ model: 'consent',
2668
+ where: [
2669
+ {
2670
+ field: 'subjectId',
2671
+ value: subjectId
2672
+ }
2673
+ ],
2674
+ sortBy: {
2675
+ field: 'givenAt',
2676
+ direction: 'desc'
2677
+ }
2678
+ });
2679
+ return consents.map((consent)=>validateEntityOutput('consent', consent, ctx.options));
2680
+ },
2681
+ findConsentsByDomainId: async (domainId)=>{
2682
+ const consents = await adapter.findMany({
2683
+ model: 'consent',
2684
+ where: [
2685
+ {
2686
+ field: 'domainId',
2687
+ value: domainId
2688
+ }
2689
+ ],
2690
+ sortBy: {
2691
+ field: 'givenAt',
2692
+ direction: 'desc'
2693
+ }
2694
+ });
2695
+ return consents.map((consent)=>validateEntityOutput('consent', consent, ctx.options));
2696
+ },
2697
+ updateConsent: async (consentId, data, context)=>{
2698
+ const consent = await updateWithHooks({
2699
+ data: {
2700
+ ...data
2701
+ },
2702
+ where: [
2703
+ {
2704
+ field: 'id',
2705
+ value: consentId
2706
+ }
2707
+ ],
2708
+ model: 'consent',
2709
+ context
2710
+ });
2711
+ return consent ? validateEntityOutput('consent', consent, ctx.options) : null;
2712
+ },
2713
+ updateWithdrawal: async (consentId, withdrawalReason, context)=>{
2714
+ const updateData = {
2715
+ status: 'withdrawn'
2716
+ };
2717
+ if (withdrawalReason) updateData.withdrawalReason = withdrawalReason;
2718
+ const consent = await updateWithHooks({
2719
+ data: updateData,
2720
+ where: [
2721
+ {
2722
+ field: 'id',
2723
+ value: consentId
2724
+ }
2725
+ ],
2726
+ model: 'consent',
2727
+ context
2728
+ });
2729
+ return consent ? validateEntityOutput('consent', consent, ctx.options) : null;
2730
+ },
2731
+ revokeConsent: async ({ consentId, reason, actor, metadata, context })=>{
2732
+ const consent = await registry.findConsentById(consentId);
2733
+ if (!consent) throw new Error('Consent not found');
2734
+ const updateData = {
2735
+ status: 'withdrawn',
2736
+ withdrawalReason: reason,
2737
+ metadata: {
2738
+ ...consent.metadata,
2739
+ consentWithdrawal: {
2740
+ actor,
2741
+ timestamp: new Date().toISOString(),
2742
+ ...metadata
2743
+ }
2744
+ }
2745
+ };
2746
+ return registry.updateConsent(consentId, updateData, context);
2747
+ },
2748
+ getRecords: async (consentId)=>{
2749
+ const records = await adapter.findMany({
2750
+ model: 'consentRecord',
2751
+ where: [
2752
+ {
2753
+ field: 'consentId',
2754
+ value: consentId
2755
+ }
2756
+ ],
2757
+ sortBy: {
2758
+ field: 'createdAt',
2759
+ direction: 'desc'
2760
+ }
2761
+ });
2762
+ return records.map((record)=>validateEntityOutput('consentRecord', record, ctx.options));
2763
+ },
2764
+ getWithdrawals: async (consentId)=>{
2765
+ const consentWithdrawals = await adapter.findMany({
2766
+ model: 'consentWithdrawal',
2767
+ where: [
2768
+ {
2769
+ field: 'consentId',
2770
+ value: consentId
2771
+ }
2772
+ ],
2773
+ sortBy: {
2774
+ field: 'createdAt',
2775
+ direction: 'desc'
2776
+ }
2777
+ });
2778
+ return consentWithdrawals.map((consentWithdrawal)=>validateEntityOutput('consentWithdrawal', consentWithdrawal, ctx.options));
2779
+ }
2780
+ };
2781
+ return registry;
2782
+ }
2783
+ const consentHistorySchema = external_zod_namespaceObject.z.object({
2784
+ actionType: external_zod_namespaceObject.z["enum"]([
2785
+ 'given',
2786
+ 'withdrawn',
2787
+ 'updated',
2788
+ 'expired'
2789
+ ]),
2790
+ timestamp: external_zod_namespaceObject.z.date(),
2791
+ details: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
2792
+ previousState: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
2793
+ newState: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional()
2794
+ });
2795
+ const consentSchema = external_zod_namespaceObject.z.object({
2796
+ id: external_zod_namespaceObject.z.string(),
2797
+ subjectId: external_zod_namespaceObject.z.string(),
2798
+ domainId: external_zod_namespaceObject.z.string(),
2799
+ purposeIds: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()),
2800
+ metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
2801
+ policyId: external_zod_namespaceObject.z.string().optional(),
2802
+ ipAddress: external_zod_namespaceObject.z.string().optional(),
2803
+ userAgent: external_zod_namespaceObject.z.string().optional(),
2804
+ status: external_zod_namespaceObject.z["enum"]([
2805
+ 'active',
2806
+ 'withdrawn',
2807
+ 'expired'
2808
+ ]).default('active'),
2809
+ withdrawalReason: external_zod_namespaceObject.z.string().optional(),
2810
+ givenAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
2811
+ validUntil: external_zod_namespaceObject.z.date().optional(),
2812
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
2813
+ history: external_zod_namespaceObject.z.array(consentHistorySchema).default([])
2814
+ });
2815
+ function getConsentTable(options, consentFields) {
2816
+ const consentConfig = options.tables?.consent;
2817
+ const subjectConfig = options.tables?.subject;
2818
+ const domainConfig = options.tables?.domain;
2819
+ const policyConfig = options.tables?.consentPolicy;
2820
+ const purposeConfig = options.tables?.consentPurpose;
2821
+ return {
2822
+ entityName: consentConfig?.entityName || 'consent',
2823
+ entityPrefix: consentConfig?.entityPrefix || 'cns',
2824
+ schema: consentSchema,
2825
+ fields: {
2826
+ subjectId: {
2827
+ type: 'string',
2828
+ required: true,
2829
+ fieldName: consentConfig?.fields?.subjectId || 'subjectId',
2830
+ references: {
2831
+ model: subjectConfig?.entityName || 'subject',
2832
+ field: 'id'
2833
+ }
2834
+ },
2835
+ domainId: {
2836
+ type: 'string',
2837
+ required: true,
2838
+ fieldName: consentConfig?.fields?.domainId || 'domainId',
2839
+ references: {
2840
+ model: domainConfig?.entityName || 'domain',
2841
+ field: 'id'
2842
+ }
2843
+ },
2844
+ purposeIds: {
2845
+ type: 'json',
2846
+ required: false,
2847
+ fieldName: consentConfig?.fields?.purposeIds || 'purposeIds',
2848
+ references: {
2849
+ model: purposeConfig?.entityName || 'consentPurpose',
2850
+ field: 'id',
2851
+ type: 'array'
2852
+ }
2853
+ },
2854
+ metadata: {
2855
+ type: 'json',
2856
+ required: false,
2857
+ fieldName: consentConfig?.fields?.metadata || 'metadata'
2858
+ },
2859
+ policyId: {
2860
+ type: 'string',
2861
+ required: false,
2862
+ fieldName: consentConfig?.fields?.policyId || 'policyId',
2863
+ references: {
2864
+ model: policyConfig?.entityName || 'consentPolicy',
2865
+ field: 'id'
2866
+ }
2867
+ },
2868
+ ipAddress: {
2869
+ type: 'string',
2870
+ required: false,
2871
+ fieldName: consentConfig?.fields?.ipAddress || 'ipAddress'
2872
+ },
2873
+ userAgent: {
2874
+ type: 'string',
2875
+ required: false,
2876
+ fieldName: consentConfig?.fields?.userAgent || 'userAgent'
2877
+ },
2878
+ status: {
2879
+ type: 'string',
2880
+ defaultValue: ()=>'active',
2881
+ required: true,
2882
+ fieldName: consentConfig?.fields?.status || 'status'
2883
+ },
2884
+ withdrawalReason: {
2885
+ type: 'string',
2886
+ required: false,
2887
+ fieldName: consentConfig?.fields?.withdrawalReason || 'withdrawalReason'
2888
+ },
2889
+ givenAt: {
2890
+ type: 'date',
2891
+ defaultValue: ()=>new Date(),
2892
+ required: true,
2893
+ fieldName: consentConfig?.fields?.givenAt || 'givenAt'
2894
+ },
2895
+ validUntil: {
2896
+ type: 'date',
2897
+ required: false,
2898
+ fieldName: consentConfig?.fields?.validUntil || 'validUntil',
2899
+ transform: {
2900
+ input: (val, data)=>{
2901
+ if (val) return val;
2902
+ const expiresIn = consentConfig?.expiresIn || 31536000;
2903
+ const givenAt = data.givenAt instanceof Date ? data.givenAt : new Date();
2904
+ if (expiresIn > 0) {
2905
+ const validUntil = new Date(givenAt);
2906
+ validUntil.setSeconds(validUntil.getSeconds() + expiresIn);
2907
+ return validUntil;
2908
+ }
2909
+ }
2910
+ }
2911
+ },
2912
+ isActive: {
2913
+ type: 'boolean',
2914
+ defaultValue: true,
2915
+ required: true,
2916
+ fieldName: consentConfig?.fields?.isActive || 'isActive'
2917
+ },
2918
+ ...consentFields || {},
2919
+ ...consentConfig?.additionalFields || {}
2920
+ },
2921
+ order: 3
2922
+ };
2923
+ }
2924
+ function domainRegistry({ adapter, ...ctx }) {
2925
+ const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
2926
+ const registry = {
2927
+ createDomain: async (domain, context)=>{
2928
+ const createdDomain = await createWithHooks({
2929
+ data: {
2930
+ ...domain,
2931
+ createdAt: new Date(),
2932
+ updatedAt: new Date()
2933
+ },
2934
+ model: 'domain',
2935
+ customFn: void 0,
2936
+ context
2937
+ });
2938
+ if (!createdDomain) throw new Error('Failed to create domain - operation returned null');
2939
+ return createdDomain;
2940
+ },
2941
+ findOrCreateDomain: async function(name, context) {
2942
+ const existingDomain = await this.findDomainByName(name);
2943
+ if (existingDomain) return existingDomain;
2944
+ const domain = await this.createDomain({
2945
+ name,
2946
+ description: `Auto-created domain for ${name}`,
2947
+ isActive: true,
2948
+ isVerified: true,
2949
+ allowedOrigins: []
2950
+ }, context);
2951
+ if (!domain) throw new src_error.kO('Failed to create domain', {
2952
+ code: src_error.H8.INTERNAL_SERVER_ERROR,
2953
+ status: 503
2954
+ });
2955
+ return domain;
2956
+ },
2957
+ findDomains: async (params = {})=>{
2958
+ const whereConditions = [];
2959
+ if (!params.includeInactive) whereConditions.push({
2960
+ field: 'isActive',
2961
+ value: true
2962
+ });
2963
+ if (params.name) whereConditions.push({
2964
+ field: 'name',
2965
+ value: params.name
2966
+ });
2967
+ const domains = await adapter.findMany({
2968
+ model: 'domain',
2969
+ where: whereConditions,
2970
+ sortBy: {
2971
+ field: 'name',
2972
+ direction: 'asc'
2973
+ }
2974
+ });
2975
+ return domains.map((domain)=>validateEntityOutput('domain', domain, ctx.options));
2976
+ },
2977
+ findDomain: async (name)=>{
2978
+ const domains = await registry.findDomains({
2979
+ name,
2980
+ includeInactive: false
2981
+ });
2982
+ return domains[0] || null;
2983
+ },
2984
+ findDomainById: async (domainId)=>{
2985
+ const domain = await adapter.findOne({
2986
+ model: 'domain',
2987
+ where: [
2988
+ {
2989
+ field: 'id',
2990
+ value: domainId
2991
+ }
2992
+ ]
2993
+ });
2994
+ return domain ? validateEntityOutput('domain', domain, ctx.options) : null;
2995
+ },
2996
+ findDomainByName: async (name)=>{
2997
+ const domain = await adapter.findOne({
2998
+ model: 'domain',
2999
+ where: [
3000
+ {
3001
+ field: 'name',
3002
+ value: name
3003
+ }
3004
+ ]
3005
+ });
3006
+ return domain ? validateEntityOutput('domain', domain, ctx.options) : null;
3007
+ },
3008
+ updateDomain: async (domainId, data, context)=>{
3009
+ const domain = await updateWithHooks({
3010
+ data: {
3011
+ ...data,
3012
+ updatedAt: new Date()
3013
+ },
3014
+ where: [
3015
+ {
3016
+ field: 'id',
3017
+ value: domainId
3018
+ }
3019
+ ],
3020
+ model: 'domain',
3021
+ customFn: void 0,
3022
+ context
3023
+ });
3024
+ return domain ? validateEntityOutput('domain', domain, ctx.options) : null;
3025
+ },
3026
+ verifyDomain: async (domainName)=>{
3027
+ const domain = await adapter.findOne({
3028
+ model: 'domain',
3029
+ where: [
3030
+ {
3031
+ field: 'name',
3032
+ value: domainName
3033
+ },
3034
+ {
3035
+ field: 'isActive',
3036
+ value: true
3037
+ }
3038
+ ]
3039
+ });
3040
+ return !!domain;
3041
+ }
3042
+ };
3043
+ return registry;
3044
+ }
3045
+ const domainSchema = external_zod_namespaceObject.z.object({
3046
+ id: external_zod_namespaceObject.z.string(),
3047
+ name: external_zod_namespaceObject.z.string().min(1),
3048
+ description: external_zod_namespaceObject.z.string().optional(),
3049
+ allowedOrigins: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional().default([]),
3050
+ isVerified: external_zod_namespaceObject.z.boolean().default(true),
3051
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
3052
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
3053
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
3054
+ });
3055
+ function getDomainTable(options, domainFields) {
3056
+ const domainConfig = options.tables?.domain;
3057
+ return {
3058
+ entityName: domainConfig?.entityName || 'domain',
3059
+ entityPrefix: domainConfig?.entityPrefix || 'dom',
3060
+ schema: domainSchema,
3061
+ fields: {
3062
+ name: {
3063
+ type: 'string',
3064
+ required: true,
3065
+ unique: true,
3066
+ fieldName: domainConfig?.fields?.name || 'name'
3067
+ },
3068
+ description: {
3069
+ type: 'string',
3070
+ required: false,
3071
+ fieldName: domainConfig?.fields?.description || "description"
3072
+ },
3073
+ allowedOrigins: {
3074
+ type: 'json',
3075
+ defaultValue: ()=>[],
3076
+ required: false,
3077
+ fieldName: domainConfig?.fields?.allowedOrigins || 'allowedOrigins'
3078
+ },
3079
+ isVerified: {
3080
+ type: 'boolean',
3081
+ defaultValue: true,
3082
+ required: true,
3083
+ fieldName: domainConfig?.fields?.isVerified || 'isVerified'
3084
+ },
3085
+ isActive: {
3086
+ type: 'boolean',
3087
+ defaultValue: true,
3088
+ required: true,
3089
+ fieldName: domainConfig?.fields?.isActive || 'isActive'
3090
+ },
3091
+ createdAt: {
3092
+ type: 'date',
3093
+ defaultValue: ()=>new Date(),
3094
+ required: true,
3095
+ fieldName: domainConfig?.fields?.createdAt || 'createdAt'
3096
+ },
3097
+ updatedAt: {
3098
+ type: 'date',
3099
+ required: false,
3100
+ fieldName: domainConfig?.fields?.updatedAt || 'updatedAt'
3101
+ },
3102
+ ...domainFields || {},
3103
+ ...domainConfig?.additionalFields || {}
3104
+ },
3105
+ order: 1
3106
+ };
3107
+ }
3108
+ function geoLocationRegistry({ adapter, ...ctx }) {
3109
+ const { createWithHooks } = getWithHooks(adapter, ctx);
3110
+ return {
3111
+ createGeoLocation: async (location, context)=>{
3112
+ const createdLocation = await createWithHooks({
3113
+ data: {
3114
+ createdAt: new Date(),
3115
+ ...location
3116
+ },
3117
+ model: 'consentGeoLocation',
3118
+ customFn: void 0,
3119
+ context
3120
+ });
3121
+ if (!createdLocation) throw new Error('Failed to create geo-location - operation returned null');
3122
+ return createdLocation;
3123
+ },
3124
+ findGeoLocations: async (filter)=>{
3125
+ const whereConditions = [];
3126
+ if (filter?.countryCode) whereConditions.push({
3127
+ field: 'countryCode',
3128
+ value: filter.countryCode
3129
+ });
3130
+ if (filter?.regionCode) whereConditions.push({
3131
+ field: 'regionCode',
3132
+ value: filter.regionCode
3133
+ });
3134
+ const locations = await adapter.findMany({
3135
+ model: 'geoLocation',
3136
+ where: whereConditions,
3137
+ sortBy: {
3138
+ field: 'countryName',
3139
+ direction: 'asc'
3140
+ }
3141
+ });
3142
+ return locations.map((location)=>validateEntityOutput('consentGeoLocation', location, ctx.options));
3143
+ },
3144
+ findGeoLocationById: async (locationId)=>{
3145
+ const location = await adapter.findOne({
3146
+ model: 'geoLocation',
3147
+ where: [
3148
+ {
3149
+ field: 'id',
3150
+ value: locationId
3151
+ }
3152
+ ]
3153
+ });
3154
+ return location ? validateEntityOutput('consentGeoLocation', location, ctx.options) : null;
3155
+ },
3156
+ findGeoLocationsByCountry: async (countryCode)=>{
3157
+ const locations = await adapter.findMany({
3158
+ model: 'geoLocation',
3159
+ where: [
3160
+ {
3161
+ field: 'countryCode',
3162
+ value: countryCode
3163
+ }
3164
+ ],
3165
+ sortBy: {
3166
+ field: 'regionName',
3167
+ direction: 'asc'
3168
+ }
3169
+ });
3170
+ return locations.map((location)=>validateEntityOutput('consentGeoLocation', location, ctx.options));
3171
+ }
3172
+ };
3173
+ }
3174
+ const geoLocationSchema = external_zod_namespaceObject.z.object({
3175
+ id: external_zod_namespaceObject.z.string(),
3176
+ countryCode: external_zod_namespaceObject.z.string().length(2).toUpperCase(),
3177
+ countryName: external_zod_namespaceObject.z.string(),
3178
+ regionCode: external_zod_namespaceObject.z.string().optional(),
3179
+ regionName: external_zod_namespaceObject.z.string().optional(),
3180
+ regulatoryZones: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z["enum"]([
3181
+ 'GDPR',
3182
+ 'CCPA',
3183
+ 'CPRA',
3184
+ 'LGPD',
3185
+ 'PIPEDA'
3186
+ ])).optional(),
3187
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date())
3188
+ });
3189
+ function getGeoLocationTable(options, geoLocationFields) {
3190
+ const geoLocationConfig = options.tables?.geoLocation;
3191
+ return {
3192
+ entityName: geoLocationConfig?.entityName || 'geoLocation',
3193
+ entityPrefix: geoLocationConfig?.entityPrefix || 'geo',
3194
+ schema: geoLocationSchema,
3195
+ fields: {
3196
+ countryCode: {
3197
+ type: 'string',
3198
+ required: true,
3199
+ fieldName: geoLocationConfig?.fields?.countryCode || 'countryCode'
3200
+ },
3201
+ countryName: {
3202
+ type: 'string',
3203
+ required: true,
3204
+ fieldName: geoLocationConfig?.fields?.countryName || 'countryName'
3205
+ },
3206
+ regionCode: {
3207
+ type: 'string',
3208
+ required: false,
3209
+ fieldName: geoLocationConfig?.fields?.regionCode || 'regionCode'
3210
+ },
3211
+ regionName: {
3212
+ type: 'string',
3213
+ required: false,
3214
+ fieldName: geoLocationConfig?.fields?.regionName || 'regionName'
3215
+ },
3216
+ regulatoryZones: {
3217
+ type: 'json',
3218
+ required: false,
3219
+ fieldName: geoLocationConfig?.fields?.regulatoryZones || 'regulatoryZones',
3220
+ transformer: {
3221
+ input: (value)=>JSON.stringify(value),
3222
+ output: (value)=>{
3223
+ try {
3224
+ return JSON.parse(value);
3225
+ } catch {
3226
+ return [];
3227
+ }
3228
+ }
3229
+ }
3230
+ },
3231
+ createdAt: {
3232
+ type: 'date',
3233
+ defaultValue: ()=>new Date(),
3234
+ required: true,
3235
+ fieldName: geoLocationConfig?.fields?.createdAt || 'createdAt'
3236
+ },
3237
+ ...geoLocationFields || {},
3238
+ ...geoLocationConfig?.additionalFields || {}
3239
+ },
3240
+ indexes: [
3241
+ {
3242
+ name: 'country_code_index',
3243
+ fields: [
3244
+ 'countryCode'
3245
+ ]
3246
+ },
3247
+ {
3248
+ name: 'region_code_index',
3249
+ fields: [
3250
+ 'regionCode'
3251
+ ]
3252
+ },
3253
+ {
3254
+ name: 'created_at_index',
3255
+ fields: [
3256
+ 'createdAt'
3257
+ ]
3258
+ }
3259
+ ],
3260
+ order: 1
3261
+ };
3262
+ }
3263
+ function subjectRegistry({ adapter, ...ctx }) {
3264
+ const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
3265
+ return {
3266
+ createSubject: async (subject, context)=>{
3267
+ const createdSubject = await createWithHooks({
3268
+ data: {
3269
+ createdAt: new Date(),
3270
+ updatedAt: new Date(),
3271
+ ...subject
3272
+ },
3273
+ model: 'subject',
3274
+ customFn: void 0,
3275
+ context
3276
+ });
3277
+ return createdSubject ? validateEntityOutput('subject', createdSubject, ctx.options) : null;
3278
+ },
3279
+ findOrCreateSubject: async function({ subjectId, externalSubjectId, ipAddress = 'unknown', context }) {
3280
+ if (subjectId && externalSubjectId) {
3281
+ const [subjectById, subjectByExternalId] = await Promise.all([
3282
+ this.findSubjectById(subjectId),
3283
+ this.findSubjectByExternalId(externalSubjectId)
3284
+ ]);
3285
+ if (!subjectById || !subjectByExternalId) {
3286
+ ctx.logger?.info('Subject validation failed: One or both subjects not found', {
3287
+ providedSubjectId: subjectId,
3288
+ providedExternalId: externalSubjectId,
3289
+ subjectByIdFound: !!subjectById,
3290
+ subjectByExternalIdFound: !!subjectByExternalId
3291
+ });
3292
+ throw new src_error.kO('The specified subject could not be found. Please verify the subject identifiers and try again.', {
3293
+ code: src_error.H8.NOT_FOUND,
3294
+ status: 404,
3295
+ data: {
3296
+ providedSubjectId: subjectId,
3297
+ providedExternalId: externalSubjectId
3298
+ }
3299
+ });
3300
+ }
3301
+ if (subjectById.id !== subjectByExternalId.id) {
3302
+ ctx.logger?.warn('Subject validation failed: IDs do not match the same subject', {
3303
+ providedSubjectId: subjectId,
3304
+ providedExternalId: externalSubjectId,
3305
+ subjectByIdId: subjectById.id,
3306
+ subjectByExternalIdId: subjectByExternalId.id
3307
+ });
3308
+ throw new src_error.kO('The provided subjectId and externalSubjectId do not match the same subject. Please ensure both identifiers refer to the same subject.', {
3309
+ code: src_error.H8.CONFLICT,
3310
+ status: 409,
3311
+ data: {
3312
+ providedSubjectId: subjectId,
3313
+ providedExternalId: externalSubjectId,
3314
+ subjectByIdId: subjectById.id,
3315
+ subjectByExternalIdId: subjectByExternalId.id
3316
+ }
3317
+ });
3318
+ }
3319
+ return subjectById;
3320
+ }
3321
+ if (subjectId) {
3322
+ const subject = await this.findSubjectById(subjectId);
3323
+ if (subject) return subject;
3324
+ throw new src_error.kO('Subject not found', {
3325
+ code: src_error.H8.NOT_FOUND,
3326
+ status: 404
3327
+ });
3328
+ }
3329
+ if (externalSubjectId) try {
3330
+ const subject = await this.findSubjectByExternalId(externalSubjectId);
3331
+ if (subject) {
3332
+ ctx.logger?.debug('Found existing subject by external ID', {
3333
+ externalSubjectId
3334
+ });
3335
+ return subject;
3336
+ }
3337
+ ctx.logger?.info('Creating new subject with external ID', {
3338
+ externalSubjectId
3339
+ });
3340
+ return await this.createSubject({
3341
+ externalId: externalSubjectId,
3342
+ identityProvider: 'external',
3343
+ lastIpAddress: ipAddress,
3344
+ isIdentified: true
3345
+ }, context);
3346
+ } catch (error) {
3347
+ if (error instanceof Error && error.message.includes('unique constraint')) {
3348
+ ctx.logger?.info('Handling duplicate key violation for external ID', {
3349
+ externalSubjectId
3350
+ });
3351
+ const subject = await this.findSubjectByExternalId(externalSubjectId);
3352
+ if (subject) return subject;
3353
+ }
3354
+ ctx.logger?.error('Failed to create or find subject with external ID', {
3355
+ externalSubjectId,
3356
+ error: error instanceof Error ? error.message : 'Unknown error'
3357
+ });
3358
+ throw new src_error.kO('Failed to create or find subject with external ID', {
3359
+ code: src_error.H8.INTERNAL_SERVER_ERROR,
3360
+ status: 500,
3361
+ data: {
3362
+ error: error instanceof Error ? error.message : 'Unknown error'
3363
+ }
3364
+ });
3365
+ }
3366
+ try {
3367
+ ctx.logger?.info('Creating new anonymous subject');
3368
+ return await this.createSubject({
3369
+ externalId: null,
3370
+ identityProvider: 'anonymous',
3371
+ lastIpAddress: ipAddress,
3372
+ isIdentified: false
3373
+ }, context);
3374
+ } catch (error) {
3375
+ ctx.logger?.error('Failed to create anonymous subject', {
3376
+ ipAddress,
3377
+ error: error instanceof Error ? error.message : 'Unknown error'
3378
+ });
3379
+ throw new src_error.kO('Failed to create anonymous subject', {
3380
+ code: src_error.H8.INTERNAL_SERVER_ERROR,
3381
+ status: 500,
3382
+ data: {
3383
+ error: error instanceof Error ? error.message : 'Unknown error'
3384
+ }
3385
+ });
3386
+ }
3387
+ },
3388
+ findSubjectById: async (subjectId)=>{
3389
+ const subject = await adapter.findOne({
3390
+ model: 'subject',
3391
+ where: [
3392
+ {
3393
+ field: 'id',
3394
+ value: subjectId
3395
+ }
3396
+ ]
3397
+ });
3398
+ return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
3399
+ },
3400
+ findSubjectByExternalId: async (externalId)=>{
3401
+ const subject = await adapter.findOne({
3402
+ model: 'subject',
3403
+ where: [
3404
+ {
3405
+ field: 'externalId',
3406
+ value: externalId
3407
+ }
3408
+ ]
3409
+ });
3410
+ return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
3411
+ },
3412
+ updateSubject: async (subjectId, data, context)=>{
3413
+ const subject = await updateWithHooks({
3414
+ data: {
3415
+ ...data,
3416
+ updatedAt: new Date()
3417
+ },
3418
+ where: [
3419
+ {
3420
+ field: 'id',
3421
+ value: subjectId
3422
+ }
3423
+ ],
3424
+ model: 'subject',
3425
+ customFn: void 0,
3426
+ context
3427
+ });
3428
+ return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
3429
+ },
3430
+ deleteSubject: async (subjectId)=>{
3431
+ await adapter.transaction({
3432
+ callback: async (tx)=>{
3433
+ await tx.update({
3434
+ model: 'subject',
3435
+ where: [
3436
+ {
3437
+ field: 'id',
3438
+ value: subjectId
3439
+ }
3440
+ ],
3441
+ update: {
3442
+ status: 'deleted',
3443
+ updatedAt: new Date()
3444
+ }
3445
+ });
3446
+ await tx.deleteMany({
3447
+ model: 'consent',
3448
+ where: [
3449
+ {
3450
+ field: 'subjectId',
3451
+ value: subjectId
3452
+ }
3453
+ ]
3454
+ });
3455
+ }
3456
+ });
3457
+ }
3458
+ };
3459
+ }
3460
+ const subjectSchema = external_zod_namespaceObject.z.object({
3461
+ id: external_zod_namespaceObject.z.string(),
3462
+ isIdentified: external_zod_namespaceObject.z.boolean().default(false),
3463
+ externalId: external_zod_namespaceObject.z.string().nullable().optional(),
3464
+ identityProvider: external_zod_namespaceObject.z.string().optional(),
3465
+ lastIpAddress: external_zod_namespaceObject.z.string().optional(),
3466
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
3467
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
3468
+ });
3469
+ function getSubjectTable(options, subjectFields) {
3470
+ const subjectConfig = options.tables?.subject;
3471
+ return {
3472
+ entityName: subjectConfig?.entityName || 'subject',
3473
+ entityPrefix: subjectConfig?.entityPrefix || 'sub',
3474
+ schema: subjectSchema,
3475
+ fields: {
3476
+ isIdentified: {
3477
+ type: 'boolean',
3478
+ defaultValue: ()=>false,
3479
+ required: true,
3480
+ fieldName: subjectConfig?.fields?.isIdentified || 'isIdentified'
3481
+ },
3482
+ externalId: {
3483
+ type: 'string',
3484
+ required: false,
3485
+ fieldName: subjectConfig?.fields?.externalId || 'externalId'
3486
+ },
3487
+ identityProvider: {
3488
+ type: 'string',
3489
+ required: false,
3490
+ fieldName: subjectConfig?.fields?.identityProvider || 'identityProvider'
3491
+ },
3492
+ lastIpAddress: {
3493
+ type: 'string',
3494
+ required: false,
3495
+ fieldName: subjectConfig?.fields?.lastIpAddress || 'lastIpAddress'
3496
+ },
3497
+ createdAt: {
3498
+ type: 'date',
3499
+ defaultValue: ()=>new Date(),
3500
+ required: true,
3501
+ fieldName: subjectConfig?.fields?.createdAt || 'createdAt'
3502
+ },
3503
+ updatedAt: {
3504
+ type: 'date',
3505
+ defaultValue: ()=>new Date(),
3506
+ required: true,
3507
+ fieldName: subjectConfig?.fields?.updatedAt || 'updatedAt'
3508
+ },
3509
+ subjectTimezone: {
3510
+ type: 'timezone',
3511
+ required: false,
3512
+ defaultValue: COMMON_TIMEZONES.UTC,
3513
+ fieldName: subjectConfig?.fields?.subjectTimezone || 'subjectTimezone'
3514
+ },
3515
+ ...subjectFields || {},
3516
+ ...subjectConfig?.additionalFields || {}
3517
+ },
3518
+ order: 1
3519
+ };
3520
+ }
3521
+ const external_kysely_namespaceObject = require("kysely");
3522
+ function dialect_getDatabaseType(db) {
3523
+ if (!db) return null;
3524
+ if ('dialect' in db) return dialect_getDatabaseType(db.dialect);
3525
+ if ('createDriver' in db) {
3526
+ if (db instanceof external_kysely_namespaceObject.SqliteDialect) return 'sqlite';
3527
+ if (db instanceof external_kysely_namespaceObject.MysqlDialect) return 'mysql';
3528
+ if (db instanceof external_kysely_namespaceObject.PostgresDialect) return 'postgres';
3529
+ if (db instanceof external_kysely_namespaceObject.MssqlDialect) return 'mssql';
3530
+ }
3531
+ if ('aggregate' in db) return 'sqlite';
3532
+ if ('getConnection' in db) return 'mysql';
3533
+ if ('connect' in db) return 'postgres';
3534
+ return null;
3535
+ }
3536
+ const dialect_createKyselyAdapter = async (config)=>{
3537
+ const db = config.database;
3538
+ if (!db) return {
3539
+ kysely: null,
3540
+ databaseType: null
3541
+ };
3542
+ if ('db' in db) {
3543
+ const kyselyConfig = db;
3544
+ return {
3545
+ kysely: kyselyConfig.db,
3546
+ databaseType: kyselyConfig.type
3547
+ };
3548
+ }
3549
+ if ('dialect' in db) {
3550
+ const dialectConfig = db;
3551
+ return {
3552
+ kysely: new external_kysely_namespaceObject.Kysely({
3553
+ dialect: dialectConfig.dialect
3554
+ }),
3555
+ databaseType: dialectConfig.type
3556
+ };
3557
+ }
3558
+ let dialect;
3559
+ const databaseType = dialect_getDatabaseType(db);
3560
+ if ('createDriver' in db) dialect = db;
3561
+ if ('aggregate' in db) dialect = new external_kysely_namespaceObject.SqliteDialect({
3562
+ database: db
3563
+ });
3564
+ if ('getConnection' in db) dialect = new external_kysely_namespaceObject.MysqlDialect({
3565
+ pool: db
3566
+ });
3567
+ if ('connect' in db) dialect = new external_kysely_namespaceObject.PostgresDialect({
3568
+ pool: db
3569
+ });
3570
+ return {
3571
+ kysely: dialect ? new external_kysely_namespaceObject.Kysely({
3572
+ dialect
3573
+ }) : null,
3574
+ databaseType
3575
+ };
3576
+ };
3577
+ function applyDefaultValue(inputValue, field, operation) {
3578
+ if ('update' === operation) return inputValue;
3579
+ if (null == inputValue && field.defaultValue) {
3580
+ if ('function' == typeof field.defaultValue) return field.defaultValue();
3581
+ return field.defaultValue;
3582
+ }
3583
+ return inputValue;
3584
+ }
3585
+ const createEntityTransformer = (db, options, config)=>{
3586
+ const schema = definition_getConsentTables(options);
3587
+ function getField(model, field) {
3588
+ if ('id' === field) return field;
3589
+ const modelFields = schema[model]?.fields;
3590
+ const f = modelFields ? modelFields[field] : void 0;
3591
+ if (!f) console.log('Field not found', model, field);
3592
+ return f?.fieldName || field;
3593
+ }
3594
+ function transformValueToDB(value, model, field) {
3595
+ if ('id' === field) return value;
3596
+ const { type = 'sqlite' } = config || {};
3597
+ const modelFields = schema[model]?.fields;
3598
+ const f = modelFields ? modelFields[field] : void 0;
3599
+ if (f?.type === 'boolean' && ('sqlite' === type || 'mssql' === type) && null != value) return value ? 1 : 0;
3600
+ if (f?.type === 'date' && value && value instanceof Date) return 'sqlite' === type ? value.toISOString() : value;
3601
+ if (f?.type === 'json' && null != value) {
3602
+ if ('postgres' === type || 'mysql' === type) return value;
3603
+ return external_superjson_default().stringify(value);
3604
+ }
3605
+ return value;
3606
+ }
3607
+ function transformValueFromDB(value, model, field) {
3608
+ const { type = 'sqlite' } = config || {};
3609
+ const modelFields = schema[model]?.fields;
3610
+ const f = modelFields ? modelFields[field] : void 0;
3611
+ if (f?.type === 'boolean' && ('sqlite' === type || 'mssql' === type) && null !== value) return 1 === value;
3612
+ if (f?.type === 'date' && value) return new Date(value);
3613
+ if (f?.type === 'json' && null != value) {
3614
+ if (('postgres' === type || 'mysql' === type) && 'object' == typeof value) return value;
3615
+ if ('string' == typeof value) try {
3616
+ return external_superjson_default().parse(value);
3617
+ } catch {
3618
+ try {
3619
+ return JSON.parse(value);
3620
+ } catch {}
3621
+ }
3622
+ }
3623
+ return value;
3624
+ }
3625
+ function getEntityName(model) {
3626
+ return schema[model].entityName;
3627
+ }
3628
+ return {
3629
+ transformInput (data, model, action) {
3630
+ const transformedData = {};
3631
+ if ('create' === action) transformedData.id = data.id || (options.advanced?.generateId ? options.advanced.generateId({
3632
+ model
3633
+ }) : generateId(schema[model].entityPrefix));
3634
+ const fields = schema[model].fields;
3635
+ for(const field in fields)if (Object.hasOwn(fields, field)) {
3636
+ const value = data[field];
3637
+ const fieldInfo = fields[field];
3638
+ const fieldName = fieldInfo?.fieldName || field;
3639
+ if (fieldInfo) transformedData[fieldName] = applyDefaultValue(transformValueToDB(value, model, field), fieldInfo, action);
3640
+ }
3641
+ return transformedData;
3642
+ },
3643
+ transformOutput (data, model, select = []) {
3644
+ if (!data) return null;
3645
+ const transformedData = {};
3646
+ if (data.id && (0 === select.length || select.includes('id'))) transformedData.id = data.id;
3647
+ const tableSchema = schema[model]?.fields;
3648
+ for(const key in tableSchema){
3649
+ if (select.length && !select.includes(key)) continue;
3650
+ const field = tableSchema[key];
3651
+ if (field) transformedData[key] = transformValueFromDB(data[field.fieldName || key], model, key);
3652
+ }
3653
+ return transformedData;
3654
+ },
3655
+ convertWhereClause (model, whereConditions) {
3656
+ if (!whereConditions || 0 === whereConditions.length) return {
3657
+ and: null,
3658
+ or: null
3659
+ };
3660
+ const conditions = {
3661
+ and: [],
3662
+ or: []
3663
+ };
3664
+ for (const condition of whereConditions){
3665
+ let { field: _field, value, operator = '=', connector = 'AND' } = condition;
3666
+ const fieldString = getField(model, _field);
3667
+ value = transformValueToDB(value, model, _field);
3668
+ const expr = (eb)=>{
3669
+ const dbField = fieldString;
3670
+ if ('in' === operator.toLowerCase()) return eb(dbField, 'in', Array.isArray(value) ? value : [
3671
+ value
3672
+ ]);
3673
+ if ('contains' === operator) return eb(dbField, 'like', `%${value}%`);
3674
+ if ('starts_with' === operator) return eb(dbField, 'like', `${value}%`);
3675
+ if ('ends_with' === operator) return eb(dbField, 'like', `%${value}`);
3676
+ if ('ilike' === operator) {
3677
+ const lowerField = eb.fn('lower', [
3678
+ dbField
3679
+ ]);
3680
+ const lowerValue = eb.fn('lower', [
3681
+ eb.val(value?.toString())
3682
+ ]);
3683
+ return eb(lowerField, 'like', lowerValue);
3684
+ }
3685
+ if ('eq' === operator) return eb(dbField, '=', value);
3686
+ if ('ne' === operator) return eb(dbField, '<>', value);
3687
+ if ('gt' === operator) return eb(dbField, '>', value);
3688
+ if ('gte' === operator) return eb(dbField, '>=', value);
3689
+ if ('lt' === operator) return eb(dbField, '<', value);
3690
+ if ('lte' === operator) return eb(dbField, '<=', value);
3691
+ return eb(dbField, operator, value);
3692
+ };
3693
+ if ('OR' === connector) conditions.or.push(expr);
3694
+ else conditions.and.push(expr);
3695
+ }
3696
+ return {
3697
+ and: conditions.and.length ? conditions.and : null,
3698
+ or: conditions.or.length ? conditions.or : null
3699
+ };
3700
+ },
3701
+ async withReturning (values, builder, model, where) {
3702
+ let res = null;
3703
+ if (config?.type === 'mysql') {
3704
+ await builder.execute();
3705
+ const whereCondition = where[0];
3706
+ const field = values.id ? 'id' : whereCondition?.field ?? 'id';
3707
+ const value = values[field] ?? whereCondition?.value;
3708
+ const fieldString = getField(model, field);
3709
+ res = await db.selectFrom(getEntityName(model)).selectAll().where((eb)=>eb(fieldString, '=', value)).executeTakeFirst();
3710
+ return res;
3711
+ }
3712
+ if (config?.type === 'mssql') {
3713
+ res = await builder.outputAll('inserted').executeTakeFirst();
3714
+ return res;
3715
+ }
3716
+ res = await builder.returningAll().executeTakeFirst();
3717
+ return res;
3718
+ },
3719
+ getEntityName,
3720
+ getField
3721
+ };
3722
+ };
3723
+ const kysely_adapter_kyselyAdapter = (db, config)=>(opts)=>{
3724
+ const { transformInput, withReturning, transformOutput, convertWhereClause, getEntityName, getField } = createEntityTransformer(db, opts, config);
3725
+ return {
3726
+ id: 'kysely',
3727
+ async create (data) {
3728
+ const { model, data: values, select } = data;
3729
+ const transformed = transformInput(values, model, 'create');
3730
+ const tableName = getEntityName(model);
3731
+ const builder = db.insertInto(tableName).values(transformed);
3732
+ const result = await withReturning(transformed, builder, model, []);
3733
+ const output = transformOutput(result, model, select);
3734
+ return output;
3735
+ },
3736
+ async findOne (data) {
3737
+ const { model, where, select } = data;
3738
+ const whereArray = Array.isArray(where) ? where : [
3739
+ where
3740
+ ];
3741
+ const { and, or } = convertWhereClause(model, whereArray);
3742
+ const tableName = getEntityName(model);
3743
+ let query = db.selectFrom(tableName).selectAll();
3744
+ if (and) query = query.where((eb)=>{
3745
+ const conditions = and.map((expr)=>expr(eb));
3746
+ return eb.and(conditions);
3747
+ });
3748
+ if (or) query = query.where((eb)=>{
3749
+ const conditions = or.map((expr)=>expr(eb));
3750
+ return eb.or(conditions);
3751
+ });
3752
+ const res = await query.executeTakeFirst();
3753
+ if (!res) return null;
3754
+ return transformOutput(res, model, select);
3755
+ },
3756
+ async findMany (data) {
3757
+ const { model, where, limit, offset, sortBy } = data;
3758
+ const whereArray = where ? Array.isArray(where) ? where : [
3759
+ where
3760
+ ] : void 0;
3761
+ const { and, or } = convertWhereClause(model, whereArray);
3762
+ const tableName = getEntityName(model);
3763
+ let query = db.selectFrom(tableName);
3764
+ if (and) query = query.where((eb)=>{
3765
+ const conditions = and.map((expr)=>expr(eb));
3766
+ return eb.and(conditions);
3767
+ });
3768
+ if (or) query = query.where((eb)=>{
3769
+ const conditions = or.map((expr)=>expr(eb));
3770
+ return eb.or(conditions);
3771
+ });
3772
+ if (config?.type === 'mssql') {
3773
+ if (!offset) query = query.top(limit || 100);
3774
+ } else query = query.limit(limit || 100);
3775
+ if (sortBy) {
3776
+ const sortFieldString = getField(model, sortBy.field);
3777
+ query = query.orderBy(sortFieldString, sortBy.direction);
3778
+ }
3779
+ if (offset) {
3780
+ if (config?.type === 'mssql') {
3781
+ if (!sortBy) query = query.orderBy('id');
3782
+ query = query.offset(offset).fetch(limit || 100);
3783
+ } else query = query.offset(offset);
3784
+ }
3785
+ const res = await query.selectAll().execute();
3786
+ if (!res) return [];
3787
+ return res.map((r)=>transformOutput(r, model));
3788
+ },
3789
+ async update (data) {
3790
+ const { model, where, update: values } = data;
3791
+ const whereArray = Array.isArray(where) ? where : [
3792
+ where
3793
+ ];
3794
+ const { and, or } = convertWhereClause(model, whereArray);
3795
+ const transformedData = transformInput(values, model, 'update');
3796
+ const tableName = getEntityName(model);
3797
+ let query = db.updateTable(tableName).set(transformedData);
3798
+ if (and) query = query.where((eb)=>{
3799
+ const conditions = and.map((expr)=>expr(eb));
3800
+ return eb.and(conditions);
3801
+ });
3802
+ if (or) query = query.where((eb)=>{
3803
+ const conditions = or.map((expr)=>expr(eb));
3804
+ return eb.or(conditions);
3805
+ });
3806
+ const result = await withReturning(transformedData, query, model, whereArray);
3807
+ return transformOutput(result, model);
3808
+ },
3809
+ async updateMany (data) {
3810
+ const { model, where, update: values } = data;
3811
+ const whereArray = Array.isArray(where) ? where : [
3812
+ where
3813
+ ];
3814
+ const { and, or } = convertWhereClause(model, whereArray);
3815
+ const transformedData = transformInput(values, model, 'update');
3816
+ const tableName = getEntityName(model);
3817
+ let query = db.updateTable(tableName).set(transformedData);
3818
+ if (and) query = query.where((eb)=>{
3819
+ const conditions = and.map((expr)=>expr(eb));
3820
+ return eb.and(conditions);
3821
+ });
3822
+ if (or) query = query.where((eb)=>{
3823
+ const conditions = or.map((expr)=>expr(eb));
3824
+ return eb.or(conditions);
3825
+ });
3826
+ await query.execute();
3827
+ let selectQuery = db.selectFrom(tableName).selectAll();
3828
+ if (and) selectQuery = selectQuery.where((eb)=>{
3829
+ const conditions = and.map((expr)=>expr(eb));
3830
+ return eb.and(conditions);
3831
+ });
3832
+ if (or) selectQuery = selectQuery.where((eb)=>{
3833
+ const conditions = or.map((expr)=>expr(eb));
3834
+ return eb.or(conditions);
3835
+ });
3836
+ const fetchedResults = await selectQuery.execute();
3837
+ if (!fetchedResults || 0 === fetchedResults.length) return [];
3838
+ return fetchedResults.map((record)=>transformOutput(record, model));
3839
+ },
3840
+ async count (data) {
3841
+ const { model, where } = data;
3842
+ const whereArray = where ? Array.isArray(where) ? where : [
3843
+ where
3844
+ ] : void 0;
3845
+ const { and, or } = convertWhereClause(model, whereArray);
3846
+ const tableName = getEntityName(model);
3847
+ let query = db.selectFrom(tableName).select((eb)=>eb.fn.count('id').as('count'));
3848
+ if (and) query = query.where((eb)=>{
3849
+ const conditions = and.map((expr)=>expr(eb));
3850
+ return eb.and(conditions);
3851
+ });
3852
+ if (or) query = query.where((eb)=>{
3853
+ const conditions = or.map((expr)=>expr(eb));
3854
+ return eb.or(conditions);
3855
+ });
3856
+ const res = await query.execute();
3857
+ const count = res[0]?.count;
3858
+ return 'number' == typeof count ? count : 0;
3859
+ },
3860
+ async delete (data) {
3861
+ const { model, where } = data;
3862
+ const whereArray = Array.isArray(where) ? where : [
3863
+ where
3864
+ ];
3865
+ const { and, or } = convertWhereClause(model, whereArray);
3866
+ const tableName = getEntityName(model);
3867
+ let query = db.deleteFrom(tableName);
3868
+ if (and) query = query.where((eb)=>{
3869
+ const conditions = and.map((expr)=>expr(eb));
3870
+ return eb.and(conditions);
3871
+ });
3872
+ if (or) query = query.where((eb)=>{
3873
+ const conditions = or.map((expr)=>expr(eb));
3874
+ return eb.or(conditions);
3875
+ });
3876
+ await query.execute();
3877
+ },
3878
+ async deleteMany (data) {
3879
+ const { model, where } = data;
3880
+ const whereArray = Array.isArray(where) ? where : [
3881
+ where
3882
+ ];
3883
+ const { and, or } = convertWhereClause(model, whereArray);
3884
+ const tableName = getEntityName(model);
3885
+ let query = db.deleteFrom(tableName);
3886
+ if (and) query = query.where((eb)=>{
3887
+ const conditions = and.map((expr)=>expr(eb));
3888
+ return eb.and(conditions);
3889
+ });
3890
+ if (or) query = query.where((eb)=>{
3891
+ const conditions = or.map((expr)=>expr(eb));
3892
+ return eb.or(conditions);
3893
+ });
3894
+ const result = await query.execute();
3895
+ const count = result.length;
3896
+ return count;
3897
+ },
3898
+ async transaction (data) {
3899
+ const { callback } = data;
3900
+ if (opts.advanced?.disableTransactions) {
3901
+ const regularAdapter = kysely_adapter_kyselyAdapter(db, config)(opts);
3902
+ return await callback(regularAdapter);
3903
+ }
3904
+ try {
3905
+ return await db.transaction().execute(async (trx)=>{
3906
+ const transactionAdapter = kysely_adapter_kyselyAdapter(trx, config)(opts);
3907
+ return await callback(transactionAdapter);
3908
+ });
3909
+ } catch (error) {
3910
+ if (error instanceof Error && (error.message.includes('transactions are not supported') || error.message.toLowerCase().includes('no transaction support'))) {
3911
+ console.warn("Warning: Database transaction failed. If your database does not support transactions, you can disable this warning by setting opts.advanced.disableTransactions to true.");
3912
+ const regularAdapter = kysely_adapter_kyselyAdapter(db, config)(opts);
3913
+ return await callback(regularAdapter);
3914
+ }
3915
+ throw error;
3916
+ }
3917
+ },
3918
+ options: config
3919
+ };
3920
+ };
3921
+ const memory_adapter_createEntityTransformer = (options)=>{
3922
+ const schema = definition_getConsentTables(options);
3923
+ function getField(model, field) {
3924
+ if ('id' === field) return field;
3925
+ const modelFields = schema[model]?.fields;
3926
+ const f = modelFields ? modelFields[field] : void 0;
3927
+ return f?.fieldName || field;
3928
+ }
3929
+ return {
3930
+ transformInput (data, model, action) {
3931
+ const transformedData = 'update' === action ? {} : {
3932
+ id: options.advanced?.generateId ? options.advanced.generateId({
3933
+ model
3934
+ }) : data.id || generateId(schema[model].entityPrefix)
3935
+ };
3936
+ const fields = schema[model].fields;
3937
+ for(const field in fields)if (Object.hasOwn(fields, field)) {
3938
+ const value = data[field];
3939
+ const fieldInfo = fields[field];
3940
+ if (void 0 === value && !fieldInfo?.defaultValue) continue;
3941
+ const fieldName = fieldInfo?.fieldName || field;
3942
+ transformedData[fieldName] = applyDefaultValue(value, fieldInfo, action);
3943
+ }
3944
+ return transformedData;
3945
+ },
3946
+ transformOutput (data, model, select = []) {
3947
+ if (!data) return null;
3948
+ const transformedData = {};
3949
+ const hasId = data.id || data._id;
3950
+ if (hasId && (0 === select.length || select.includes('id'))) transformedData.id = data.id;
3951
+ const tableSchema = schema[model].fields;
3952
+ for(const key in tableSchema){
3953
+ if (select.length && !select.includes(key)) continue;
3954
+ const field = tableSchema[key];
3955
+ if (field) transformedData[key] = data[field.fieldName || key];
3956
+ }
3957
+ return transformedData;
3958
+ },
3959
+ convertWhereClause (where, table, model) {
3960
+ return table.filter((record)=>where.every((clause)=>{
3961
+ const { field: _field, value, operator = '=' } = clause;
3962
+ const field = getField(model, _field);
3963
+ if ('in' === operator) {
3964
+ if (!Array.isArray(value)) throw new Error('Value must be an array');
3965
+ return value.includes(record[field]);
3966
+ }
3967
+ if ('contains' === operator) {
3968
+ const fieldValue = record[field];
3969
+ return 'string' == typeof fieldValue && fieldValue.includes(value);
3970
+ }
3971
+ if ('starts_with' === operator) {
3972
+ const fieldValue = record[field];
3973
+ return 'string' == typeof fieldValue && fieldValue.startsWith(value);
3974
+ }
3975
+ if ('ends_with' === operator) {
3976
+ const fieldValue = record[field];
3977
+ return 'string' == typeof fieldValue && fieldValue.endsWith(value);
3978
+ }
3979
+ if ('eq' === operator) return record[field] === value;
3980
+ if ('ne' === operator) return record[field] !== value;
3981
+ return record[field] === value;
3982
+ }));
3983
+ },
3984
+ getField
3985
+ };
3986
+ };
3987
+ const memory_adapter_memoryAdapter = (db)=>(options)=>{
3988
+ const { transformInput, transformOutput, convertWhereClause, getField } = memory_adapter_createEntityTransformer(options);
3989
+ return {
3990
+ id: 'memory',
3991
+ async create (data) {
3992
+ const { model, data: values, select } = data;
3993
+ const transformed = transformInput(values, model, 'create');
3994
+ if (!db[model]) db[model] = [];
3995
+ db[model].push(transformed);
3996
+ return transformOutput(transformed, model, select);
3997
+ },
3998
+ async findOne (data) {
3999
+ const { model, where, select } = data;
4000
+ const table = db[model] || [];
4001
+ const whereArray = Array.isArray(where) ? where : [
4002
+ where
4003
+ ];
4004
+ const res = convertWhereClause(whereArray, table, model);
4005
+ const record = res[0] || null;
4006
+ return transformOutput(record, model, select);
4007
+ },
4008
+ async findMany (data) {
4009
+ const { model, where, sortBy, limit, offset } = data;
4010
+ let table = db[model] || [];
4011
+ if (where) {
4012
+ const whereArray = Array.isArray(where) ? where : [
4013
+ where
4014
+ ];
4015
+ table = convertWhereClause(whereArray, table, model);
4016
+ }
4017
+ if (sortBy) {
4018
+ const field = getField(model, sortBy.field);
4019
+ table = [
4020
+ ...table
4021
+ ].sort((a, b)=>{
4022
+ if ('asc' === sortBy.direction) return a[field] > b[field] ? 1 : -1;
4023
+ return a[field] < b[field] ? 1 : -1;
4024
+ });
4025
+ }
4026
+ let result = table;
4027
+ if (void 0 !== offset) result = result.slice(offset);
4028
+ if (void 0 !== limit) result = result.slice(0, limit);
4029
+ return result.map((record)=>transformOutput(record, model));
4030
+ },
4031
+ async count (data) {
4032
+ const { model, where } = data;
4033
+ const table = db[model] || [];
4034
+ if (!where) return table.length;
4035
+ const whereArray = Array.isArray(where) ? where : [
4036
+ where
4037
+ ];
4038
+ const filtered = convertWhereClause(whereArray, table, model);
4039
+ return filtered.length;
4040
+ },
4041
+ async update (data) {
4042
+ const { model, where, update: values } = data;
4043
+ const table = db[model] || [];
4044
+ const whereArray = Array.isArray(where) ? where : [
4045
+ where
4046
+ ];
4047
+ const res = convertWhereClause(whereArray, table, model);
4048
+ for (const record of res)Object.assign(record, transformInput(values, model, 'update'));
4049
+ return transformOutput(res[0] || null, model);
4050
+ },
4051
+ async updateMany (data) {
4052
+ const { model, where, update: values } = data;
4053
+ const table = db[model] || [];
4054
+ const whereArray = Array.isArray(where) ? where : [
4055
+ where
4056
+ ];
4057
+ const res = convertWhereClause(whereArray, table, model);
4058
+ for (const record of res)Object.assign(record, transformInput(values, model, 'update'));
4059
+ return res.map((record)=>transformOutput(record, model));
4060
+ },
4061
+ async delete (data) {
4062
+ const { model, where } = data;
4063
+ const table = db[model] || [];
4064
+ const whereArray = Array.isArray(where) ? where : [
4065
+ where
4066
+ ];
4067
+ const res = convertWhereClause(whereArray, table, model);
4068
+ db[model] = table.filter((record)=>!res.includes(record));
4069
+ },
4070
+ async deleteMany (data) {
4071
+ const { model, where } = data;
4072
+ const table = db[model] || [];
4073
+ const whereArray = Array.isArray(where) ? where : [
4074
+ where
4075
+ ];
4076
+ const res = convertWhereClause(whereArray, table, model);
4077
+ let count = 0;
4078
+ db[model] = table.filter((record)=>{
4079
+ if (res.includes(record)) {
4080
+ count++;
4081
+ return false;
4082
+ }
4083
+ return true;
4084
+ });
4085
+ return count;
4086
+ },
4087
+ async transaction (data) {
4088
+ const { callback } = data;
4089
+ const tempDb = {};
4090
+ for(const key in db)if (Object.hasOwn(db, key)) tempDb[key] = JSON.parse(JSON.stringify(db[key]));
4091
+ const transactionAdapter = memory_adapter_memoryAdapter(tempDb)(options);
4092
+ const result = await callback(transactionAdapter);
4093
+ for(const key in tempDb)if (Object.hasOwn(tempDb, key)) db[key] = tempDb[key];
4094
+ return result;
4095
+ }
4096
+ };
4097
+ };
4098
+ const createRegistry = (ctx)=>({
4099
+ ...auditLogRegistry(ctx),
4100
+ ...consentRegistry(ctx),
4101
+ ...domainRegistry(ctx),
4102
+ ...geoLocationRegistry(ctx),
4103
+ ...consentGeoLocationRegistry(ctx),
4104
+ ...consentPurposeJunctionRegistry(ctx),
4105
+ ...consentPurposeRegistry(ctx),
4106
+ ...policyRegistry(ctx),
4107
+ ...consentRecordRegistry(ctx),
4108
+ ...subjectRegistry(ctx),
4109
+ ...consentWithdrawalRegistry(ctx)
4110
+ });
4111
+ var utils = __webpack_require__("./src/utils/index.ts");
4112
+ async function utils_getAdapter(options) {
4113
+ if (!options.database) {
4114
+ const tables = definition_getConsentTables(options);
4115
+ const memoryDB = Object.keys(tables).reduce((acc, key)=>{
4116
+ acc[key] = [];
4117
+ return acc;
4118
+ }, {});
4119
+ utils.kg.warn('No database configuration provided. Using memory adapter in development');
4120
+ return memory_adapter_memoryAdapter(memoryDB)(options);
4121
+ }
4122
+ if ('function' == typeof options.database) return options.database(options);
4123
+ const { kysely, databaseType } = await dialect_createKyselyAdapter(options);
4124
+ if (!kysely) throw new src_error.kO('Failed to initialize database adapter', {
4125
+ code: src_error.H8.INTERNAL_SERVER_ERROR,
4126
+ status: 500
4127
+ });
4128
+ return kysely_adapter_kyselyAdapter(kysely, {
4129
+ type: databaseType || 'sqlite'
4130
+ })(options);
4131
+ }
4132
+ var results = __webpack_require__("./src/error/results.ts");
4133
+ const fromC15TPromise = (promise)=>(0, src_error.p4)(promise, (error)=>({
4134
+ message: error instanceof Error ? error.message : String(error),
4135
+ code: src_error.H8.UNKNOWN_ERROR,
4136
+ name: 'C15TError',
4137
+ data: {
4138
+ error
4139
+ }
4140
+ }));
4141
+ const DEFAULT_SECRET = 'c15t-default-secret-please-change-in-production';
4142
+ const init = async (options)=>{
4143
+ try {
4144
+ const adapterResult = await fromC15TPromise(utils_getAdapter(options));
4145
+ return adapterResult.andThen((adapter)=>{
4146
+ const logger = (0, utils.hu)(options.logger);
4147
+ const baseURL = (0, utils.BS)(options.baseURL, options.basePath);
4148
+ const secret = options.secret || utils.OB.C15T_SECRET || utils.OB.CONSENT_SECRET || DEFAULT_SECRET;
4149
+ if (secret === DEFAULT_SECRET && utils.yv) logger.error('Using default secret in production. Set C15T_SECRET or pass secret in config.');
4150
+ const finalOptions = {
4151
+ ...options,
4152
+ secret,
4153
+ baseURL: baseURL ? new URL(baseURL).origin : '',
4154
+ basePath: options.basePath || '/api/c15t',
4155
+ plugins: [
4156
+ ...options.plugins || [],
4157
+ ...getInternalPlugins(options)
4158
+ ]
4159
+ };
4160
+ const generateIdFunc = ({ model, size = 16 })=>finalOptions?.advanced?.generateId?.({
4161
+ model,
4162
+ size
4163
+ }) || generateId(definition_getConsentTables(finalOptions)[model].entityPrefix);
4164
+ const registryContext = {
4165
+ adapter,
4166
+ options: finalOptions,
4167
+ logger,
4168
+ hooks: options.databaseHooks || [],
4169
+ generateId: generateIdFunc
4170
+ };
4171
+ const ctx = {
4172
+ appName: finalOptions.appName || 'c15t Consent Manager',
4173
+ options: finalOptions,
4174
+ trustedOrigins: getTrustedOrigins(finalOptions),
4175
+ baseURL: baseURL || '',
4176
+ secret,
4177
+ logger,
4178
+ generateId: generateIdFunc,
4179
+ adapter,
4180
+ registry: createRegistry(registryContext),
4181
+ tables: definition_getConsentTables(options)
4182
+ };
4183
+ return runPluginInit(ctx);
4184
+ });
4185
+ } catch (error) {
4186
+ return (0, src_error.N5)(`Failed to initialize consent system: ${error instanceof Error ? error.message : String(error)}`, {
4187
+ code: src_error.H8.INITIALIZATION_FAILED,
4188
+ data: {
4189
+ error
4190
+ }
4191
+ });
4192
+ }
4193
+ };
4194
+ function runPluginInit(ctx) {
4195
+ try {
4196
+ let options = ctx.options;
4197
+ const plugins = options.plugins || [];
4198
+ let context = ctx;
4199
+ for (const plugin of plugins)if (plugin.init) {
4200
+ const result = plugin.init(ctx);
4201
+ if ('object' == typeof result) {
4202
+ if (result.options) options = (0, external_defu_namespaceObject.defu)(result.options, options);
4203
+ if (result.context) context = {
4204
+ ...context,
4205
+ ...result.context
4206
+ };
4207
+ }
4208
+ }
4209
+ context.options = options;
4210
+ return (0, results.ok)(context);
4211
+ } catch (error) {
4212
+ return (0, results.bG)(`Plugin initialization failed: ${error instanceof Error ? error.message : String(error)}`, {
4213
+ code: src_error.H8.PLUGIN_INITIALIZATION_FAILED,
4214
+ data: {
4215
+ error
4216
+ }
4217
+ });
4218
+ }
4219
+ }
4220
+ function getInternalPlugins(_options) {
4221
+ const plugins = [];
4222
+ return plugins;
4223
+ }
4224
+ function getTrustedOrigins(options) {
4225
+ const baseURL = (0, utils.BS)(options.baseURL, options.basePath);
4226
+ if (!baseURL) return [];
4227
+ const trustedOrigins = [
4228
+ new URL(baseURL).origin
4229
+ ];
4230
+ if (options.trustedOrigins && Array.isArray(options.trustedOrigins)) trustedOrigins.push(...options.trustedOrigins);
4231
+ const envTrustedOrigins = utils.OB.C15T_TRUSTED_ORIGINS;
4232
+ if (envTrustedOrigins) trustedOrigins.push(...envTrustedOrigins.split(','));
4233
+ return trustedOrigins;
4234
+ }
4235
+ const c15tInstance = (options)=>{
4236
+ const contextPromise = init(options);
4237
+ const handler = async (request)=>{
4238
+ const contextResult = await contextPromise;
4239
+ return contextResult.asyncAndThen((ctx)=>{
4240
+ const basePath = ctx.options.basePath || '/api/c15t';
4241
+ const url = new URL(request.url);
4242
+ if (ctx.options.baseURL) {
4243
+ const baseURL = new URL(ctx.options.baseURL);
4244
+ if (!baseURL.pathname || '/' === baseURL.pathname) {
4245
+ ctx.options.baseURL = `${baseURL.origin}${basePath}`;
4246
+ ctx.baseURL = ctx.options.baseURL;
4247
+ }
4248
+ } else {
4249
+ const baseURL = (0, utils.BS)(void 0, basePath) || `${url.origin}${basePath}`;
4250
+ ctx.options.baseURL = baseURL;
4251
+ ctx.baseURL = baseURL;
4252
+ }
4253
+ let originsFromOptions = [];
4254
+ if (options.trustedOrigins) originsFromOptions = Array.isArray(options.trustedOrigins) ? options.trustedOrigins : options.trustedOrigins(request);
4255
+ ctx.trustedOrigins = [
4256
+ ...originsFromOptions,
4257
+ ctx.options.baseURL || '',
4258
+ url.origin
4259
+ ];
4260
+ try {
4261
+ const { handler } = router(ctx, options);
4262
+ return (0, src_error.i0)(handler(request), src_error.H8.REQUEST_HANDLER_ERROR);
4263
+ } catch (error) {
4264
+ const safeErrorMessage = error instanceof Error ? error.message.split('\n')[0] : 'An unknown error occurred';
4265
+ return (0, src_error.N5)(`Error processing request: ${safeErrorMessage}`, {
4266
+ code: src_error.H8.REQUEST_HANDLER_ERROR,
4267
+ status: 500,
4268
+ data: {
4269
+ url: request.url
4270
+ }
4271
+ });
4272
+ }
4273
+ });
4274
+ };
4275
+ const getApi = async ()=>{
4276
+ const contextResult = await contextPromise;
4277
+ return contextResult.asyncAndThen((context)=>{
4278
+ if (!context.baseURL) try {
4279
+ const basePath = context.options.basePath || '/api/c15t';
4280
+ const baseURL = (0, utils.BS)(context.options.baseURL, basePath);
4281
+ if (baseURL) context.baseURL = baseURL;
4282
+ } catch (error) {
4283
+ return (0, src_error.N5)(`Failed to determine base URL: ${error instanceof Error ? error.message : String(error)}`, {
4284
+ code: src_error.H8.API_RETRIEVAL_ERROR
4285
+ });
4286
+ }
4287
+ try {
4288
+ const { endpoints } = router(context, options);
4289
+ const typedEndpoints = endpoints;
4290
+ return (0, src_error.Z2)(typedEndpoints);
4291
+ } catch (error) {
4292
+ return (0, src_error.N5)(`Failed to get API endpoints: ${error instanceof Error ? error.message : String(error)}`, {
4293
+ code: src_error.H8.API_RETRIEVAL_ERROR,
4294
+ data: {
4295
+ error
4296
+ }
4297
+ });
4298
+ }
4299
+ });
4300
+ };
4301
+ return {
4302
+ handler,
4303
+ getApi,
4304
+ options,
4305
+ $context: contextPromise
4306
+ };
4307
+ };
4308
+ },
4309
+ "./src/error/codes.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4310
+ "use strict";
4311
+ __webpack_require__.d(__webpack_exports__, {
4312
+ H: ()=>BASE_ERROR_CODES,
4313
+ x: ()=>ERROR_CATEGORIES
4314
+ });
4315
+ const BASE_ERROR_CODES = {
4316
+ NOT_FOUND: 'Resource not found',
4317
+ BAD_REQUEST: 'Bad request',
4318
+ CONFLICT: 'Conflict with current state',
4319
+ CONSENT_NOT_FOUND: 'Consent not found',
4320
+ CONSENT_EXPIRED: 'Consent has expired',
4321
+ FAILED_TO_CREATE_CONSENT: 'Failed to create consent',
4322
+ FAILED_TO_UPDATE_CONSENT: 'Failed to update consent',
4323
+ FAILED_TO_GET_CONSENT: 'Failed to get consent',
4324
+ FAILED_TO_CREATE_PURPOSE: 'Failed to create consentPurpose',
4325
+ PURPOSE_NOT_FOUND: 'Consent Purpose not found',
4326
+ INVALID_CONFIGURATION: 'Invalid configuration',
4327
+ MISSING_REQUIRED_PARAMETER: 'Missing required parameter',
4328
+ UNAUTHORIZED: 'Unauthorized',
4329
+ FORBIDDEN: 'Forbidden',
4330
+ INTERNAL_SERVER_ERROR: 'Internal server error',
4331
+ INITIALIZATION_FAILED: 'Initialization failed',
4332
+ PLUGIN_INITIALIZATION_FAILED: 'Plugin initialization failed',
4333
+ DATABASE_CONNECTION_ERROR: 'Database connection error',
4334
+ DATABASE_QUERY_ERROR: 'Database query error',
4335
+ REQUEST_HANDLER_ERROR: 'Request handler error',
4336
+ API_RETRIEVAL_ERROR: 'API retrieval error',
4337
+ INVALID_REQUEST: 'Invalid request',
4338
+ UNKNOWN_ERROR: 'Unknown error'
4339
+ };
4340
+ const ERROR_CATEGORIES = {
4341
+ VALIDATION: 'validation',
4342
+ AUTHORIZATION: 'authorization',
4343
+ STORAGE: 'storage',
4344
+ NETWORK: 'network',
4345
+ PLUGIN: 'plugin',
4346
+ CONFIGURATION: 'configuration',
4347
+ UNEXPECTED: 'unexpected'
4348
+ };
4349
+ },
4350
+ "./src/error/error.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4351
+ "use strict";
4352
+ __webpack_require__.d(__webpack_exports__, {
4353
+ k: ()=>C15TError
4354
+ });
4355
+ var _codes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/error/codes.ts");
4356
+ class C15TError extends Error {
4357
+ code;
4358
+ status;
4359
+ data;
4360
+ category;
4361
+ constructor(message, options){
4362
+ super(message);
4363
+ this.name = 'C15TError';
4364
+ if (options) {
4365
+ this.code = options.code;
4366
+ this.status = options.status;
4367
+ this.data = options.data;
4368
+ this.category = options.category;
4369
+ }
4370
+ Object.setPrototypeOf(this, C15TError.prototype);
4371
+ }
4372
+ static fromResponse(response, data) {
4373
+ let message = `HTTP error ${response.status}`;
4374
+ let code;
4375
+ let errorData;
4376
+ if (data && 'object' == typeof data && null !== data) {
4377
+ const errorObj = data;
4378
+ if ('string' == typeof errorObj.message) message = errorObj.message;
4379
+ if ('string' == typeof errorObj.code) {
4380
+ const isKnownCode = Object.values(_codes__WEBPACK_IMPORTED_MODULE_0__.H).includes(errorObj.code);
4381
+ if (isKnownCode) code = errorObj.code;
4382
+ }
4383
+ if ('object' == typeof errorObj.data && null !== errorObj.data) errorData = errorObj.data;
4384
+ }
4385
+ return new C15TError(message, {
4386
+ code,
4387
+ status: response.status,
4388
+ data: errorData
4389
+ });
4390
+ }
4391
+ static isC15TError(error) {
4392
+ return error instanceof C15TError;
4393
+ }
4394
+ }
4395
+ },
4396
+ "./src/error/index.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4397
+ "use strict";
4398
+ __webpack_require__.d(__webpack_exports__, {
4399
+ H8: ()=>_codes__WEBPACK_IMPORTED_MODULE_0__.H,
4400
+ N5: ()=>_results__WEBPACK_IMPORTED_MODULE_2__.N5,
4401
+ Z2: ()=>neverthrow__WEBPACK_IMPORTED_MODULE_5__.okAsync,
4402
+ i0: ()=>_results__WEBPACK_IMPORTED_MODULE_2__.i0,
4403
+ kO: ()=>_error__WEBPACK_IMPORTED_MODULE_1__.k,
4404
+ p4: ()=>neverthrow__WEBPACK_IMPORTED_MODULE_5__.fromPromise
4405
+ });
4406
+ var _codes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/error/codes.ts");
4407
+ var _error__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/error/error.ts");
4408
+ var _results__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./src/error/results.ts");
4409
+ __webpack_require__("./src/error/recovery.ts");
4410
+ __webpack_require__("./src/error/pipeline.ts");
4411
+ var neverthrow__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("neverthrow");
4412
+ },
4413
+ "./src/error/pipeline.ts": function(__unused_webpack_module, __unused_webpack___webpack_exports__, __webpack_require__) {
4414
+ "use strict";
4415
+ __webpack_require__("./src/error/results.ts");
4416
+ },
4417
+ "./src/error/recovery.ts": function(__unused_webpack_module, __unused_webpack___webpack_exports__, __webpack_require__) {
4418
+ "use strict";
4419
+ __webpack_require__("neverthrow");
4420
+ },
4421
+ "./src/error/results.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4422
+ "use strict";
4423
+ __webpack_require__.d(__webpack_exports__, {
4424
+ N5: ()=>failAsync,
4425
+ bG: ()=>fail,
4426
+ i0: ()=>safeResultAsync,
4427
+ ok: ()=>ok
4428
+ });
4429
+ var neverthrow__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("neverthrow");
4430
+ var _codes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./src/error/codes.ts");
4431
+ var _error__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/error/error.ts");
4432
+ const ok = (value)=>(0, neverthrow__WEBPACK_IMPORTED_MODULE_0__.ok)(value);
4433
+ const fail = (message, options)=>(0, neverthrow__WEBPACK_IMPORTED_MODULE_0__.err)(new _error__WEBPACK_IMPORTED_MODULE_1__.k(message, options));
4434
+ const failAsync = (message, options)=>neverthrow__WEBPACK_IMPORTED_MODULE_0__.ResultAsync.fromSafePromise(Promise.reject(new _error__WEBPACK_IMPORTED_MODULE_1__.k(message, options)));
4435
+ const safeResultAsync = (promise, errorCode = _codes__WEBPACK_IMPORTED_MODULE_2__.H.UNKNOWN_ERROR)=>neverthrow__WEBPACK_IMPORTED_MODULE_0__.ResultAsync.fromPromise(promise, (error)=>new _error__WEBPACK_IMPORTED_MODULE_1__.k(error instanceof Error ? error.message : String(error), {
4436
+ code: errorCode,
4437
+ data: {
4438
+ originalError: error
4439
+ }
4440
+ }));
4441
+ },
4442
+ "./src/plugins/geo/index.ts": function() {},
4443
+ "./src/types/index.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4444
+ "use strict";
4445
+ __webpack_require__.r(__webpack_exports__);
4446
+ },
4447
+ "./src/utils/env.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4448
+ "use strict";
4449
+ __webpack_require__.d(__webpack_exports__, {
4450
+ OB: ()=>env,
4451
+ Y8: ()=>isTest,
4452
+ aD: ()=>nodeENV,
4453
+ yG: ()=>isDevelopment,
4454
+ yv: ()=>isProduction
4455
+ });
4456
+ const env = 'undefined' != typeof process ? process.env : {};
4457
+ const isProduction = 'undefined' != typeof process && 'production' === process.env.NODE_ENV;
4458
+ const isDevelopment = 'undefined' != typeof process && 'development' === process.env.NODE_ENV;
4459
+ function toBoolean(val) {
4460
+ return val ? 'false' !== val : false;
4461
+ }
4462
+ const nodeENV = 'undefined' != typeof process && process.env && process.env.NODE_ENV || '';
4463
+ const isTest = 'test' === nodeENV || toBoolean(env.TEST);
4464
+ },
4465
+ "./src/utils/hide-metadata.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4466
+ "use strict";
4467
+ __webpack_require__.d(__webpack_exports__, {
4468
+ a: ()=>HIDE_METADATA
4469
+ });
4470
+ const HIDE_METADATA = {
4471
+ isAction: false
4472
+ };
4473
+ },
4474
+ "./src/utils/index.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4475
+ "use strict";
4476
+ __webpack_require__.d(__webpack_exports__, {
4477
+ XF: ()=>url.XF,
4478
+ BS: ()=>url.BS,
4479
+ yG: ()=>env.yG,
4480
+ Y8: ()=>env.Y8,
4481
+ P$: ()=>url.P$,
4482
+ eU: ()=>url.eU,
4483
+ yv: ()=>env.yv,
4484
+ OB: ()=>env.OB,
4485
+ hu: ()=>logger.hu,
4486
+ rC: ()=>stringifyJson,
4487
+ Ev: ()=>url.Ev,
4488
+ kg: ()=>logger.kg,
4489
+ Mo: ()=>parseJson,
4490
+ cN: ()=>logger.cN,
4491
+ gr: ()=>logger.gr,
4492
+ aD: ()=>env.aD,
4493
+ ae: ()=>hide_metadata.a
4494
+ });
4495
+ var env = __webpack_require__("./src/utils/env.ts");
4496
+ var hide_metadata = __webpack_require__("./src/utils/hide-metadata.ts");
4497
+ var logger = __webpack_require__("./src/utils/logger.ts");
4498
+ var url = __webpack_require__("./src/utils/url.ts");
4499
+ var external_superjson_ = __webpack_require__("superjson");
4500
+ var external_superjson_default = /*#__PURE__*/ __webpack_require__.n(external_superjson_);
4501
+ function parseJson(json) {
4502
+ return external_superjson_default().parse(json);
4503
+ }
4504
+ function stringifyJson(value) {
4505
+ return external_superjson_default().stringify(value);
4506
+ }
4507
+ },
4508
+ "./src/utils/logger.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4509
+ "use strict";
4510
+ __webpack_require__.d(__webpack_exports__, {
4511
+ cN: ()=>shouldPublishLog,
4512
+ gr: ()=>levels,
4513
+ hu: ()=>createLogger,
4514
+ kg: ()=>logger
4515
+ });
4516
+ const levels = [
4517
+ 'info',
4518
+ 'success',
4519
+ 'warn',
4520
+ 'error',
4521
+ 'debug'
4522
+ ];
4523
+ function shouldPublishLog(currentLogLevel, logLevel) {
4524
+ return levels.indexOf(logLevel) <= levels.indexOf(currentLogLevel);
4525
+ }
4526
+ const colors = {
4527
+ reset: '\x1b[0m',
4528
+ bright: '\x1b[1m',
4529
+ dim: '\x1b[2m',
4530
+ underscore: '\x1b[4m',
4531
+ blink: '\x1b[5m',
4532
+ reverse: '\x1b[7m',
4533
+ hidden: '\x1b[8m',
4534
+ fg: {
4535
+ black: '\x1b[30m',
4536
+ red: '\x1b[31m',
4537
+ green: '\x1b[32m',
4538
+ yellow: '\x1b[33m',
4539
+ blue: '\x1b[34m',
4540
+ magenta: '\x1b[35m',
4541
+ cyan: '\x1b[36m',
4542
+ white: '\x1b[37m'
4543
+ },
4544
+ bg: {
4545
+ black: '\x1b[40m',
4546
+ red: '\x1b[41m',
4547
+ green: '\x1b[42m',
4548
+ yellow: '\x1b[43m',
4549
+ blue: '\x1b[44m',
4550
+ magenta: '\x1b[45m',
4551
+ cyan: '\x1b[46m',
4552
+ white: '\x1b[47m'
4553
+ }
4554
+ };
4555
+ const levelColors = {
4556
+ info: colors.fg.blue,
4557
+ success: colors.fg.green,
4558
+ warn: colors.fg.yellow,
4559
+ error: colors.fg.red,
4560
+ debug: colors.fg.magenta
4561
+ };
4562
+ const formatMessage = (level, message)=>{
4563
+ const timestamp = new Date().toISOString();
4564
+ return `${colors.dim}${timestamp}${colors.reset} ${levelColors[level]}${level.toUpperCase()}${colors.reset} ${colors.bright}[c15t]:${colors.reset} ${message}`;
4565
+ };
4566
+ const createLogger = (options)=>{
4567
+ const enabled = options?.disabled !== true;
4568
+ const logLevel = options?.level ?? 'error';
4569
+ const LogFunc = (level, message, args = [])=>{
4570
+ if (!enabled || !shouldPublishLog(logLevel, level)) return;
4571
+ const formattedMessage = formatMessage(level, message);
4572
+ if (!options || 'function' != typeof options.log) {
4573
+ if ('error' === level) console.error(formattedMessage, ...args);
4574
+ else if ('warn' === level) console.warn(formattedMessage, ...args);
4575
+ else if ('info' === level) console.log(formattedMessage, ...args);
4576
+ else if ('debug' === level) console.debug(formattedMessage, ...args);
4577
+ else if ('success' === level) console.log(formattedMessage, ...args);
4578
+ return;
4579
+ }
4580
+ options.log('success' === level ? 'info' : level, message, ...args);
4581
+ };
4582
+ return Object.fromEntries(levels.map((level)=>[
4583
+ level,
4584
+ (...[message, ...args])=>LogFunc(level, message, args)
4585
+ ]));
4586
+ };
4587
+ const logger = createLogger();
4588
+ },
4589
+ "./src/utils/url.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
4590
+ "use strict";
4591
+ __webpack_require__.d(__webpack_exports__, {
4592
+ BS: ()=>getBaseURL,
4593
+ Ev: ()=>getProtocol,
4594
+ P$: ()=>getOrigin,
4595
+ XF: ()=>getHost,
4596
+ eU: ()=>checkURLValidity
4597
+ });
4598
+ var _error__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/error/index.ts");
4599
+ var _utils_env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/utils/env.ts");
4600
+ const TRAILING_SLASHES_REGEX = /\/+$/;
4601
+ function checkHasPath(url) {
4602
+ try {
4603
+ const parsedUrl = new URL(url);
4604
+ return '/' !== parsedUrl.pathname;
4605
+ } catch {
4606
+ throw new _error__WEBPACK_IMPORTED_MODULE_0__.kO(`Invalid base URL: ${url}. Please provide a valid base URL.`, {
4607
+ code: _error__WEBPACK_IMPORTED_MODULE_0__.H8.BAD_REQUEST,
4608
+ status: 400,
4609
+ data: {
4610
+ url
4611
+ }
4612
+ });
4613
+ }
4614
+ }
4615
+ function withPath(url, path = '/api/auth') {
4616
+ const hasPath = checkHasPath(url);
4617
+ if (hasPath) return url;
4618
+ const pathWithSlash = path.startsWith('/') ? path : `/${path}`;
4619
+ return `${url.replace(TRAILING_SLASHES_REGEX, '')}${pathWithSlash}`;
4620
+ }
4621
+ function getBaseURL(url, path) {
4622
+ if (url) return withPath(url, path);
4623
+ const fromEnv = _utils_env__WEBPACK_IMPORTED_MODULE_1__.OB.C15T_URL || _utils_env__WEBPACK_IMPORTED_MODULE_1__.OB.NEXT_PUBLIC_C15T_URL || _utils_env__WEBPACK_IMPORTED_MODULE_1__.OB.PUBLIC_C15T_URL || _utils_env__WEBPACK_IMPORTED_MODULE_1__.OB.NUXT_PUBLIC_C15T_URL || _utils_env__WEBPACK_IMPORTED_MODULE_1__.OB.NUXT_PUBLIC_AUTH_URL || ('/' !== _utils_env__WEBPACK_IMPORTED_MODULE_1__.OB.BASE_URL ? _utils_env__WEBPACK_IMPORTED_MODULE_1__.OB.BASE_URL : void 0);
4624
+ if (fromEnv) return withPath(fromEnv, path);
4625
+ if ('undefined' != typeof window && window.location) return withPath(window.location.origin, path);
4626
+ }
4627
+ function getOrigin(url) {
4628
+ try {
4629
+ const parsedUrl = new URL(url);
4630
+ return parsedUrl.origin;
4631
+ } catch {
4632
+ return null;
4633
+ }
4634
+ }
4635
+ function getProtocol(url) {
4636
+ try {
4637
+ const parsedUrl = new URL(url);
4638
+ return parsedUrl.protocol;
4639
+ } catch {
4640
+ return null;
4641
+ }
4642
+ }
4643
+ const checkURLValidity = (url)=>{
4644
+ const urlPattern = url.includes('://');
4645
+ return urlPattern;
4646
+ };
4647
+ function getHost(url) {
4648
+ if (url.includes('://')) {
4649
+ const parsedUrl = new URL(url);
4650
+ return parsedUrl.host;
4651
+ }
4652
+ return url;
4653
+ }
4654
+ },
4655
+ neverthrow: function(module) {
4656
+ "use strict";
4657
+ module.exports = require("neverthrow");
4658
+ },
4659
+ superjson: function(module) {
4660
+ "use strict";
4661
+ module.exports = require("superjson");
4662
+ }
4663
+ };
4664
+ var __webpack_module_cache__ = {};
4665
+ function __webpack_require__(moduleId) {
4666
+ var cachedModule = __webpack_module_cache__[moduleId];
4667
+ if (void 0 !== cachedModule) return cachedModule.exports;
4668
+ var module = __webpack_module_cache__[moduleId] = {
4669
+ exports: {}
4670
+ };
4671
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
4672
+ return module.exports;
4673
+ }
4674
+ (()=>{
4675
+ __webpack_require__.n = (module)=>{
4676
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
4677
+ __webpack_require__.d(getter, {
4678
+ a: getter
4679
+ });
4680
+ return getter;
4681
+ };
4682
+ })();
4683
+ (()=>{
4684
+ __webpack_require__.d = (exports1, definition)=>{
4685
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
4686
+ enumerable: true,
4687
+ get: definition[key]
4688
+ });
4689
+ };
4690
+ })();
4691
+ (()=>{
4692
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
4693
+ })();
4694
+ (()=>{
4695
+ __webpack_require__.r = function(exports1) {
4696
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
4697
+ value: 'Module'
4698
+ });
4699
+ Object.defineProperty(exports1, '__esModule', {
4700
+ value: true
4701
+ });
4702
+ };
4703
+ })();
4704
+ var __webpack_exports__ = {};
4705
+ (()=>{
4706
+ "use strict";
4707
+ __webpack_require__.r(__webpack_exports__);
4708
+ __webpack_require__.d(__webpack_exports__, {
4709
+ BASE_ERROR_CODES: ()=>_error_codes__WEBPACK_IMPORTED_MODULE_1__.H,
4710
+ ClientTypes: ()=>_client_types__WEBPACK_IMPORTED_MODULE_4__,
4711
+ ERROR_CATEGORIES: ()=>_error_codes__WEBPACK_IMPORTED_MODULE_1__.x,
4712
+ HIDE_METADATA: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.ae,
4713
+ Types: ()=>_types__WEBPACK_IMPORTED_MODULE_6__,
4714
+ c15tClient: ()=>_client__WEBPACK_IMPORTED_MODULE_3__.G,
4715
+ c15tInstance: ()=>_core__WEBPACK_IMPORTED_MODULE_0__.w,
4716
+ checkURLValidity: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.eU,
4717
+ createConsentClient: ()=>_client__WEBPACK_IMPORTED_MODULE_3__.D,
4718
+ createLogger: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.hu,
4719
+ env: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.OB,
4720
+ getBaseURL: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.BS,
4721
+ getHost: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.XF,
4722
+ getOrigin: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.P$,
4723
+ getProtocol: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.Ev,
4724
+ isDevelopment: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.yG,
4725
+ isProduction: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.yv,
4726
+ isTest: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.Y8,
4727
+ levels: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.gr,
4728
+ logger: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.kg,
4729
+ nodeENV: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.aD,
4730
+ parseJson: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.Mo,
4731
+ shouldPublishLog: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.cN,
4732
+ stringifyJson: ()=>_utils__WEBPACK_IMPORTED_MODULE_2__.rC
4733
+ });
4734
+ var _core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/core.ts");
4735
+ var _error_codes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/error/codes.ts");
4736
+ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./src/utils/index.ts");
4737
+ var _client__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./src/client/index.ts");
4738
+ var _client_types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("./src/client/types.ts");
4739
+ var _plugins_geo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("./src/plugins/geo/index.ts");
4740
+ var __WEBPACK_REEXPORT_OBJECT__ = {};
4741
+ for(var __WEBPACK_IMPORT_KEY__ in _plugins_geo__WEBPACK_IMPORTED_MODULE_5__)if ([
4742
+ "HIDE_METADATA",
4743
+ "env",
4744
+ "createLogger",
4745
+ "BASE_ERROR_CODES",
4746
+ "ERROR_CATEGORIES",
4747
+ "getHost",
4748
+ "shouldPublishLog",
4749
+ "getBaseURL",
4750
+ "stringifyJson",
4751
+ "isProduction",
4752
+ "Types",
4753
+ "default",
4754
+ "nodeENV",
4755
+ "ClientTypes",
4756
+ "c15tInstance",
4757
+ "isTest",
4758
+ "checkURLValidity",
4759
+ "levels",
4760
+ "isDevelopment",
4761
+ "logger",
4762
+ "getOrigin",
4763
+ "parseJson",
4764
+ "c15tClient",
4765
+ "createConsentClient",
4766
+ "getProtocol"
4767
+ ].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = (function(key) {
4768
+ return _plugins_geo__WEBPACK_IMPORTED_MODULE_5__[key];
4769
+ }).bind(0, __WEBPACK_IMPORT_KEY__);
4770
+ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__);
4771
+ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__("./src/types/index.ts");
4772
+ })();
4773
+ var __webpack_export_target__ = exports;
4774
+ for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
4775
+ if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
4776
+ value: true
4777
+ });