@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
@@ -0,0 +1,2404 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE_zod__ from "zod";
2
+ import * as __WEBPACK_EXTERNAL_MODULE_superjson__ from "superjson";
3
+ import * as __WEBPACK_EXTERNAL_MODULE_base_x_aeb88370__ from "base-x";
4
+ import "node:crypto";
5
+ import "neverthrow";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_kysely__ from "kysely";
7
+ const getConsentTables = (options)=>{
8
+ const pluginSchema = options.plugins?.reduce((acc, plugin)=>{
9
+ const schema = plugin.schema;
10
+ if (!schema) return acc;
11
+ for (const [key, value] of Object.entries(schema))acc[key] = {
12
+ fields: {
13
+ ...acc[key]?.fields,
14
+ ...value.fields
15
+ },
16
+ entityName: value.entityName || key
17
+ };
18
+ return acc;
19
+ }, {});
20
+ const { subject, consentPurpose, consentPolicy, domain, geoLocation, consent, consentPurposeJunction, record, consentGeoLocation, consentWithdrawal, auditLog, ...pluginTables } = pluginSchema || {};
21
+ return {
22
+ subject: getSubjectTable(options, subject?.fields),
23
+ consentPurpose: getPurposeTable(options, consentPurpose?.fields),
24
+ consentPolicy: getConsentPolicyTable(options, consentPolicy?.fields),
25
+ domain: getDomainTable(options, domain?.fields),
26
+ consent: getConsentTable(options, consent?.fields),
27
+ consentPurposeJunction: getPurposeJunctionTable(options, consentPurposeJunction?.fields),
28
+ consentRecord: getConsentRecordTable(options, record?.fields),
29
+ consentGeoLocation: getConsentGeoLocationTable(options, consentGeoLocation?.fields),
30
+ consentWithdrawal: getConsentWithdrawalTable(options, consentWithdrawal?.fields),
31
+ auditLog: getAuditLogTable(options, auditLog?.fields),
32
+ geoLocation: getGeoLocationTable(options, geoLocation?.fields),
33
+ ...pluginTables
34
+ };
35
+ };
36
+ const auditLogSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
37
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
38
+ entityType: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
39
+ entityId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
40
+ actionType: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
41
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
42
+ ipAddress: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
43
+ userAgent: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
44
+ changes: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional(),
45
+ metadata: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional(),
46
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
47
+ });
48
+ const currentDatabaseType = 'unknown';
49
+ function getDatabaseType() {
50
+ return currentDatabaseType;
51
+ }
52
+ const fieldConfigSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
53
+ required: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
54
+ returned: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
55
+ input: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
56
+ defaultValue: __WEBPACK_EXTERNAL_MODULE_zod__.z.union([
57
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
58
+ __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
59
+ ]).optional(),
60
+ transform: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
61
+ input: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
62
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
63
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
64
+ ])).optional(),
65
+ output: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
66
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
67
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
68
+ ])).optional()
69
+ }).optional(),
70
+ validator: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
71
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
72
+ __WEBPACK_EXTERNAL_MODULE_zod__.z["null"]()
73
+ ])).optional(),
74
+ unique: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
75
+ indexed: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
76
+ sortable: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
77
+ fieldName: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
78
+ bigint: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
79
+ });
80
+ const stringFieldSchema = fieldConfigSchema.extend({
81
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string'),
82
+ minLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
83
+ maxLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
84
+ pattern: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional()
85
+ });
86
+ const numberFieldSchema = fieldConfigSchema.extend({
87
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number'),
88
+ min: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
89
+ max: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional()
90
+ });
91
+ const booleanFieldSchema = fieldConfigSchema.extend({
92
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('boolean')
93
+ });
94
+ const dateFieldSchema = fieldConfigSchema.extend({
95
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('date'),
96
+ minDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
97
+ maxDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
98
+ dateOnly: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false),
99
+ format: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional()
100
+ });
101
+ const timezoneFieldSchema = fieldConfigSchema.extend({
102
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('timezone'),
103
+ validateTimezone: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
104
+ suggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional(),
105
+ restrictToSuggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
106
+ });
107
+ const jsonFieldSchema = fieldConfigSchema.extend({
108
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('json'),
109
+ validateJson: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true)
110
+ });
111
+ const stringArrayFieldSchema = fieldConfigSchema.extend({
112
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string[]')
113
+ });
114
+ const numberArrayFieldSchema = fieldConfigSchema.extend({
115
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number[]')
116
+ });
117
+ const fieldSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.discriminatedUnion('type', [
118
+ stringFieldSchema,
119
+ numberFieldSchema,
120
+ booleanFieldSchema,
121
+ dateFieldSchema,
122
+ timezoneFieldSchema,
123
+ jsonFieldSchema,
124
+ stringArrayFieldSchema,
125
+ numberArrayFieldSchema
126
+ ]);
127
+ function validateField(field) {
128
+ return fieldSchema.parse(field);
129
+ }
130
+ const COMMON_TIMEZONES = {
131
+ UTC: 'UTC',
132
+ GMT: 'GMT',
133
+ EASTERN: 'America/New_York',
134
+ CENTRAL: 'America/Chicago',
135
+ MOUNTAIN: 'America/Denver',
136
+ PACIFIC: 'America/Los_Angeles',
137
+ LONDON: 'Europe/London',
138
+ PARIS: 'Europe/Paris',
139
+ BERLIN: 'Europe/Berlin',
140
+ TOKYO: 'Asia/Tokyo',
141
+ SHANGHAI: 'Asia/Shanghai',
142
+ SINGAPORE: 'Asia/Singapore',
143
+ SYDNEY: 'Australia/Sydney',
144
+ SAO_PAULO: 'America/Sao_Paulo'
145
+ };
146
+ function createField(type, config) {
147
+ const fieldConfig = {
148
+ type,
149
+ required: true,
150
+ returned: true,
151
+ input: true,
152
+ sortable: true,
153
+ bigint: false,
154
+ ...config
155
+ };
156
+ return validateField(fieldConfig);
157
+ }
158
+ function stringField(config = {}) {
159
+ return createField('string', config);
160
+ }
161
+ function numberField(config = {}) {
162
+ return createField('number', config);
163
+ }
164
+ function booleanField(config = {}) {
165
+ return createField('boolean', config);
166
+ }
167
+ function dateField(config = {}) {
168
+ const { transform = {}, minDate, maxDate, dateOnly = false, format, validator, ...restConfig } = config;
169
+ const originalInputTransform = transform.input;
170
+ const originalOutputTransform = transform.output;
171
+ const dbType = getDatabaseType();
172
+ const inputTransform = async (value)=>{
173
+ let transformedValue = value;
174
+ if (originalInputTransform) transformedValue = await originalInputTransform(value);
175
+ if (dateOnly && transformedValue instanceof Date) {
176
+ const dateOnlyValue = new Date(transformedValue);
177
+ dateOnlyValue.setHours(0, 0, 0, 0);
178
+ transformedValue = dateOnlyValue;
179
+ }
180
+ if ('sqlite' === dbType) return __WEBPACK_EXTERNAL_MODULE_superjson__["default"].stringify({
181
+ date: transformedValue
182
+ });
183
+ return transformedValue;
184
+ };
185
+ const outputTransform = async (value)=>{
186
+ let parsedValue = value;
187
+ if ('sqlite' === dbType && 'string' == typeof value && value.includes('"date"')) try {
188
+ const parsed = __WEBPACK_EXTERNAL_MODULE_superjson__["default"].parse(value);
189
+ parsedValue = parsed.date;
190
+ } catch {}
191
+ if (originalOutputTransform && parsedValue instanceof Date) return await originalOutputTransform(parsedValue);
192
+ if (!originalOutputTransform && format && parsedValue instanceof Date) return new Date(new Intl.DateTimeFormat(void 0, format).format(parsedValue));
193
+ return parsedValue;
194
+ };
195
+ let dateValidator = validator;
196
+ if ((minDate || maxDate) && !dateValidator) dateValidator = (value)=>{
197
+ if (!(value instanceof Date)) return 'Value must be a Date object';
198
+ if (minDate && value < minDate) return `Date must not be earlier than ${minDate.toISOString()}`;
199
+ if (maxDate && value > maxDate) return `Date must not be later than ${maxDate.toISOString()}`;
200
+ return null;
201
+ };
202
+ else if ((minDate || maxDate) && dateValidator && 'function' == typeof dateValidator) {
203
+ const originalValidator = dateValidator;
204
+ dateValidator = (value)=>{
205
+ if (!(value instanceof Date)) return 'Value must be a Date object';
206
+ if (minDate && value < minDate) return `Date must not be earlier than ${minDate.toISOString()}`;
207
+ if (maxDate && value > maxDate) return `Date must not be later than ${maxDate.toISOString()}`;
208
+ return originalValidator(value);
209
+ };
210
+ }
211
+ return createField('date', {
212
+ ...restConfig,
213
+ transform: {
214
+ input: inputTransform,
215
+ output: outputTransform
216
+ },
217
+ validator: dateValidator
218
+ });
219
+ }
220
+ function stringArrayField(config = {}) {
221
+ return createField('string[]', config);
222
+ }
223
+ function numberArrayField(config = {}) {
224
+ return createField('number[]', config);
225
+ }
226
+ const b58 = (0, __WEBPACK_EXTERNAL_MODULE_base_x_aeb88370__["default"])('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
227
+ function generateId(prefix) {
228
+ const buf = crypto.getRandomValues(new Uint8Array(20));
229
+ const EPOCH_TIMESTAMP = 1700000000000;
230
+ const t = Date.now() - EPOCH_TIMESTAMP;
231
+ const high = Math.floor(t / 0x100000000);
232
+ const low = t >>> 0;
233
+ buf[0] = high >>> 24 & 255;
234
+ buf[1] = high >>> 16 & 255;
235
+ buf[2] = high >>> 8 & 255;
236
+ buf[3] = 255 & high;
237
+ buf[4] = low >>> 24 & 255;
238
+ buf[5] = low >>> 16 & 255;
239
+ buf[6] = low >>> 8 & 255;
240
+ buf[7] = 255 & low;
241
+ return `${prefix}_${b58.encode(buf)}`;
242
+ }
243
+ function getAuditLogTable(options, auditLogFields) {
244
+ const auditLogConfig = options.tables?.auditLog;
245
+ const subjectConfig = options.tables?.subject;
246
+ return {
247
+ entityName: auditLogConfig?.entityName || 'auditLog',
248
+ entityPrefix: auditLogConfig?.entityPrefix || 'log',
249
+ schema: auditLogSchema,
250
+ fields: {
251
+ entityType: {
252
+ type: 'string',
253
+ required: true,
254
+ fieldName: auditLogConfig?.fields?.entityType || 'entityType'
255
+ },
256
+ entityId: {
257
+ type: 'string',
258
+ required: true,
259
+ fieldName: auditLogConfig?.fields?.entityId || 'entityId'
260
+ },
261
+ actionType: {
262
+ type: 'string',
263
+ required: true,
264
+ fieldName: auditLogConfig?.fields?.actionType || 'actionType'
265
+ },
266
+ subjectId: {
267
+ type: 'string',
268
+ required: false,
269
+ fieldName: auditLogConfig?.fields?.subjectId || 'subjectId',
270
+ references: {
271
+ model: subjectConfig?.entityName || 'subject',
272
+ field: 'id'
273
+ }
274
+ },
275
+ ipAddress: {
276
+ type: 'string',
277
+ required: false,
278
+ fieldName: auditLogConfig?.fields?.ipAddress || 'ipAddress'
279
+ },
280
+ userAgent: {
281
+ type: 'string',
282
+ required: false,
283
+ fieldName: auditLogConfig?.fields?.userAgent || 'userAgent'
284
+ },
285
+ changes: {
286
+ type: 'json',
287
+ required: false,
288
+ fieldName: auditLogConfig?.fields?.changes || 'changes'
289
+ },
290
+ metadata: {
291
+ type: 'json',
292
+ required: false,
293
+ fieldName: auditLogConfig?.fields?.metadata || 'metadata'
294
+ },
295
+ createdAt: {
296
+ type: 'date',
297
+ defaultValue: ()=>new Date(),
298
+ required: true,
299
+ fieldName: auditLogConfig?.fields?.createdAt || 'createdAt'
300
+ },
301
+ eventTimezone: {
302
+ type: 'timezone',
303
+ required: true,
304
+ defaultValue: COMMON_TIMEZONES.UTC,
305
+ fieldName: auditLogConfig?.fields?.eventTimezone || 'eventTimezone'
306
+ },
307
+ ...auditLogFields || {},
308
+ ...auditLogConfig?.additionalFields || {}
309
+ },
310
+ indexes: [
311
+ {
312
+ name: 'entity_index',
313
+ fields: [
314
+ 'entityType',
315
+ 'entityId'
316
+ ]
317
+ },
318
+ {
319
+ name: 'action_type_index',
320
+ fields: [
321
+ 'actionType'
322
+ ]
323
+ },
324
+ {
325
+ name: 'subject_id_index',
326
+ fields: [
327
+ 'subjectId'
328
+ ]
329
+ },
330
+ {
331
+ name: 'created_at_index',
332
+ fields: [
333
+ 'createdAt'
334
+ ]
335
+ }
336
+ ],
337
+ order: 5
338
+ };
339
+ }
340
+ const consentGeoLocationSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
341
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
342
+ consentId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
343
+ ip: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().ip(),
344
+ country: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
345
+ region: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
346
+ city: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
347
+ latitude: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().min(-90).max(90).optional(),
348
+ longitude: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().min(-180).max(180).optional(),
349
+ timezone: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().regex(/^[A-Za-z_]+\/[A-Za-z_]+$/).optional(),
350
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date()),
351
+ updatedAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
352
+ });
353
+ function getConsentGeoLocationTable(options, geoLocationFields) {
354
+ const consentGeoLocationConfig = options.tables?.consentGeoLocation;
355
+ const consentConfig = options.tables?.consent;
356
+ return {
357
+ entityName: consentGeoLocationConfig?.entityName || 'consentGeoLocation',
358
+ entityPrefix: consentGeoLocationConfig?.entityPrefix || 'cgl',
359
+ schema: consentGeoLocationSchema,
360
+ fields: {
361
+ consentId: {
362
+ type: 'string',
363
+ required: true,
364
+ fieldName: consentGeoLocationConfig?.fields?.consentId || 'consentId',
365
+ references: {
366
+ model: consentConfig?.entityName || 'consent',
367
+ field: 'id'
368
+ }
369
+ },
370
+ ip: {
371
+ type: 'string',
372
+ required: true,
373
+ fieldName: consentGeoLocationConfig?.fields?.ip || 'ip'
374
+ },
375
+ country: {
376
+ type: 'string',
377
+ required: false,
378
+ fieldName: consentGeoLocationConfig?.fields?.country || 'country'
379
+ },
380
+ region: {
381
+ type: 'string',
382
+ required: false,
383
+ fieldName: consentGeoLocationConfig?.fields?.region || 'region'
384
+ },
385
+ city: {
386
+ type: 'string',
387
+ required: false,
388
+ fieldName: consentGeoLocationConfig?.fields?.city || 'city'
389
+ },
390
+ latitude: {
391
+ type: 'number',
392
+ required: false,
393
+ fieldName: consentGeoLocationConfig?.fields?.latitude || 'latitude'
394
+ },
395
+ longitude: {
396
+ type: 'number',
397
+ required: false,
398
+ fieldName: consentGeoLocationConfig?.fields?.longitude || 'longitude'
399
+ },
400
+ timezone: {
401
+ type: 'string',
402
+ required: false,
403
+ fieldName: consentGeoLocationConfig?.fields?.timezone || 'timezone'
404
+ },
405
+ createdAt: {
406
+ type: 'date',
407
+ defaultValue: ()=>new Date(),
408
+ required: true,
409
+ fieldName: consentGeoLocationConfig?.fields?.createdAt || 'createdAt'
410
+ },
411
+ ...geoLocationFields || {},
412
+ ...consentGeoLocationConfig?.additionalFields || {}
413
+ },
414
+ indexes: [
415
+ {
416
+ name: 'consent_id_index',
417
+ fields: [
418
+ 'consentId'
419
+ ]
420
+ },
421
+ {
422
+ name: 'country_index',
423
+ fields: [
424
+ 'country'
425
+ ]
426
+ },
427
+ {
428
+ name: 'created_at_index',
429
+ fields: [
430
+ 'createdAt'
431
+ ]
432
+ }
433
+ ],
434
+ order: 4
435
+ };
436
+ }
437
+ const consentPolicySchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
438
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
439
+ version: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
440
+ name: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
441
+ effectiveDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date(),
442
+ expirationDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().nullable().optional(),
443
+ content: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
444
+ contentHash: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
445
+ isActive: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
446
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date()),
447
+ updatedAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
448
+ });
449
+ function getConsentPolicyTable(options, policyFields) {
450
+ const consentPolicyConfig = options.tables?.consentPolicy;
451
+ return {
452
+ entityName: consentPolicyConfig?.entityName || 'consentPolicy',
453
+ entityPrefix: consentPolicyConfig?.entityPrefix || 'pol',
454
+ schema: consentPolicySchema,
455
+ fields: {
456
+ version: {
457
+ type: 'string',
458
+ required: true,
459
+ fieldName: consentPolicyConfig?.fields?.version || 'version'
460
+ },
461
+ name: {
462
+ type: 'string',
463
+ required: true,
464
+ fieldName: consentPolicyConfig?.fields?.name || 'name'
465
+ },
466
+ effectiveDate: {
467
+ type: 'date',
468
+ required: true,
469
+ fieldName: consentPolicyConfig?.fields?.effectiveDate || 'effectiveDate'
470
+ },
471
+ expirationDate: {
472
+ type: 'date',
473
+ required: false,
474
+ fieldName: consentPolicyConfig?.fields?.expirationDate || 'expirationDate'
475
+ },
476
+ content: {
477
+ type: 'string',
478
+ required: true,
479
+ fieldName: consentPolicyConfig?.fields?.content || 'content'
480
+ },
481
+ contentHash: {
482
+ type: 'string',
483
+ required: true,
484
+ fieldName: consentPolicyConfig?.fields?.contentHash || 'contentHash'
485
+ },
486
+ isActive: {
487
+ type: 'boolean',
488
+ defaultValue: true,
489
+ required: true,
490
+ fieldName: consentPolicyConfig?.fields?.isActive || 'isActive'
491
+ },
492
+ createdAt: {
493
+ type: 'date',
494
+ defaultValue: ()=>new Date(),
495
+ required: true,
496
+ fieldName: consentPolicyConfig?.fields?.createdAt || 'createdAt'
497
+ },
498
+ ...policyFields || {},
499
+ ...consentPolicyConfig?.additionalFields || {}
500
+ },
501
+ order: 2
502
+ };
503
+ }
504
+ const consentPurposeJunctionSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
505
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
506
+ consentId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
507
+ consentPurposeId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
508
+ status: __WEBPACK_EXTERNAL_MODULE_zod__.z["enum"]([
509
+ 'active',
510
+ 'withdrawn'
511
+ ], {
512
+ errorMap: ()=>({
513
+ message: "Status must be either 'active' or 'withdrawn'"
514
+ })
515
+ }).default('active'),
516
+ metadata: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
517
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
518
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.number(),
519
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean()
520
+ ])).optional(),
521
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date()),
522
+ updatedAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
523
+ });
524
+ function getPurposeJunctionTable(options, junctionFields) {
525
+ const purposeJunctionConfig = options.tables?.consentPurposeJunction;
526
+ const consentConfig = options.tables?.consent;
527
+ const purposeConfig = options.tables?.consentPurpose;
528
+ return {
529
+ entityName: purposeJunctionConfig?.entityName || 'consentPurposeJunction',
530
+ entityPrefix: purposeJunctionConfig?.entityPrefix || 'pjx',
531
+ schema: consentPurposeJunctionSchema,
532
+ fields: {
533
+ consentId: {
534
+ type: 'string',
535
+ required: true,
536
+ fieldName: purposeJunctionConfig?.fields?.consentId || 'consentId',
537
+ references: {
538
+ model: consentConfig?.entityName || 'consent',
539
+ field: 'id'
540
+ }
541
+ },
542
+ purposeId: {
543
+ type: 'string',
544
+ required: true,
545
+ fieldName: purposeJunctionConfig?.fields?.purposeId || 'purposeId',
546
+ references: {
547
+ model: purposeConfig?.entityName || 'consentPurpose',
548
+ field: 'id'
549
+ }
550
+ },
551
+ status: {
552
+ type: 'string',
553
+ defaultValue: ()=>'active',
554
+ required: true,
555
+ fieldName: purposeJunctionConfig?.fields?.status || 'status'
556
+ },
557
+ metadata: {
558
+ type: 'json',
559
+ required: false,
560
+ fieldName: purposeJunctionConfig?.fields?.metadata || 'metadata'
561
+ },
562
+ createdAt: {
563
+ type: 'date',
564
+ defaultValue: ()=>new Date(),
565
+ required: true,
566
+ fieldName: purposeJunctionConfig?.fields?.createdAt || 'createdAt'
567
+ },
568
+ updatedAt: {
569
+ type: 'date',
570
+ required: false,
571
+ fieldName: purposeJunctionConfig?.fields?.updatedAt || 'updatedAt'
572
+ },
573
+ ...junctionFields || {},
574
+ ...purposeJunctionConfig?.additionalFields || {}
575
+ },
576
+ uniqueConstraints: [
577
+ {
578
+ name: 'unique_consent_purpose',
579
+ fields: [
580
+ 'consentId',
581
+ 'purposeId'
582
+ ]
583
+ }
584
+ ],
585
+ order: 4
586
+ };
587
+ }
588
+ const purposeSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
589
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
590
+ code: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
591
+ name: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
592
+ description: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
593
+ isEssential: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false),
594
+ dataCategory: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
595
+ legalBasis: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
596
+ isActive: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
597
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date()),
598
+ updatedAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
599
+ });
600
+ function getPurposeTable(options, purposeFields) {
601
+ const purposeConfig = options.tables?.consentPurpose;
602
+ return {
603
+ entityName: purposeConfig?.entityName || 'consentPurpose',
604
+ entityPrefix: purposeConfig?.entityPrefix || 'pur',
605
+ schema: purposeSchema,
606
+ fields: {
607
+ code: {
608
+ type: 'string',
609
+ required: true,
610
+ fieldName: purposeConfig?.fields?.code || 'code'
611
+ },
612
+ name: {
613
+ type: 'string',
614
+ required: true,
615
+ fieldName: purposeConfig?.fields?.name || 'name'
616
+ },
617
+ description: {
618
+ type: 'string',
619
+ required: true,
620
+ fieldName: purposeConfig?.fields?.description || "description"
621
+ },
622
+ isEssential: {
623
+ type: 'boolean',
624
+ defaultValue: ()=>false,
625
+ required: true,
626
+ fieldName: purposeConfig?.fields?.isEssential || 'isEssential'
627
+ },
628
+ dataCategory: {
629
+ type: 'string',
630
+ required: false,
631
+ fieldName: purposeConfig?.fields?.dataCategory || 'dataCategory'
632
+ },
633
+ legalBasis: {
634
+ type: 'string',
635
+ required: false,
636
+ fieldName: purposeConfig?.fields?.legalBasis || 'legalBasis'
637
+ },
638
+ isActive: {
639
+ type: 'boolean',
640
+ defaultValue: true,
641
+ required: true,
642
+ fieldName: purposeConfig?.fields?.isActive || 'isActive'
643
+ },
644
+ createdAt: {
645
+ type: 'date',
646
+ defaultValue: ()=>new Date(),
647
+ required: true,
648
+ fieldName: purposeConfig?.fields?.createdAt || 'createdAt'
649
+ },
650
+ updatedAt: {
651
+ type: 'date',
652
+ defaultValue: ()=>new Date(),
653
+ required: true,
654
+ fieldName: purposeConfig?.fields?.updatedAt || 'updatedAt'
655
+ },
656
+ ...purposeFields || {},
657
+ ...purposeConfig?.additionalFields || {}
658
+ },
659
+ order: 1
660
+ };
661
+ }
662
+ const consentRecordSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
663
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
664
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
665
+ consentId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
666
+ actionType: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
667
+ details: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional(),
668
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date()),
669
+ updatedAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
670
+ });
671
+ function getConsentRecordTable(options, recordFields) {
672
+ const recordConfig = options.tables?.record;
673
+ const subjectConfig = options.tables?.subject;
674
+ const consentConfig = options.tables?.consent;
675
+ return {
676
+ entityName: recordConfig?.entityName || 'consentRecord',
677
+ entityPrefix: recordConfig?.entityPrefix || 'rec',
678
+ schema: consentRecordSchema,
679
+ fields: {
680
+ subjectId: {
681
+ type: 'string',
682
+ required: true,
683
+ fieldName: recordConfig?.fields?.subjectId || 'subjectId',
684
+ references: {
685
+ model: subjectConfig?.entityName || 'subject',
686
+ field: 'id'
687
+ }
688
+ },
689
+ consentId: {
690
+ type: 'string',
691
+ required: false,
692
+ fieldName: recordConfig?.fields?.consentId || 'consentId',
693
+ references: {
694
+ model: consentConfig?.entityName || 'consent',
695
+ field: 'id'
696
+ }
697
+ },
698
+ actionType: {
699
+ type: 'string',
700
+ required: true,
701
+ fieldName: recordConfig?.fields?.actionType || 'actionType'
702
+ },
703
+ details: {
704
+ type: 'json',
705
+ required: false,
706
+ fieldName: recordConfig?.fields?.details || 'details'
707
+ },
708
+ createdAt: {
709
+ type: 'date',
710
+ defaultValue: ()=>new Date(),
711
+ required: true,
712
+ fieldName: recordConfig?.fields?.createdAt || 'createdAt'
713
+ },
714
+ ...recordFields || {},
715
+ ...recordConfig?.additionalFields || {}
716
+ },
717
+ order: 4
718
+ };
719
+ }
720
+ const consentWithdrawalSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
721
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
722
+ consentId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
723
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
724
+ withdrawalReason: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
725
+ withdrawalMethod: __WEBPACK_EXTERNAL_MODULE_zod__.z["enum"]([
726
+ 'subject-initiated',
727
+ 'automatic-expiry',
728
+ 'admin',
729
+ 'api',
730
+ 'other'
731
+ ]).default('subject-initiated'),
732
+ ipAddress: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
733
+ userAgent: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
734
+ metadata: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional(),
735
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date()),
736
+ updatedAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
737
+ });
738
+ function getConsentWithdrawalTable(options, withdrawalFields) {
739
+ const consentWithdrawalConfig = options.tables?.consentWithdrawal;
740
+ const consentConfig = options.tables?.consent;
741
+ const subjectConfig = options.tables?.subject;
742
+ return {
743
+ entityName: consentWithdrawalConfig?.entityName || 'consentWithdrawal',
744
+ entityPrefix: consentWithdrawalConfig?.entityPrefix || 'wdr',
745
+ schema: consentWithdrawalSchema,
746
+ fields: {
747
+ consentId: {
748
+ type: 'string',
749
+ required: true,
750
+ fieldName: consentWithdrawalConfig?.fields?.consentId || 'consentId',
751
+ references: {
752
+ model: consentConfig?.entityName || 'consent',
753
+ field: 'id'
754
+ }
755
+ },
756
+ subjectId: {
757
+ type: 'string',
758
+ required: true,
759
+ fieldName: consentWithdrawalConfig?.fields?.subjectId || 'subjectId',
760
+ references: {
761
+ model: subjectConfig?.entityName || 'subject',
762
+ field: 'id'
763
+ }
764
+ },
765
+ withdrawalReason: {
766
+ type: 'string',
767
+ required: false,
768
+ fieldName: consentWithdrawalConfig?.fields?.withdrawalReason || 'withdrawalReason'
769
+ },
770
+ withdrawalMethod: {
771
+ type: 'string',
772
+ defaultValue: ()=>'subject-initiated',
773
+ required: true,
774
+ fieldName: consentWithdrawalConfig?.fields?.withdrawalMethod || 'withdrawalMethod'
775
+ },
776
+ ipAddress: {
777
+ type: 'string',
778
+ required: false,
779
+ fieldName: consentWithdrawalConfig?.fields?.ipAddress || 'ipAddress'
780
+ },
781
+ userAgent: {
782
+ type: 'string',
783
+ required: false,
784
+ fieldName: consentWithdrawalConfig?.fields?.userAgent || 'userAgent'
785
+ },
786
+ metadata: {
787
+ type: 'json',
788
+ required: false,
789
+ fieldName: consentWithdrawalConfig?.fields?.metadata || 'metadata'
790
+ },
791
+ createdAt: {
792
+ type: 'date',
793
+ defaultValue: ()=>new Date(),
794
+ required: true,
795
+ fieldName: consentWithdrawalConfig?.fields?.createdAt || 'createdAt'
796
+ },
797
+ ...withdrawalFields || {},
798
+ ...consentWithdrawalConfig?.additionalFields || {}
799
+ },
800
+ uniqueConstraints: consentWithdrawalConfig?.preventMultipleWithdrawals !== false ? [
801
+ {
802
+ name: 'unique_consent_withdrawal',
803
+ fields: [
804
+ 'consentId'
805
+ ]
806
+ }
807
+ ] : [],
808
+ indexes: [
809
+ {
810
+ name: 'subject_id_index',
811
+ fields: [
812
+ 'subjectId'
813
+ ]
814
+ },
815
+ {
816
+ name: 'created_at_index',
817
+ fields: [
818
+ 'createdAt'
819
+ ]
820
+ }
821
+ ],
822
+ order: 4
823
+ };
824
+ }
825
+ const consentHistorySchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
826
+ actionType: __WEBPACK_EXTERNAL_MODULE_zod__.z["enum"]([
827
+ 'given',
828
+ 'withdrawn',
829
+ 'updated',
830
+ 'expired'
831
+ ]),
832
+ timestamp: __WEBPACK_EXTERNAL_MODULE_zod__.z.date(),
833
+ details: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional(),
834
+ previousState: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional(),
835
+ newState: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional()
836
+ });
837
+ const consentSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
838
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
839
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
840
+ domainId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
841
+ purposeIds: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()),
842
+ metadata: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional(),
843
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
844
+ ipAddress: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
845
+ userAgent: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
846
+ status: __WEBPACK_EXTERNAL_MODULE_zod__.z["enum"]([
847
+ 'active',
848
+ 'withdrawn',
849
+ 'expired'
850
+ ]).default('active'),
851
+ withdrawalReason: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
852
+ givenAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date()),
853
+ validUntil: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
854
+ isActive: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
855
+ history: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(consentHistorySchema).default([])
856
+ });
857
+ function getConsentTable(options, consentFields) {
858
+ const consentConfig = options.tables?.consent;
859
+ const subjectConfig = options.tables?.subject;
860
+ const domainConfig = options.tables?.domain;
861
+ const policyConfig = options.tables?.consentPolicy;
862
+ const purposeConfig = options.tables?.consentPurpose;
863
+ return {
864
+ entityName: consentConfig?.entityName || 'consent',
865
+ entityPrefix: consentConfig?.entityPrefix || 'cns',
866
+ schema: consentSchema,
867
+ fields: {
868
+ subjectId: {
869
+ type: 'string',
870
+ required: true,
871
+ fieldName: consentConfig?.fields?.subjectId || 'subjectId',
872
+ references: {
873
+ model: subjectConfig?.entityName || 'subject',
874
+ field: 'id'
875
+ }
876
+ },
877
+ domainId: {
878
+ type: 'string',
879
+ required: true,
880
+ fieldName: consentConfig?.fields?.domainId || 'domainId',
881
+ references: {
882
+ model: domainConfig?.entityName || 'domain',
883
+ field: 'id'
884
+ }
885
+ },
886
+ purposeIds: {
887
+ type: 'json',
888
+ required: false,
889
+ fieldName: consentConfig?.fields?.purposeIds || 'purposeIds',
890
+ references: {
891
+ model: purposeConfig?.entityName || 'consentPurpose',
892
+ field: 'id',
893
+ type: 'array'
894
+ }
895
+ },
896
+ metadata: {
897
+ type: 'json',
898
+ required: false,
899
+ fieldName: consentConfig?.fields?.metadata || 'metadata'
900
+ },
901
+ policyId: {
902
+ type: 'string',
903
+ required: false,
904
+ fieldName: consentConfig?.fields?.policyId || 'policyId',
905
+ references: {
906
+ model: policyConfig?.entityName || 'consentPolicy',
907
+ field: 'id'
908
+ }
909
+ },
910
+ ipAddress: {
911
+ type: 'string',
912
+ required: false,
913
+ fieldName: consentConfig?.fields?.ipAddress || 'ipAddress'
914
+ },
915
+ userAgent: {
916
+ type: 'string',
917
+ required: false,
918
+ fieldName: consentConfig?.fields?.userAgent || 'userAgent'
919
+ },
920
+ status: {
921
+ type: 'string',
922
+ defaultValue: ()=>'active',
923
+ required: true,
924
+ fieldName: consentConfig?.fields?.status || 'status'
925
+ },
926
+ withdrawalReason: {
927
+ type: 'string',
928
+ required: false,
929
+ fieldName: consentConfig?.fields?.withdrawalReason || 'withdrawalReason'
930
+ },
931
+ givenAt: {
932
+ type: 'date',
933
+ defaultValue: ()=>new Date(),
934
+ required: true,
935
+ fieldName: consentConfig?.fields?.givenAt || 'givenAt'
936
+ },
937
+ validUntil: {
938
+ type: 'date',
939
+ required: false,
940
+ fieldName: consentConfig?.fields?.validUntil || 'validUntil',
941
+ transform: {
942
+ input: (val, data)=>{
943
+ if (val) return val;
944
+ const expiresIn = consentConfig?.expiresIn || 31536000;
945
+ const givenAt = data.givenAt instanceof Date ? data.givenAt : new Date();
946
+ if (expiresIn > 0) {
947
+ const validUntil = new Date(givenAt);
948
+ validUntil.setSeconds(validUntil.getSeconds() + expiresIn);
949
+ return validUntil;
950
+ }
951
+ }
952
+ }
953
+ },
954
+ isActive: {
955
+ type: 'boolean',
956
+ defaultValue: true,
957
+ required: true,
958
+ fieldName: consentConfig?.fields?.isActive || 'isActive'
959
+ },
960
+ ...consentFields || {},
961
+ ...consentConfig?.additionalFields || {}
962
+ },
963
+ order: 3
964
+ };
965
+ }
966
+ const codes_BASE_ERROR_CODES = {
967
+ NOT_FOUND: 'Resource not found',
968
+ BAD_REQUEST: 'Bad request',
969
+ CONFLICT: 'Conflict with current state',
970
+ CONSENT_NOT_FOUND: 'Consent not found',
971
+ CONSENT_EXPIRED: 'Consent has expired',
972
+ FAILED_TO_CREATE_CONSENT: 'Failed to create consent',
973
+ FAILED_TO_UPDATE_CONSENT: 'Failed to update consent',
974
+ FAILED_TO_GET_CONSENT: 'Failed to get consent',
975
+ FAILED_TO_CREATE_PURPOSE: 'Failed to create consentPurpose',
976
+ PURPOSE_NOT_FOUND: 'Consent Purpose not found',
977
+ INVALID_CONFIGURATION: 'Invalid configuration',
978
+ MISSING_REQUIRED_PARAMETER: 'Missing required parameter',
979
+ UNAUTHORIZED: 'Unauthorized',
980
+ FORBIDDEN: 'Forbidden',
981
+ INTERNAL_SERVER_ERROR: 'Internal server error',
982
+ INITIALIZATION_FAILED: 'Initialization failed',
983
+ PLUGIN_INITIALIZATION_FAILED: 'Plugin initialization failed',
984
+ DATABASE_CONNECTION_ERROR: 'Database connection error',
985
+ DATABASE_QUERY_ERROR: 'Database query error',
986
+ REQUEST_HANDLER_ERROR: 'Request handler error',
987
+ API_RETRIEVAL_ERROR: 'API retrieval error',
988
+ INVALID_REQUEST: 'Invalid request',
989
+ UNKNOWN_ERROR: 'Unknown error'
990
+ };
991
+ class error_C15TError extends Error {
992
+ code;
993
+ status;
994
+ data;
995
+ category;
996
+ constructor(message, options){
997
+ super(message);
998
+ this.name = 'C15TError';
999
+ if (options) {
1000
+ this.code = options.code;
1001
+ this.status = options.status;
1002
+ this.data = options.data;
1003
+ this.category = options.category;
1004
+ }
1005
+ Object.setPrototypeOf(this, error_C15TError.prototype);
1006
+ }
1007
+ static fromResponse(response, data) {
1008
+ let message = `HTTP error ${response.status}`;
1009
+ let code;
1010
+ let errorData;
1011
+ if (data && 'object' == typeof data && null !== data) {
1012
+ const errorObj = data;
1013
+ if ('string' == typeof errorObj.message) message = errorObj.message;
1014
+ if ('string' == typeof errorObj.code) {
1015
+ const isKnownCode = Object.values(codes_BASE_ERROR_CODES).includes(errorObj.code);
1016
+ if (isKnownCode) code = errorObj.code;
1017
+ }
1018
+ if ('object' == typeof errorObj.data && null !== errorObj.data) errorData = errorObj.data;
1019
+ }
1020
+ return new error_C15TError(message, {
1021
+ code,
1022
+ status: response.status,
1023
+ data: errorData
1024
+ });
1025
+ }
1026
+ static isC15TError(error) {
1027
+ return error instanceof error_C15TError;
1028
+ }
1029
+ }
1030
+ const domainSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
1031
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
1032
+ name: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().min(1),
1033
+ description: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
1034
+ allowedOrigins: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional().default([]),
1035
+ isVerified: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
1036
+ isActive: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
1037
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date()),
1038
+ updatedAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
1039
+ });
1040
+ function getDomainTable(options, domainFields) {
1041
+ const domainConfig = options.tables?.domain;
1042
+ return {
1043
+ entityName: domainConfig?.entityName || 'domain',
1044
+ entityPrefix: domainConfig?.entityPrefix || 'dom',
1045
+ schema: domainSchema,
1046
+ fields: {
1047
+ name: {
1048
+ type: 'string',
1049
+ required: true,
1050
+ unique: true,
1051
+ fieldName: domainConfig?.fields?.name || 'name'
1052
+ },
1053
+ description: {
1054
+ type: 'string',
1055
+ required: false,
1056
+ fieldName: domainConfig?.fields?.description || "description"
1057
+ },
1058
+ allowedOrigins: {
1059
+ type: 'json',
1060
+ defaultValue: ()=>[],
1061
+ required: false,
1062
+ fieldName: domainConfig?.fields?.allowedOrigins || 'allowedOrigins'
1063
+ },
1064
+ isVerified: {
1065
+ type: 'boolean',
1066
+ defaultValue: true,
1067
+ required: true,
1068
+ fieldName: domainConfig?.fields?.isVerified || 'isVerified'
1069
+ },
1070
+ isActive: {
1071
+ type: 'boolean',
1072
+ defaultValue: true,
1073
+ required: true,
1074
+ fieldName: domainConfig?.fields?.isActive || 'isActive'
1075
+ },
1076
+ createdAt: {
1077
+ type: 'date',
1078
+ defaultValue: ()=>new Date(),
1079
+ required: true,
1080
+ fieldName: domainConfig?.fields?.createdAt || 'createdAt'
1081
+ },
1082
+ updatedAt: {
1083
+ type: 'date',
1084
+ required: false,
1085
+ fieldName: domainConfig?.fields?.updatedAt || 'updatedAt'
1086
+ },
1087
+ ...domainFields || {},
1088
+ ...domainConfig?.additionalFields || {}
1089
+ },
1090
+ order: 1
1091
+ };
1092
+ }
1093
+ const geoLocationSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
1094
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
1095
+ countryCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().length(2).toUpperCase(),
1096
+ countryName: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
1097
+ regionCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
1098
+ regionName: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
1099
+ regulatoryZones: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z["enum"]([
1100
+ 'GDPR',
1101
+ 'CCPA',
1102
+ 'CPRA',
1103
+ 'LGPD',
1104
+ 'PIPEDA'
1105
+ ])).optional(),
1106
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
1107
+ });
1108
+ function getGeoLocationTable(options, geoLocationFields) {
1109
+ const geoLocationConfig = options.tables?.geoLocation;
1110
+ return {
1111
+ entityName: geoLocationConfig?.entityName || 'geoLocation',
1112
+ entityPrefix: geoLocationConfig?.entityPrefix || 'geo',
1113
+ schema: geoLocationSchema,
1114
+ fields: {
1115
+ countryCode: {
1116
+ type: 'string',
1117
+ required: true,
1118
+ fieldName: geoLocationConfig?.fields?.countryCode || 'countryCode'
1119
+ },
1120
+ countryName: {
1121
+ type: 'string',
1122
+ required: true,
1123
+ fieldName: geoLocationConfig?.fields?.countryName || 'countryName'
1124
+ },
1125
+ regionCode: {
1126
+ type: 'string',
1127
+ required: false,
1128
+ fieldName: geoLocationConfig?.fields?.regionCode || 'regionCode'
1129
+ },
1130
+ regionName: {
1131
+ type: 'string',
1132
+ required: false,
1133
+ fieldName: geoLocationConfig?.fields?.regionName || 'regionName'
1134
+ },
1135
+ regulatoryZones: {
1136
+ type: 'json',
1137
+ required: false,
1138
+ fieldName: geoLocationConfig?.fields?.regulatoryZones || 'regulatoryZones',
1139
+ transformer: {
1140
+ input: (value)=>JSON.stringify(value),
1141
+ output: (value)=>{
1142
+ try {
1143
+ return JSON.parse(value);
1144
+ } catch {
1145
+ return [];
1146
+ }
1147
+ }
1148
+ }
1149
+ },
1150
+ createdAt: {
1151
+ type: 'date',
1152
+ defaultValue: ()=>new Date(),
1153
+ required: true,
1154
+ fieldName: geoLocationConfig?.fields?.createdAt || 'createdAt'
1155
+ },
1156
+ ...geoLocationFields || {},
1157
+ ...geoLocationConfig?.additionalFields || {}
1158
+ },
1159
+ indexes: [
1160
+ {
1161
+ name: 'country_code_index',
1162
+ fields: [
1163
+ 'countryCode'
1164
+ ]
1165
+ },
1166
+ {
1167
+ name: 'region_code_index',
1168
+ fields: [
1169
+ 'regionCode'
1170
+ ]
1171
+ },
1172
+ {
1173
+ name: 'created_at_index',
1174
+ fields: [
1175
+ 'createdAt'
1176
+ ]
1177
+ }
1178
+ ],
1179
+ order: 1
1180
+ };
1181
+ }
1182
+ const subjectSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
1183
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
1184
+ isIdentified: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false),
1185
+ externalId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable().optional(),
1186
+ identityProvider: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
1187
+ lastIpAddress: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
1188
+ createdAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date()),
1189
+ updatedAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().default(()=>new Date())
1190
+ });
1191
+ function getSubjectTable(options, subjectFields) {
1192
+ const subjectConfig = options.tables?.subject;
1193
+ return {
1194
+ entityName: subjectConfig?.entityName || 'subject',
1195
+ entityPrefix: subjectConfig?.entityPrefix || 'sub',
1196
+ schema: subjectSchema,
1197
+ fields: {
1198
+ isIdentified: {
1199
+ type: 'boolean',
1200
+ defaultValue: ()=>false,
1201
+ required: true,
1202
+ fieldName: subjectConfig?.fields?.isIdentified || 'isIdentified'
1203
+ },
1204
+ externalId: {
1205
+ type: 'string',
1206
+ required: false,
1207
+ fieldName: subjectConfig?.fields?.externalId || 'externalId'
1208
+ },
1209
+ identityProvider: {
1210
+ type: 'string',
1211
+ required: false,
1212
+ fieldName: subjectConfig?.fields?.identityProvider || 'identityProvider'
1213
+ },
1214
+ lastIpAddress: {
1215
+ type: 'string',
1216
+ required: false,
1217
+ fieldName: subjectConfig?.fields?.lastIpAddress || 'lastIpAddress'
1218
+ },
1219
+ createdAt: {
1220
+ type: 'date',
1221
+ defaultValue: ()=>new Date(),
1222
+ required: true,
1223
+ fieldName: subjectConfig?.fields?.createdAt || 'createdAt'
1224
+ },
1225
+ updatedAt: {
1226
+ type: 'date',
1227
+ defaultValue: ()=>new Date(),
1228
+ required: true,
1229
+ fieldName: subjectConfig?.fields?.updatedAt || 'updatedAt'
1230
+ },
1231
+ subjectTimezone: {
1232
+ type: 'timezone',
1233
+ required: false,
1234
+ defaultValue: COMMON_TIMEZONES.UTC,
1235
+ fieldName: subjectConfig?.fields?.subjectTimezone || 'subjectTimezone'
1236
+ },
1237
+ ...subjectFields || {},
1238
+ ...subjectConfig?.additionalFields || {}
1239
+ },
1240
+ order: 1
1241
+ };
1242
+ }
1243
+ function parseEntityOutputData(data, schema) {
1244
+ const fields = schema.fields;
1245
+ const parsedData = {};
1246
+ for(const key in data)if (Object.hasOwn(data, key)) {
1247
+ const field = fields[key];
1248
+ if (!field) {
1249
+ parsedData[key] = data[key];
1250
+ continue;
1251
+ }
1252
+ if (false === field.returned) continue;
1253
+ parsedData[key] = data[key];
1254
+ }
1255
+ return parsedData;
1256
+ }
1257
+ function getAllFields(options, table, conflictResolution = {
1258
+ strategy: 'error'
1259
+ }) {
1260
+ const schema = {};
1261
+ const fieldOrigins = new Map();
1262
+ const addFields = (fields, source)=>{
1263
+ for (const [key, field] of Object.entries(fields)){
1264
+ if (schema[key]) {
1265
+ const origins = fieldOrigins.get(key) || [];
1266
+ origins.push(source);
1267
+ fieldOrigins.set(key, origins);
1268
+ if ('error' === conflictResolution.strategy) throw new error_C15TError('A field conflict was detected in the schema. Multiple definitions exist for the same field.', {
1269
+ code: codes_BASE_ERROR_CODES.CONFLICT,
1270
+ status: 500,
1271
+ data: {
1272
+ field: key,
1273
+ table,
1274
+ definedIn: origins.join(', ')
1275
+ }
1276
+ });
1277
+ if ('warn' === conflictResolution.strategy && conflictResolution.onWarning) conflictResolution.onWarning(`Field conflict detected for '${key}' in table '${table}'. Using last definition from ${source}.`);
1278
+ }
1279
+ schema[key] = field;
1280
+ }
1281
+ };
1282
+ if (options.tables && table in options.tables) {
1283
+ const tableConfig = options.tables[table];
1284
+ if (tableConfig?.additionalFields) addFields(tableConfig.additionalFields, 'table configuration');
1285
+ }
1286
+ for (const plugin of options.plugins || []){
1287
+ const pluginSchema = plugin.schema;
1288
+ if (pluginSchema?.[table]) addFields(pluginSchema[table].fields, `plugin: ${plugin.name || 'unnamed'}`);
1289
+ }
1290
+ return schema;
1291
+ }
1292
+ function parseInputData(data, schema, extraFieldsConfig = {
1293
+ strategy: 'error'
1294
+ }) {
1295
+ const action = schema.action || 'create';
1296
+ const fields = schema.fields;
1297
+ const parsedData = {};
1298
+ const extraFields = new Set();
1299
+ for(const key in fields)if (Object.hasOwn(fields, key)) {
1300
+ if (key in data) {
1301
+ if (fields[key]?.input === false) {
1302
+ if (fields[key]?.defaultValue) parsedData[key] = fields[key]?.defaultValue;
1303
+ continue;
1304
+ }
1305
+ function isLegacyValidator(validator) {
1306
+ return 'object' == typeof validator && null !== validator && 'input' in validator;
1307
+ }
1308
+ if (fields[key]?.validator && isLegacyValidator(fields[key]?.validator) && fields[key]?.validator.input && void 0 !== data[key]) {
1309
+ parsedData[key] = fields[key]?.validator.input.parse(data[key]);
1310
+ continue;
1311
+ }
1312
+ if (fields[key]?.transform?.input && void 0 !== data[key]) {
1313
+ const inputValue = data[key];
1314
+ parsedData[key] = fields[key]?.transform?.input(inputValue);
1315
+ continue;
1316
+ }
1317
+ parsedData[key] = data[key];
1318
+ continue;
1319
+ }
1320
+ if (fields[key]?.defaultValue && 'create' === action) {
1321
+ parsedData[key] = fields[key]?.defaultValue;
1322
+ continue;
1323
+ }
1324
+ if (fields[key]?.required && 'create' === action) throw new error_C15TError('Missing required field', {
1325
+ code: codes_BASE_ERROR_CODES.BAD_REQUEST,
1326
+ status: 400,
1327
+ data: {
1328
+ message: `${key} is required`
1329
+ }
1330
+ });
1331
+ }
1332
+ for(const key in data)if (Object.hasOwn(data, key) && !(key in fields)) extraFields.add(key);
1333
+ if (extraFields.size > 0) {
1334
+ const allowedFields = new Set(extraFieldsConfig.allowedExtraFields || []);
1335
+ const unallowedFields = Array.from(extraFields).filter((field)=>!allowedFields.has(field));
1336
+ if (unallowedFields.length > 0) switch(extraFieldsConfig.strategy){
1337
+ case 'error':
1338
+ throw new error_C15TError('Unexpected fields found', {
1339
+ code: codes_BASE_ERROR_CODES.BAD_REQUEST,
1340
+ status: 400,
1341
+ data: {
1342
+ message: `Unexpected fields found: ${unallowedFields.join(', ')}`
1343
+ }
1344
+ });
1345
+ case 'warn':
1346
+ if (extraFieldsConfig.onWarning) extraFieldsConfig.onWarning(`Unexpected fields found: ${unallowedFields.join(', ')}`);
1347
+ for (const key of extraFields)parsedData[key] = data[key];
1348
+ break;
1349
+ case 'silent':
1350
+ for (const key of extraFields)parsedData[key] = data[key];
1351
+ break;
1352
+ case 'drop':
1353
+ break;
1354
+ default:
1355
+ throw new error_C15TError('Unexpected fields found', {
1356
+ code: codes_BASE_ERROR_CODES.BAD_REQUEST,
1357
+ status: 400,
1358
+ data: {
1359
+ message: `Unexpected fields found: ${unallowedFields.join(', ')}`
1360
+ }
1361
+ });
1362
+ }
1363
+ else for (const key of extraFields)parsedData[key] = data[key];
1364
+ }
1365
+ return parsedData;
1366
+ }
1367
+ const levels = [
1368
+ 'info',
1369
+ 'success',
1370
+ 'warn',
1371
+ 'error',
1372
+ 'debug'
1373
+ ];
1374
+ function shouldPublishLog(currentLogLevel, logLevel) {
1375
+ return levels.indexOf(logLevel) <= levels.indexOf(currentLogLevel);
1376
+ }
1377
+ const colors = {
1378
+ reset: '\x1b[0m',
1379
+ bright: '\x1b[1m',
1380
+ dim: '\x1b[2m',
1381
+ underscore: '\x1b[4m',
1382
+ blink: '\x1b[5m',
1383
+ reverse: '\x1b[7m',
1384
+ hidden: '\x1b[8m',
1385
+ fg: {
1386
+ black: '\x1b[30m',
1387
+ red: '\x1b[31m',
1388
+ green: '\x1b[32m',
1389
+ yellow: '\x1b[33m',
1390
+ blue: '\x1b[34m',
1391
+ magenta: '\x1b[35m',
1392
+ cyan: '\x1b[36m',
1393
+ white: '\x1b[37m'
1394
+ },
1395
+ bg: {
1396
+ black: '\x1b[40m',
1397
+ red: '\x1b[41m',
1398
+ green: '\x1b[42m',
1399
+ yellow: '\x1b[43m',
1400
+ blue: '\x1b[44m',
1401
+ magenta: '\x1b[45m',
1402
+ cyan: '\x1b[46m',
1403
+ white: '\x1b[47m'
1404
+ }
1405
+ };
1406
+ const levelColors = {
1407
+ info: colors.fg.blue,
1408
+ success: colors.fg.green,
1409
+ warn: colors.fg.yellow,
1410
+ error: colors.fg.red,
1411
+ debug: colors.fg.magenta
1412
+ };
1413
+ const formatMessage = (level, message)=>{
1414
+ const timestamp = new Date().toISOString();
1415
+ return `${colors.dim}${timestamp}${colors.reset} ${levelColors[level]}${level.toUpperCase()}${colors.reset} ${colors.bright}[c15t]:${colors.reset} ${message}`;
1416
+ };
1417
+ const createLogger = (options)=>{
1418
+ const enabled = options?.disabled !== true;
1419
+ const logLevel = options?.level ?? 'error';
1420
+ const LogFunc = (level, message, args = [])=>{
1421
+ if (!enabled || !shouldPublishLog(logLevel, level)) return;
1422
+ const formattedMessage = formatMessage(level, message);
1423
+ if (!options || 'function' != typeof options.log) {
1424
+ if ('error' === level) console.error(formattedMessage, ...args);
1425
+ else if ('warn' === level) console.warn(formattedMessage, ...args);
1426
+ else if ('info' === level) console.log(formattedMessage, ...args);
1427
+ else if ('debug' === level) console.debug(formattedMessage, ...args);
1428
+ else if ('success' === level) console.log(formattedMessage, ...args);
1429
+ return;
1430
+ }
1431
+ options.log('success' === level ? 'info' : level, message, ...args);
1432
+ };
1433
+ return Object.fromEntries(levels.map((level)=>[
1434
+ level,
1435
+ (...[message, ...args])=>LogFunc(level, message, args)
1436
+ ]));
1437
+ };
1438
+ createLogger();
1439
+ function dialect_getDatabaseType(db) {
1440
+ if (!db) return null;
1441
+ if ('dialect' in db) return dialect_getDatabaseType(db.dialect);
1442
+ if ('createDriver' in db) {
1443
+ if (db instanceof __WEBPACK_EXTERNAL_MODULE_kysely__.SqliteDialect) return 'sqlite';
1444
+ if (db instanceof __WEBPACK_EXTERNAL_MODULE_kysely__.MysqlDialect) return 'mysql';
1445
+ if (db instanceof __WEBPACK_EXTERNAL_MODULE_kysely__.PostgresDialect) return 'postgres';
1446
+ if (db instanceof __WEBPACK_EXTERNAL_MODULE_kysely__.MssqlDialect) return 'mssql';
1447
+ }
1448
+ if ('aggregate' in db) return 'sqlite';
1449
+ if ('getConnection' in db) return 'mysql';
1450
+ if ('connect' in db) return 'postgres';
1451
+ return null;
1452
+ }
1453
+ const createKyselyAdapter = async (config)=>{
1454
+ const db = config.database;
1455
+ if (!db) return {
1456
+ kysely: null,
1457
+ databaseType: null
1458
+ };
1459
+ if ('db' in db) {
1460
+ const kyselyConfig = db;
1461
+ return {
1462
+ kysely: kyselyConfig.db,
1463
+ databaseType: kyselyConfig.type
1464
+ };
1465
+ }
1466
+ if ('dialect' in db) {
1467
+ const dialectConfig = db;
1468
+ return {
1469
+ kysely: new __WEBPACK_EXTERNAL_MODULE_kysely__.Kysely({
1470
+ dialect: dialectConfig.dialect
1471
+ }),
1472
+ databaseType: dialectConfig.type
1473
+ };
1474
+ }
1475
+ let dialect;
1476
+ const databaseType = dialect_getDatabaseType(db);
1477
+ if ('createDriver' in db) dialect = db;
1478
+ if ('aggregate' in db) dialect = new __WEBPACK_EXTERNAL_MODULE_kysely__.SqliteDialect({
1479
+ database: db
1480
+ });
1481
+ if ('getConnection' in db) dialect = new __WEBPACK_EXTERNAL_MODULE_kysely__.MysqlDialect({
1482
+ pool: db
1483
+ });
1484
+ if ('connect' in db) dialect = new __WEBPACK_EXTERNAL_MODULE_kysely__.PostgresDialect({
1485
+ pool: db
1486
+ });
1487
+ return {
1488
+ kysely: dialect ? new __WEBPACK_EXTERNAL_MODULE_kysely__.Kysely({
1489
+ dialect
1490
+ }) : null,
1491
+ databaseType
1492
+ };
1493
+ };
1494
+ const postgresMap = {
1495
+ string: [
1496
+ 'character varying',
1497
+ 'text'
1498
+ ],
1499
+ number: [
1500
+ 'int4',
1501
+ 'integer',
1502
+ 'bigint',
1503
+ 'smallint',
1504
+ 'numeric',
1505
+ 'real',
1506
+ 'double precision'
1507
+ ],
1508
+ boolean: [
1509
+ 'bool',
1510
+ 'boolean'
1511
+ ],
1512
+ date: [
1513
+ 'timestamp',
1514
+ 'date'
1515
+ ],
1516
+ json: [
1517
+ 'json',
1518
+ 'jsonb'
1519
+ ],
1520
+ timezone: [
1521
+ 'text',
1522
+ 'character varying'
1523
+ ]
1524
+ };
1525
+ const mysqlMap = {
1526
+ string: [
1527
+ 'varchar(255)',
1528
+ 'varchar(36)',
1529
+ 'text'
1530
+ ],
1531
+ number: [
1532
+ 'integer',
1533
+ 'int',
1534
+ 'bigint',
1535
+ 'smallint',
1536
+ 'decimal',
1537
+ 'float',
1538
+ 'double'
1539
+ ],
1540
+ boolean: [
1541
+ 'boolean',
1542
+ 'tinyint'
1543
+ ],
1544
+ date: [
1545
+ 'timestamp',
1546
+ 'datetime',
1547
+ 'date'
1548
+ ],
1549
+ json: [
1550
+ 'json'
1551
+ ],
1552
+ timezone: [
1553
+ 'varchar(50)'
1554
+ ]
1555
+ };
1556
+ const sqliteMap = {
1557
+ string: [
1558
+ 'TEXT'
1559
+ ],
1560
+ number: [
1561
+ 'INTEGER',
1562
+ 'REAL'
1563
+ ],
1564
+ boolean: [
1565
+ 'INTEGER',
1566
+ 'BOOLEAN'
1567
+ ],
1568
+ date: [
1569
+ 'DATE',
1570
+ 'INTEGER'
1571
+ ],
1572
+ json: [
1573
+ 'TEXT'
1574
+ ],
1575
+ timezone: [
1576
+ 'TEXT'
1577
+ ]
1578
+ };
1579
+ const mssqlMap = {
1580
+ string: [
1581
+ 'text',
1582
+ 'varchar'
1583
+ ],
1584
+ number: [
1585
+ 'int',
1586
+ 'bigint',
1587
+ 'smallint',
1588
+ 'decimal',
1589
+ 'float(53)',
1590
+ 'float(24)'
1591
+ ],
1592
+ boolean: [
1593
+ 'bit',
1594
+ 'smallint'
1595
+ ],
1596
+ date: [
1597
+ 'datetime',
1598
+ 'date'
1599
+ ],
1600
+ json: [
1601
+ 'nvarchar(max)'
1602
+ ],
1603
+ timezone: [
1604
+ 'varchar',
1605
+ 'text'
1606
+ ]
1607
+ };
1608
+ const map = {
1609
+ postgres: postgresMap,
1610
+ mysql: mysqlMap,
1611
+ sqlite: sqliteMap,
1612
+ mssql: mssqlMap
1613
+ };
1614
+ function getMySqlStringType(field) {
1615
+ if (field.unique) return 'varchar(255)';
1616
+ if (field.references) return 'varchar(36)';
1617
+ return 'text';
1618
+ }
1619
+ function matchType(columnDataType, fieldType, dbType) {
1620
+ if ('string[]' === fieldType || 'number[]' === fieldType) return columnDataType.toLowerCase().includes('json');
1621
+ const types = map[dbType];
1622
+ const type = Array.isArray(fieldType) ? types.string.map((t)=>t.toLowerCase()) : types[fieldType].map((t)=>t.toLowerCase());
1623
+ const matches = type.includes(columnDataType.toLowerCase());
1624
+ return matches;
1625
+ }
1626
+ function getType(field, dbType = 'sqlite') {
1627
+ const type = field.type;
1628
+ const typeMap = {
1629
+ string: {
1630
+ sqlite: 'text',
1631
+ postgres: 'text',
1632
+ mysql: getMySqlStringType(field),
1633
+ mssql: getMySqlStringType(field)
1634
+ },
1635
+ boolean: {
1636
+ sqlite: 'integer',
1637
+ postgres: 'boolean',
1638
+ mysql: 'boolean',
1639
+ mssql: 'smallint'
1640
+ },
1641
+ number: {
1642
+ sqlite: field.bigint ? 'bigint' : 'integer',
1643
+ postgres: field.bigint ? 'bigint' : 'integer',
1644
+ mysql: field.bigint ? 'bigint' : 'integer',
1645
+ mssql: field.bigint ? 'bigint' : 'integer'
1646
+ },
1647
+ date: {
1648
+ sqlite: 'date',
1649
+ postgres: 'timestamp',
1650
+ mysql: 'datetime',
1651
+ mssql: 'datetime'
1652
+ },
1653
+ timezone: {
1654
+ sqlite: 'text',
1655
+ postgres: 'text',
1656
+ mysql: 'varchar(50)',
1657
+ mssql: 'nvarchar(50)'
1658
+ },
1659
+ json: {
1660
+ sqlite: 'text',
1661
+ postgres: 'jsonb',
1662
+ mysql: 'json',
1663
+ mssql: 'nvarchar(max)'
1664
+ }
1665
+ };
1666
+ if ('sqlite' === dbType && ('string[]' === type || 'number[]' === type)) return 'text';
1667
+ if ('string[]' === type || 'number[]' === type) switch(dbType){
1668
+ case 'postgres':
1669
+ return 'jsonb';
1670
+ case 'mysql':
1671
+ case 'mssql':
1672
+ return 'json';
1673
+ default:
1674
+ return 'text';
1675
+ }
1676
+ if ('json' === type) return typeMap.json[dbType];
1677
+ return typeMap[type][dbType];
1678
+ }
1679
+ function buildColumnAddMigrations(db, toBeAdded, dbType) {
1680
+ const migrations = [];
1681
+ for (const table of toBeAdded)for (const [fieldName, field] of Object.entries(table.fields)){
1682
+ const type = getType(field, dbType);
1683
+ const exec = db.schema.alterTable(table.table).addColumn(fieldName, type, (col)=>{
1684
+ let column = false !== field.required ? col.notNull() : col;
1685
+ if (field.references) column = column.references(`${field.references.model}.${field.references.field}`);
1686
+ if (field.unique) column = column.unique();
1687
+ return column;
1688
+ });
1689
+ migrations.push(exec);
1690
+ }
1691
+ return migrations;
1692
+ }
1693
+ function buildTableCreateMigrations(db, toBeCreated, dbType) {
1694
+ const logger = createLogger();
1695
+ const migrations = [];
1696
+ for (const table of toBeCreated){
1697
+ const fieldNames = Object.keys(table.fields);
1698
+ logger.info(`Creating table ${table.table} with fields: ${fieldNames.join(', ')}`);
1699
+ if (fieldNames.includes('id')) logger.warn(`⚠️ Table ${table.table} already has an explicit 'id' field, which may conflict with the auto-generated primary key`);
1700
+ for (const [fieldName, field] of Object.entries(table.fields))if ('id' === field.fieldName && 'id' !== fieldName) logger.error(`❌ ERROR: Table ${table.table} has field '${fieldName}' with fieldName 'id' - this will cause a duplicate column error`);
1701
+ let dbT = db.schema.createTable(table.table).addColumn('id', 'mysql' === dbType || 'mssql' === dbType ? 'varchar(36)' : 'text', (col)=>col.primaryKey().notNull());
1702
+ for (const [fieldName, field] of Object.entries(table.fields)){
1703
+ const type = getType(field, dbType);
1704
+ logger.info(`Adding column ${fieldName} (fieldName: ${field.fieldName || fieldName}) to table ${table.table}`);
1705
+ dbT = dbT.addColumn(fieldName, type, (col)=>{
1706
+ let column = false !== field.required ? col.notNull() : col;
1707
+ if (field.references) column = column.references(`${field.references.model}.${field.references.field}`);
1708
+ if (field.unique) column = column.unique();
1709
+ return column;
1710
+ });
1711
+ }
1712
+ const sqlDebug = dbT.compile().sql;
1713
+ logger.info(`SQL for table ${table.table}:\n${sqlDebug}`);
1714
+ migrations.push(dbT);
1715
+ }
1716
+ return migrations;
1717
+ }
1718
+ function createMigrationExecutors(migrations) {
1719
+ const logger = createLogger();
1720
+ async function runMigrations() {
1721
+ for (const migration of migrations)try {
1722
+ await migration.execute();
1723
+ } catch (error) {
1724
+ const sql = migration.compile().sql;
1725
+ logger.error(`Migration failed! SQL:\n${sql}`);
1726
+ throw error;
1727
+ }
1728
+ }
1729
+ async function compileMigrations() {
1730
+ const compiled = migrations.map((m)=>m.compile().sql);
1731
+ return `${compiled.join(';\n\n')};`;
1732
+ }
1733
+ return {
1734
+ runMigrations,
1735
+ compileMigrations
1736
+ };
1737
+ }
1738
+ function applyDefaultValue(inputValue, field, operation) {
1739
+ if ('update' === operation) return inputValue;
1740
+ if (null == inputValue && field.defaultValue) {
1741
+ if ('function' == typeof field.defaultValue) return field.defaultValue();
1742
+ return field.defaultValue;
1743
+ }
1744
+ return inputValue;
1745
+ }
1746
+ const createEntityTransformer = (db, options, config)=>{
1747
+ const schema = getConsentTables(options);
1748
+ function getField(model, field) {
1749
+ if ('id' === field) return field;
1750
+ const modelFields = schema[model]?.fields;
1751
+ const f = modelFields ? modelFields[field] : void 0;
1752
+ if (!f) console.log('Field not found', model, field);
1753
+ return f?.fieldName || field;
1754
+ }
1755
+ function transformValueToDB(value, model, field) {
1756
+ if ('id' === field) return value;
1757
+ const { type = 'sqlite' } = config || {};
1758
+ const modelFields = schema[model]?.fields;
1759
+ const f = modelFields ? modelFields[field] : void 0;
1760
+ if (f?.type === 'boolean' && ('sqlite' === type || 'mssql' === type) && null != value) return value ? 1 : 0;
1761
+ if (f?.type === 'date' && value && value instanceof Date) return 'sqlite' === type ? value.toISOString() : value;
1762
+ if (f?.type === 'json' && null != value) {
1763
+ if ('postgres' === type || 'mysql' === type) return value;
1764
+ return __WEBPACK_EXTERNAL_MODULE_superjson__["default"].stringify(value);
1765
+ }
1766
+ return value;
1767
+ }
1768
+ function transformValueFromDB(value, model, field) {
1769
+ const { type = 'sqlite' } = config || {};
1770
+ const modelFields = schema[model]?.fields;
1771
+ const f = modelFields ? modelFields[field] : void 0;
1772
+ if (f?.type === 'boolean' && ('sqlite' === type || 'mssql' === type) && null !== value) return 1 === value;
1773
+ if (f?.type === 'date' && value) return new Date(value);
1774
+ if (f?.type === 'json' && null != value) {
1775
+ if (('postgres' === type || 'mysql' === type) && 'object' == typeof value) return value;
1776
+ if ('string' == typeof value) try {
1777
+ return __WEBPACK_EXTERNAL_MODULE_superjson__["default"].parse(value);
1778
+ } catch {
1779
+ try {
1780
+ return JSON.parse(value);
1781
+ } catch {}
1782
+ }
1783
+ }
1784
+ return value;
1785
+ }
1786
+ function getEntityName(model) {
1787
+ return schema[model].entityName;
1788
+ }
1789
+ return {
1790
+ transformInput (data, model, action) {
1791
+ const transformedData = {};
1792
+ if ('create' === action) transformedData.id = data.id || (options.advanced?.generateId ? options.advanced.generateId({
1793
+ model
1794
+ }) : generateId(schema[model].entityPrefix));
1795
+ const fields = schema[model].fields;
1796
+ for(const field in fields)if (Object.hasOwn(fields, field)) {
1797
+ const value = data[field];
1798
+ const fieldInfo = fields[field];
1799
+ const fieldName = fieldInfo?.fieldName || field;
1800
+ if (fieldInfo) transformedData[fieldName] = applyDefaultValue(transformValueToDB(value, model, field), fieldInfo, action);
1801
+ }
1802
+ return transformedData;
1803
+ },
1804
+ transformOutput (data, model, select = []) {
1805
+ if (!data) return null;
1806
+ const transformedData = {};
1807
+ if (data.id && (0 === select.length || select.includes('id'))) transformedData.id = data.id;
1808
+ const tableSchema = schema[model]?.fields;
1809
+ for(const key in tableSchema){
1810
+ if (select.length && !select.includes(key)) continue;
1811
+ const field = tableSchema[key];
1812
+ if (field) transformedData[key] = transformValueFromDB(data[field.fieldName || key], model, key);
1813
+ }
1814
+ return transformedData;
1815
+ },
1816
+ convertWhereClause (model, whereConditions) {
1817
+ if (!whereConditions || 0 === whereConditions.length) return {
1818
+ and: null,
1819
+ or: null
1820
+ };
1821
+ const conditions = {
1822
+ and: [],
1823
+ or: []
1824
+ };
1825
+ for (const condition of whereConditions){
1826
+ let { field: _field, value, operator = '=', connector = 'AND' } = condition;
1827
+ const fieldString = getField(model, _field);
1828
+ value = transformValueToDB(value, model, _field);
1829
+ const expr = (eb)=>{
1830
+ const dbField = fieldString;
1831
+ if ('in' === operator.toLowerCase()) return eb(dbField, 'in', Array.isArray(value) ? value : [
1832
+ value
1833
+ ]);
1834
+ if ('contains' === operator) return eb(dbField, 'like', `%${value}%`);
1835
+ if ('starts_with' === operator) return eb(dbField, 'like', `${value}%`);
1836
+ if ('ends_with' === operator) return eb(dbField, 'like', `%${value}`);
1837
+ if ('ilike' === operator) {
1838
+ const lowerField = eb.fn('lower', [
1839
+ dbField
1840
+ ]);
1841
+ const lowerValue = eb.fn('lower', [
1842
+ eb.val(value?.toString())
1843
+ ]);
1844
+ return eb(lowerField, 'like', lowerValue);
1845
+ }
1846
+ if ('eq' === operator) return eb(dbField, '=', value);
1847
+ if ('ne' === operator) return eb(dbField, '<>', value);
1848
+ if ('gt' === operator) return eb(dbField, '>', value);
1849
+ if ('gte' === operator) return eb(dbField, '>=', value);
1850
+ if ('lt' === operator) return eb(dbField, '<', value);
1851
+ if ('lte' === operator) return eb(dbField, '<=', value);
1852
+ return eb(dbField, operator, value);
1853
+ };
1854
+ if ('OR' === connector) conditions.or.push(expr);
1855
+ else conditions.and.push(expr);
1856
+ }
1857
+ return {
1858
+ and: conditions.and.length ? conditions.and : null,
1859
+ or: conditions.or.length ? conditions.or : null
1860
+ };
1861
+ },
1862
+ async withReturning (values, builder, model, where) {
1863
+ let res = null;
1864
+ if (config?.type === 'mysql') {
1865
+ await builder.execute();
1866
+ const whereCondition = where[0];
1867
+ const field = values.id ? 'id' : whereCondition?.field ?? 'id';
1868
+ const value = values[field] ?? whereCondition?.value;
1869
+ const fieldString = getField(model, field);
1870
+ res = await db.selectFrom(getEntityName(model)).selectAll().where((eb)=>eb(fieldString, '=', value)).executeTakeFirst();
1871
+ return res;
1872
+ }
1873
+ if (config?.type === 'mssql') {
1874
+ res = await builder.outputAll('inserted').executeTakeFirst();
1875
+ return res;
1876
+ }
1877
+ res = await builder.returningAll().executeTakeFirst();
1878
+ return res;
1879
+ },
1880
+ getEntityName,
1881
+ getField
1882
+ };
1883
+ };
1884
+ const kyselyAdapter = (db, config)=>(opts)=>{
1885
+ const { transformInput, withReturning, transformOutput, convertWhereClause, getEntityName, getField } = createEntityTransformer(db, opts, config);
1886
+ return {
1887
+ id: 'kysely',
1888
+ async create (data) {
1889
+ const { model, data: values, select } = data;
1890
+ const transformed = transformInput(values, model, 'create');
1891
+ const tableName = getEntityName(model);
1892
+ const builder = db.insertInto(tableName).values(transformed);
1893
+ const result = await withReturning(transformed, builder, model, []);
1894
+ const output = transformOutput(result, model, select);
1895
+ return output;
1896
+ },
1897
+ async findOne (data) {
1898
+ const { model, where, select } = data;
1899
+ const whereArray = Array.isArray(where) ? where : [
1900
+ where
1901
+ ];
1902
+ const { and, or } = convertWhereClause(model, whereArray);
1903
+ const tableName = getEntityName(model);
1904
+ let query = db.selectFrom(tableName).selectAll();
1905
+ if (and) query = query.where((eb)=>{
1906
+ const conditions = and.map((expr)=>expr(eb));
1907
+ return eb.and(conditions);
1908
+ });
1909
+ if (or) query = query.where((eb)=>{
1910
+ const conditions = or.map((expr)=>expr(eb));
1911
+ return eb.or(conditions);
1912
+ });
1913
+ const res = await query.executeTakeFirst();
1914
+ if (!res) return null;
1915
+ return transformOutput(res, model, select);
1916
+ },
1917
+ async findMany (data) {
1918
+ const { model, where, limit, offset, sortBy } = data;
1919
+ const whereArray = where ? Array.isArray(where) ? where : [
1920
+ where
1921
+ ] : void 0;
1922
+ const { and, or } = convertWhereClause(model, whereArray);
1923
+ const tableName = getEntityName(model);
1924
+ let query = db.selectFrom(tableName);
1925
+ if (and) query = query.where((eb)=>{
1926
+ const conditions = and.map((expr)=>expr(eb));
1927
+ return eb.and(conditions);
1928
+ });
1929
+ if (or) query = query.where((eb)=>{
1930
+ const conditions = or.map((expr)=>expr(eb));
1931
+ return eb.or(conditions);
1932
+ });
1933
+ if (config?.type === 'mssql') {
1934
+ if (!offset) query = query.top(limit || 100);
1935
+ } else query = query.limit(limit || 100);
1936
+ if (sortBy) {
1937
+ const sortFieldString = getField(model, sortBy.field);
1938
+ query = query.orderBy(sortFieldString, sortBy.direction);
1939
+ }
1940
+ if (offset) {
1941
+ if (config?.type === 'mssql') {
1942
+ if (!sortBy) query = query.orderBy('id');
1943
+ query = query.offset(offset).fetch(limit || 100);
1944
+ } else query = query.offset(offset);
1945
+ }
1946
+ const res = await query.selectAll().execute();
1947
+ if (!res) return [];
1948
+ return res.map((r)=>transformOutput(r, model));
1949
+ },
1950
+ async update (data) {
1951
+ const { model, where, update: values } = data;
1952
+ const whereArray = Array.isArray(where) ? where : [
1953
+ where
1954
+ ];
1955
+ const { and, or } = convertWhereClause(model, whereArray);
1956
+ const transformedData = transformInput(values, model, 'update');
1957
+ const tableName = getEntityName(model);
1958
+ let query = db.updateTable(tableName).set(transformedData);
1959
+ if (and) query = query.where((eb)=>{
1960
+ const conditions = and.map((expr)=>expr(eb));
1961
+ return eb.and(conditions);
1962
+ });
1963
+ if (or) query = query.where((eb)=>{
1964
+ const conditions = or.map((expr)=>expr(eb));
1965
+ return eb.or(conditions);
1966
+ });
1967
+ const result = await withReturning(transformedData, query, model, whereArray);
1968
+ return transformOutput(result, model);
1969
+ },
1970
+ async updateMany (data) {
1971
+ const { model, where, update: values } = data;
1972
+ const whereArray = Array.isArray(where) ? where : [
1973
+ where
1974
+ ];
1975
+ const { and, or } = convertWhereClause(model, whereArray);
1976
+ const transformedData = transformInput(values, model, 'update');
1977
+ const tableName = getEntityName(model);
1978
+ let query = db.updateTable(tableName).set(transformedData);
1979
+ if (and) query = query.where((eb)=>{
1980
+ const conditions = and.map((expr)=>expr(eb));
1981
+ return eb.and(conditions);
1982
+ });
1983
+ if (or) query = query.where((eb)=>{
1984
+ const conditions = or.map((expr)=>expr(eb));
1985
+ return eb.or(conditions);
1986
+ });
1987
+ await query.execute();
1988
+ let selectQuery = db.selectFrom(tableName).selectAll();
1989
+ if (and) selectQuery = selectQuery.where((eb)=>{
1990
+ const conditions = and.map((expr)=>expr(eb));
1991
+ return eb.and(conditions);
1992
+ });
1993
+ if (or) selectQuery = selectQuery.where((eb)=>{
1994
+ const conditions = or.map((expr)=>expr(eb));
1995
+ return eb.or(conditions);
1996
+ });
1997
+ const fetchedResults = await selectQuery.execute();
1998
+ if (!fetchedResults || 0 === fetchedResults.length) return [];
1999
+ return fetchedResults.map((record)=>transformOutput(record, model));
2000
+ },
2001
+ async count (data) {
2002
+ const { model, where } = data;
2003
+ const whereArray = where ? Array.isArray(where) ? where : [
2004
+ where
2005
+ ] : void 0;
2006
+ const { and, or } = convertWhereClause(model, whereArray);
2007
+ const tableName = getEntityName(model);
2008
+ let query = db.selectFrom(tableName).select((eb)=>eb.fn.count('id').as('count'));
2009
+ if (and) query = query.where((eb)=>{
2010
+ const conditions = and.map((expr)=>expr(eb));
2011
+ return eb.and(conditions);
2012
+ });
2013
+ if (or) query = query.where((eb)=>{
2014
+ const conditions = or.map((expr)=>expr(eb));
2015
+ return eb.or(conditions);
2016
+ });
2017
+ const res = await query.execute();
2018
+ const count = res[0]?.count;
2019
+ return 'number' == typeof count ? count : 0;
2020
+ },
2021
+ async delete (data) {
2022
+ const { model, where } = data;
2023
+ const whereArray = Array.isArray(where) ? where : [
2024
+ where
2025
+ ];
2026
+ const { and, or } = convertWhereClause(model, whereArray);
2027
+ const tableName = getEntityName(model);
2028
+ let query = db.deleteFrom(tableName);
2029
+ if (and) query = query.where((eb)=>{
2030
+ const conditions = and.map((expr)=>expr(eb));
2031
+ return eb.and(conditions);
2032
+ });
2033
+ if (or) query = query.where((eb)=>{
2034
+ const conditions = or.map((expr)=>expr(eb));
2035
+ return eb.or(conditions);
2036
+ });
2037
+ await query.execute();
2038
+ },
2039
+ async deleteMany (data) {
2040
+ const { model, where } = data;
2041
+ const whereArray = Array.isArray(where) ? where : [
2042
+ where
2043
+ ];
2044
+ const { and, or } = convertWhereClause(model, whereArray);
2045
+ const tableName = getEntityName(model);
2046
+ let query = db.deleteFrom(tableName);
2047
+ if (and) query = query.where((eb)=>{
2048
+ const conditions = and.map((expr)=>expr(eb));
2049
+ return eb.and(conditions);
2050
+ });
2051
+ if (or) query = query.where((eb)=>{
2052
+ const conditions = or.map((expr)=>expr(eb));
2053
+ return eb.or(conditions);
2054
+ });
2055
+ const result = await query.execute();
2056
+ const count = result.length;
2057
+ return count;
2058
+ },
2059
+ async transaction (data) {
2060
+ const { callback } = data;
2061
+ if (opts.advanced?.disableTransactions) {
2062
+ const regularAdapter = kyselyAdapter(db, config)(opts);
2063
+ return await callback(regularAdapter);
2064
+ }
2065
+ try {
2066
+ return await db.transaction().execute(async (trx)=>{
2067
+ const transactionAdapter = kyselyAdapter(trx, config)(opts);
2068
+ return await callback(transactionAdapter);
2069
+ });
2070
+ } catch (error) {
2071
+ if (error instanceof Error && (error.message.includes('transactions are not supported') || error.message.toLowerCase().includes('no transaction support'))) {
2072
+ 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.");
2073
+ const regularAdapter = kyselyAdapter(db, config)(opts);
2074
+ return await callback(regularAdapter);
2075
+ }
2076
+ throw error;
2077
+ }
2078
+ },
2079
+ options: config
2080
+ };
2081
+ };
2082
+ const memory_adapter_createEntityTransformer = (options)=>{
2083
+ const schema = getConsentTables(options);
2084
+ function getField(model, field) {
2085
+ if ('id' === field) return field;
2086
+ const modelFields = schema[model]?.fields;
2087
+ const f = modelFields ? modelFields[field] : void 0;
2088
+ return f?.fieldName || field;
2089
+ }
2090
+ return {
2091
+ transformInput (data, model, action) {
2092
+ const transformedData = 'update' === action ? {} : {
2093
+ id: options.advanced?.generateId ? options.advanced.generateId({
2094
+ model
2095
+ }) : data.id || generateId(schema[model].entityPrefix)
2096
+ };
2097
+ const fields = schema[model].fields;
2098
+ for(const field in fields)if (Object.hasOwn(fields, field)) {
2099
+ const value = data[field];
2100
+ const fieldInfo = fields[field];
2101
+ if (void 0 === value && !fieldInfo?.defaultValue) continue;
2102
+ const fieldName = fieldInfo?.fieldName || field;
2103
+ transformedData[fieldName] = applyDefaultValue(value, fieldInfo, action);
2104
+ }
2105
+ return transformedData;
2106
+ },
2107
+ transformOutput (data, model, select = []) {
2108
+ if (!data) return null;
2109
+ const transformedData = {};
2110
+ const hasId = data.id || data._id;
2111
+ if (hasId && (0 === select.length || select.includes('id'))) transformedData.id = data.id;
2112
+ const tableSchema = schema[model].fields;
2113
+ for(const key in tableSchema){
2114
+ if (select.length && !select.includes(key)) continue;
2115
+ const field = tableSchema[key];
2116
+ if (field) transformedData[key] = data[field.fieldName || key];
2117
+ }
2118
+ return transformedData;
2119
+ },
2120
+ convertWhereClause (where, table, model) {
2121
+ return table.filter((record)=>where.every((clause)=>{
2122
+ const { field: _field, value, operator = '=' } = clause;
2123
+ const field = getField(model, _field);
2124
+ if ('in' === operator) {
2125
+ if (!Array.isArray(value)) throw new Error('Value must be an array');
2126
+ return value.includes(record[field]);
2127
+ }
2128
+ if ('contains' === operator) {
2129
+ const fieldValue = record[field];
2130
+ return 'string' == typeof fieldValue && fieldValue.includes(value);
2131
+ }
2132
+ if ('starts_with' === operator) {
2133
+ const fieldValue = record[field];
2134
+ return 'string' == typeof fieldValue && fieldValue.startsWith(value);
2135
+ }
2136
+ if ('ends_with' === operator) {
2137
+ const fieldValue = record[field];
2138
+ return 'string' == typeof fieldValue && fieldValue.endsWith(value);
2139
+ }
2140
+ if ('eq' === operator) return record[field] === value;
2141
+ if ('ne' === operator) return record[field] !== value;
2142
+ return record[field] === value;
2143
+ }));
2144
+ },
2145
+ getField
2146
+ };
2147
+ };
2148
+ const memoryAdapter = (db)=>(options)=>{
2149
+ const { transformInput, transformOutput, convertWhereClause, getField } = memory_adapter_createEntityTransformer(options);
2150
+ return {
2151
+ id: 'memory',
2152
+ async create (data) {
2153
+ const { model, data: values, select } = data;
2154
+ const transformed = transformInput(values, model, 'create');
2155
+ if (!db[model]) db[model] = [];
2156
+ db[model].push(transformed);
2157
+ return transformOutput(transformed, model, select);
2158
+ },
2159
+ async findOne (data) {
2160
+ const { model, where, select } = data;
2161
+ const table = db[model] || [];
2162
+ const whereArray = Array.isArray(where) ? where : [
2163
+ where
2164
+ ];
2165
+ const res = convertWhereClause(whereArray, table, model);
2166
+ const record = res[0] || null;
2167
+ return transformOutput(record, model, select);
2168
+ },
2169
+ async findMany (data) {
2170
+ const { model, where, sortBy, limit, offset } = data;
2171
+ let table = db[model] || [];
2172
+ if (where) {
2173
+ const whereArray = Array.isArray(where) ? where : [
2174
+ where
2175
+ ];
2176
+ table = convertWhereClause(whereArray, table, model);
2177
+ }
2178
+ if (sortBy) {
2179
+ const field = getField(model, sortBy.field);
2180
+ table = [
2181
+ ...table
2182
+ ].sort((a, b)=>{
2183
+ if ('asc' === sortBy.direction) return a[field] > b[field] ? 1 : -1;
2184
+ return a[field] < b[field] ? 1 : -1;
2185
+ });
2186
+ }
2187
+ let result = table;
2188
+ if (void 0 !== offset) result = result.slice(offset);
2189
+ if (void 0 !== limit) result = result.slice(0, limit);
2190
+ return result.map((record)=>transformOutput(record, model));
2191
+ },
2192
+ async count (data) {
2193
+ const { model, where } = data;
2194
+ const table = db[model] || [];
2195
+ if (!where) return table.length;
2196
+ const whereArray = Array.isArray(where) ? where : [
2197
+ where
2198
+ ];
2199
+ const filtered = convertWhereClause(whereArray, table, model);
2200
+ return filtered.length;
2201
+ },
2202
+ async update (data) {
2203
+ const { model, where, update: values } = data;
2204
+ const table = db[model] || [];
2205
+ const whereArray = Array.isArray(where) ? where : [
2206
+ where
2207
+ ];
2208
+ const res = convertWhereClause(whereArray, table, model);
2209
+ for (const record of res)Object.assign(record, transformInput(values, model, 'update'));
2210
+ return transformOutput(res[0] || null, model);
2211
+ },
2212
+ async updateMany (data) {
2213
+ const { model, where, update: values } = data;
2214
+ const table = db[model] || [];
2215
+ const whereArray = Array.isArray(where) ? where : [
2216
+ where
2217
+ ];
2218
+ const res = convertWhereClause(whereArray, table, model);
2219
+ for (const record of res)Object.assign(record, transformInput(values, model, 'update'));
2220
+ return res.map((record)=>transformOutput(record, model));
2221
+ },
2222
+ async delete (data) {
2223
+ const { model, where } = data;
2224
+ const table = db[model] || [];
2225
+ const whereArray = Array.isArray(where) ? where : [
2226
+ where
2227
+ ];
2228
+ const res = convertWhereClause(whereArray, table, model);
2229
+ db[model] = table.filter((record)=>!res.includes(record));
2230
+ },
2231
+ async deleteMany (data) {
2232
+ const { model, where } = data;
2233
+ const table = db[model] || [];
2234
+ const whereArray = Array.isArray(where) ? where : [
2235
+ where
2236
+ ];
2237
+ const res = convertWhereClause(whereArray, table, model);
2238
+ let count = 0;
2239
+ db[model] = table.filter((record)=>{
2240
+ if (res.includes(record)) {
2241
+ count++;
2242
+ return false;
2243
+ }
2244
+ return true;
2245
+ });
2246
+ return count;
2247
+ },
2248
+ async transaction (data) {
2249
+ const { callback } = data;
2250
+ const tempDb = {};
2251
+ for(const key in db)if (Object.hasOwn(db, key)) tempDb[key] = JSON.parse(JSON.stringify(db[key]));
2252
+ const transactionAdapter = memoryAdapter(tempDb)(options);
2253
+ const result = await callback(transactionAdapter);
2254
+ for(const key in tempDb)if (Object.hasOwn(tempDb, key)) db[key] = tempDb[key];
2255
+ return result;
2256
+ }
2257
+ };
2258
+ };
2259
+ async function getAdapter(options) {
2260
+ const logger = createLogger();
2261
+ if (!options.database) {
2262
+ const tables = getConsentTables(options);
2263
+ const memoryDB = Object.keys(tables).reduce((acc, key)=>{
2264
+ acc[key] = [];
2265
+ return acc;
2266
+ }, {});
2267
+ logger.warn('No database configuration provided. Using memory adapter in development');
2268
+ return memoryAdapter(memoryDB)(options);
2269
+ }
2270
+ if ('function' == typeof options.database) return options.database(options);
2271
+ const { kysely, databaseType } = await createKyselyAdapter(options);
2272
+ if (!kysely) throw new error_C15TError('Failed to initialize database adapter', {
2273
+ code: codes_BASE_ERROR_CODES.INTERNAL_SERVER_ERROR,
2274
+ status: 500
2275
+ });
2276
+ return kyselyAdapter(kysely, {
2277
+ type: databaseType || 'sqlite'
2278
+ })(options);
2279
+ }
2280
+ function getSchema(config) {
2281
+ const entities = getConsentTables(config);
2282
+ const schema = {};
2283
+ for (const [key, entity] of Object.entries(entities)){
2284
+ if (!entity) continue;
2285
+ const fields = entity.fields || {};
2286
+ const processedFields = {};
2287
+ for (const [fieldKey, field] of Object.entries(fields)){
2288
+ if (!field) continue;
2289
+ const fieldName = field.fieldName || fieldKey;
2290
+ const typedField = field;
2291
+ processedFields[fieldName] = typedField;
2292
+ if (typedField && 'references' in typedField && typedField.references) {
2293
+ const entityName = typedField.references.model;
2294
+ const referencedEntity = entities[entityName];
2295
+ if (referencedEntity) processedFields[fieldName] = {
2296
+ ...typedField,
2297
+ references: {
2298
+ model: referencedEntity.entityName,
2299
+ entity: referencedEntity.entityName,
2300
+ field: typedField.references.field,
2301
+ onDelete: typedField.references.onDelete
2302
+ }
2303
+ };
2304
+ }
2305
+ }
2306
+ const entityName = entity.entityName || key;
2307
+ if (entityName in schema) {
2308
+ const existingEntry = schema[entityName];
2309
+ schema[entityName] = {
2310
+ ...existingEntry,
2311
+ order: existingEntry?.order ?? Number.POSITIVE_INFINITY,
2312
+ fields: {
2313
+ ...existingEntry?.fields,
2314
+ ...processedFields
2315
+ }
2316
+ };
2317
+ } else schema[entityName] = {
2318
+ fields: processedFields,
2319
+ order: entity.order ?? Number.POSITIVE_INFINITY
2320
+ };
2321
+ }
2322
+ return schema;
2323
+ }
2324
+ function analyzeSchemaChanges(config, tableMetadata, dbType) {
2325
+ const betterAuthSchema = getSchema(config);
2326
+ const logger = createLogger(config.logger);
2327
+ const toBeCreated = [];
2328
+ const toBeAdded = [];
2329
+ for (const [key, value] of Object.entries(betterAuthSchema)){
2330
+ const table = tableMetadata.find((t)=>t.name === key);
2331
+ if (!table) {
2332
+ handleNewTable(key, value, toBeCreated);
2333
+ continue;
2334
+ }
2335
+ handleExistingTable(key, value, table, toBeAdded, dbType, logger);
2336
+ }
2337
+ return {
2338
+ toBeCreated,
2339
+ toBeAdded
2340
+ };
2341
+ }
2342
+ function handleNewTable(tableName, value, toBeCreated) {
2343
+ const tIndex = toBeCreated.findIndex((t)=>t.table === tableName);
2344
+ const tableData = {
2345
+ table: tableName,
2346
+ fields: value.fields,
2347
+ order: value.order || Number.POSITIVE_INFINITY
2348
+ };
2349
+ const insertIndex = toBeCreated.findIndex((t)=>(t.order || Number.POSITIVE_INFINITY) > tableData.order);
2350
+ if (-1 === insertIndex) {
2351
+ if (-1 === tIndex) toBeCreated.push(tableData);
2352
+ else {
2353
+ const existingTable = toBeCreated[tIndex];
2354
+ if (existingTable) existingTable.fields = {
2355
+ ...existingTable.fields,
2356
+ ...value.fields
2357
+ };
2358
+ }
2359
+ } else toBeCreated.splice(insertIndex, 0, tableData);
2360
+ }
2361
+ function handleExistingTable(tableName, value, table, toBeAdded, dbType, logger) {
2362
+ const toBeAddedFields = {};
2363
+ for (const [fieldName, field] of Object.entries(value.fields)){
2364
+ const column = table.columns.find((c)=>c.name === fieldName);
2365
+ if (!column) {
2366
+ toBeAddedFields[fieldName] = field;
2367
+ continue;
2368
+ }
2369
+ if (!matchType(column.dataType, field.type, dbType)) logger.warn(`Field ${fieldName} in table ${tableName} has a different type in the database. Expected ${field.type} but got ${column.dataType}.`);
2370
+ }
2371
+ if (Object.keys(toBeAddedFields).length > 0) toBeAdded.push({
2372
+ table: tableName,
2373
+ fields: toBeAddedFields,
2374
+ order: value.order || Number.POSITIVE_INFINITY
2375
+ });
2376
+ }
2377
+ async function getMigrations(config) {
2378
+ const logger = createLogger(config.logger);
2379
+ let { kysely: db, databaseType: dbType } = await createKyselyAdapter(config);
2380
+ if (!dbType) {
2381
+ logger.warn('Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.');
2382
+ dbType = 'sqlite';
2383
+ }
2384
+ if (!db) {
2385
+ logger.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter.");
2386
+ process.exit(1);
2387
+ }
2388
+ const tableMetadata = await db.introspection.getTables();
2389
+ const { toBeCreated, toBeAdded } = analyzeSchemaChanges(config, tableMetadata, dbType);
2390
+ const columnMigrations = buildColumnAddMigrations(db, toBeAdded, dbType);
2391
+ const tableMigrations = buildTableCreateMigrations(db, toBeCreated, dbType);
2392
+ const migrations = [
2393
+ ...columnMigrations,
2394
+ ...tableMigrations
2395
+ ];
2396
+ const { runMigrations, compileMigrations } = createMigrationExecutors(migrations);
2397
+ return {
2398
+ toBeCreated,
2399
+ toBeAdded,
2400
+ runMigrations,
2401
+ compileMigrations
2402
+ };
2403
+ }
2404
+ export { booleanField, dateField, getAdapter, getAllFields, getConsentTables, getMigrations, numberArrayField, numberField, parseEntityOutputData, parseInputData, stringArrayField, stringField };