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