@c15t/backend 1.0.5 → 1.2.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (462) hide show
  1. package/.turbo/turbo-build.log +33 -39
  2. package/.turbo/turbo-fmt.log +3 -3
  3. package/.turbo/turbo-test.log +531 -0
  4. package/coverage/coverage-final.json +84 -0
  5. package/coverage/coverage-summary.json +85 -0
  6. package/coverage/html/backend/index.html +116 -0
  7. package/coverage/html/backend/rslib.config.ts.html +415 -0
  8. package/coverage/html/backend/src/contracts/consent/index.html +161 -0
  9. package/coverage/html/backend/src/contracts/consent/index.ts.html +112 -0
  10. package/coverage/html/backend/src/contracts/consent/post.contract.ts.html +559 -0
  11. package/coverage/html/backend/src/contracts/consent/show-banner.contract.ts.html +220 -0
  12. package/coverage/html/backend/src/contracts/consent/verify.contract.ts.html +463 -0
  13. package/coverage/html/backend/src/contracts/index.html +116 -0
  14. package/coverage/html/backend/src/contracts/index.ts.html +139 -0
  15. package/coverage/html/backend/src/contracts/meta/index.html +131 -0
  16. package/coverage/html/backend/src/contracts/meta/index.ts.html +100 -0
  17. package/coverage/html/backend/src/contracts/meta/status.contract.ts.html +196 -0
  18. package/coverage/html/backend/src/contracts/shared/index.html +116 -0
  19. package/coverage/html/backend/src/contracts/shared/jurisdiction.schema.ts.html +175 -0
  20. package/coverage/html/backend/src/core.ts.html +1624 -0
  21. package/coverage/html/backend/src/handlers/consent/index.html +161 -0
  22. package/coverage/html/backend/src/handlers/consent/index.ts.html +112 -0
  23. package/coverage/html/backend/src/handlers/consent/post.handler.ts.html +889 -0
  24. package/coverage/html/backend/src/handlers/consent/show-banner.handler.ts.html +535 -0
  25. package/coverage/html/backend/src/handlers/consent/verify.handler.ts.html +1000 -0
  26. package/coverage/html/backend/src/handlers/meta/index.html +131 -0
  27. package/coverage/html/backend/src/handlers/meta/index.ts.html +100 -0
  28. package/coverage/html/backend/src/handlers/meta/status.handler.ts.html +226 -0
  29. package/coverage/html/backend/src/index.html +161 -0
  30. package/coverage/html/backend/src/init.ts.html +1018 -0
  31. package/coverage/html/backend/src/pkgs/api-router/hooks/index.html +116 -0
  32. package/coverage/html/backend/src/pkgs/api-router/hooks/processor.ts.html +544 -0
  33. package/coverage/html/backend/src/pkgs/api-router/index.html +116 -0
  34. package/coverage/html/backend/src/pkgs/api-router/telemetry.ts.html +334 -0
  35. package/coverage/html/backend/src/pkgs/api-router/utils/cors.ts.html +304 -0
  36. package/coverage/html/backend/src/pkgs/api-router/utils/index.html +131 -0
  37. package/coverage/html/backend/src/pkgs/api-router/utils/ip.ts.html +361 -0
  38. package/coverage/html/backend/src/pkgs/data-model/fields/field-factory.ts.html +709 -0
  39. package/coverage/html/backend/src/pkgs/data-model/fields/id-generator.ts.html +256 -0
  40. package/coverage/html/backend/src/pkgs/data-model/fields/index.html +161 -0
  41. package/coverage/html/backend/src/pkgs/data-model/fields/superjson-utils.ts.html +136 -0
  42. package/coverage/html/backend/src/pkgs/data-model/fields/zod-fields.ts.html +496 -0
  43. package/coverage/html/backend/src/pkgs/data-model/hooks/create-hooks.ts.html +349 -0
  44. package/coverage/html/backend/src/pkgs/data-model/hooks/index.html +176 -0
  45. package/coverage/html/backend/src/pkgs/data-model/hooks/update-hooks.ts.html +358 -0
  46. package/coverage/html/backend/src/pkgs/data-model/hooks/update-many-hooks.ts.html +613 -0
  47. package/coverage/html/backend/src/pkgs/data-model/hooks/utils.ts.html +538 -0
  48. package/coverage/html/backend/src/pkgs/data-model/hooks/with-hooks-factory.ts.html +289 -0
  49. package/coverage/html/backend/src/pkgs/db-adapters/adapter-factory.ts.html +289 -0
  50. package/coverage/html/backend/src/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.ts.html +2203 -0
  51. package/coverage/html/backend/src/pkgs/db-adapters/adapters/drizzle-adapter/index.html +116 -0
  52. package/coverage/html/backend/src/pkgs/db-adapters/adapters/index.html +116 -0
  53. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/dialect.ts.html +670 -0
  54. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/index.html +131 -0
  55. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/kysely-adapter.ts.html +3634 -0
  56. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/tests/index.html +116 -0
  57. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.ts.html +1417 -0
  58. package/coverage/html/backend/src/pkgs/db-adapters/adapters/memory-adapter/index.html +116 -0
  59. package/coverage/html/backend/src/pkgs/db-adapters/adapters/memory-adapter/memory-adapter.ts.html +2071 -0
  60. package/coverage/html/backend/src/pkgs/db-adapters/adapters/prisma-adapter/index.html +116 -0
  61. package/coverage/html/backend/src/pkgs/db-adapters/adapters/prisma-adapter/prisma-adapter.ts.html +1834 -0
  62. package/coverage/html/backend/src/pkgs/db-adapters/adapters/test.ts.html +316 -0
  63. package/coverage/html/backend/src/pkgs/db-adapters/index.html +131 -0
  64. package/coverage/html/backend/src/pkgs/db-adapters/utils.ts.html +238 -0
  65. package/coverage/html/backend/src/pkgs/migrations/get-migration.ts.html +343 -0
  66. package/coverage/html/backend/src/pkgs/migrations/get-schema/get-schema.ts.html +217 -0
  67. package/coverage/html/backend/src/pkgs/migrations/get-schema/index.html +146 -0
  68. package/coverage/html/backend/src/pkgs/migrations/get-schema/process-fields.ts.html +280 -0
  69. package/coverage/html/backend/src/pkgs/migrations/get-schema/process-tables.ts.html +289 -0
  70. package/coverage/html/backend/src/pkgs/migrations/index.html +176 -0
  71. package/coverage/html/backend/src/pkgs/migrations/migration-builders.ts.html +595 -0
  72. package/coverage/html/backend/src/pkgs/migrations/migration-execution.ts.html +301 -0
  73. package/coverage/html/backend/src/pkgs/migrations/schema-comparison.ts.html +694 -0
  74. package/coverage/html/backend/src/pkgs/migrations/type-mapping.ts.html +817 -0
  75. package/coverage/html/backend/src/pkgs/results/core/error-class.ts.html +976 -0
  76. package/coverage/html/backend/src/pkgs/results/core/error-codes.ts.html +703 -0
  77. package/coverage/html/backend/src/pkgs/results/core/index.html +146 -0
  78. package/coverage/html/backend/src/pkgs/results/core/tracing.ts.html +280 -0
  79. package/coverage/html/backend/src/pkgs/results/create-telemetry-options.ts.html +271 -0
  80. package/coverage/html/backend/src/pkgs/results/index.html +131 -0
  81. package/coverage/html/backend/src/pkgs/results/orpc-error-handler.ts.html +496 -0
  82. package/coverage/html/backend/src/pkgs/results/results/index.html +131 -0
  83. package/coverage/html/backend/src/pkgs/results/results/recovery-utils.ts.html +628 -0
  84. package/coverage/html/backend/src/pkgs/results/results/result-helpers.ts.html +1234 -0
  85. package/coverage/html/backend/src/pkgs/utils/env.ts.html +337 -0
  86. package/coverage/html/backend/src/pkgs/utils/index.html +146 -0
  87. package/coverage/html/backend/src/pkgs/utils/logger.ts.html +199 -0
  88. package/coverage/html/backend/src/pkgs/utils/url.ts.html +400 -0
  89. package/coverage/html/backend/src/router.ts.html +109 -0
  90. package/coverage/html/backend/src/schema/audit-log/index.html +146 -0
  91. package/coverage/html/backend/src/schema/audit-log/registry.ts.html +436 -0
  92. package/coverage/html/backend/src/schema/audit-log/schema.ts.html +223 -0
  93. package/coverage/html/backend/src/schema/audit-log/table.ts.html +640 -0
  94. package/coverage/html/backend/src/schema/consent/index.html +146 -0
  95. package/coverage/html/backend/src/schema/consent/registry.ts.html +616 -0
  96. package/coverage/html/backend/src/schema/consent/schema.ts.html +238 -0
  97. package/coverage/html/backend/src/schema/consent/table.ts.html +748 -0
  98. package/coverage/html/backend/src/schema/consent-policy/index.html +146 -0
  99. package/coverage/html/backend/src/schema/consent-policy/registry.ts.html +1063 -0
  100. package/coverage/html/backend/src/schema/consent-policy/schema.ts.html +265 -0
  101. package/coverage/html/backend/src/schema/consent-policy/table.ts.html +535 -0
  102. package/coverage/html/backend/src/schema/consent-purpose/index.html +146 -0
  103. package/coverage/html/backend/src/schema/consent-purpose/registry.ts.html +589 -0
  104. package/coverage/html/backend/src/schema/consent-purpose/schema.ts.html +259 -0
  105. package/coverage/html/backend/src/schema/consent-purpose/table.ts.html +547 -0
  106. package/coverage/html/backend/src/schema/consent-record/index.html +131 -0
  107. package/coverage/html/backend/src/schema/consent-record/schema.ts.html +211 -0
  108. package/coverage/html/backend/src/schema/consent-record/table.ts.html +457 -0
  109. package/coverage/html/backend/src/schema/create-registry.ts.html +148 -0
  110. package/coverage/html/backend/src/schema/definition.ts.html +685 -0
  111. package/coverage/html/backend/src/schema/domain/index.html +146 -0
  112. package/coverage/html/backend/src/schema/domain/registry.ts.html +973 -0
  113. package/coverage/html/backend/src/schema/domain/schema.ts.html +214 -0
  114. package/coverage/html/backend/src/schema/domain/table.ts.html +496 -0
  115. package/coverage/html/backend/src/schema/index.html +146 -0
  116. package/coverage/html/backend/src/schema/schemas.ts.html +166 -0
  117. package/coverage/html/backend/src/schema/subject/index.html +146 -0
  118. package/coverage/html/backend/src/schema/subject/registry.ts.html +973 -0
  119. package/coverage/html/backend/src/schema/subject/schema.ts.html +208 -0
  120. package/coverage/html/backend/src/schema/subject/table.ts.html +499 -0
  121. package/coverage/html/backend/src/server.ts.html +475 -0
  122. package/coverage/html/backend/src/testing/contract-testing.ts.html +1348 -0
  123. package/coverage/html/backend/src/testing/index.html +116 -0
  124. package/coverage/html/base.css +224 -0
  125. package/coverage/html/block-navigation.js +87 -0
  126. package/coverage/html/favicon.png +0 -0
  127. package/coverage/html/index.html +626 -0
  128. package/coverage/html/prettify.css +1 -0
  129. package/coverage/html/prettify.js +2 -0
  130. package/coverage/html/sort-arrow-sprite.png +0 -0
  131. package/coverage/html/sorter.js +196 -0
  132. package/dist/contracts/consent/index.d.ts +401 -0
  133. package/dist/contracts/consent/index.d.ts.map +1 -0
  134. package/dist/contracts/consent/index.test.d.ts +2 -0
  135. package/dist/contracts/consent/index.test.d.ts.map +1 -0
  136. package/dist/contracts/consent/post.contract.d.ts +212 -0
  137. package/dist/contracts/consent/post.contract.d.ts.map +1 -0
  138. package/dist/contracts/consent/post.contract.test.d.ts +2 -0
  139. package/dist/contracts/consent/post.contract.test.d.ts.map +1 -0
  140. package/dist/contracts/consent/show-banner.contract.d.ts +45 -0
  141. package/dist/contracts/consent/show-banner.contract.d.ts.map +1 -0
  142. package/dist/contracts/consent/show-banner.contract.test.d.ts +2 -0
  143. package/dist/contracts/consent/show-banner.contract.test.d.ts.map +1 -0
  144. package/dist/contracts/consent/verify.contract.d.ts +147 -0
  145. package/dist/contracts/consent/verify.contract.d.ts.map +1 -0
  146. package/dist/contracts/consent/verify.contract.test.d.ts +2 -0
  147. package/dist/contracts/consent/verify.contract.test.d.ts.map +1 -0
  148. package/dist/contracts/index.d.ts +963 -0
  149. package/dist/contracts/index.d.ts.map +1 -0
  150. package/dist/contracts/meta/index.d.ts +78 -0
  151. package/dist/contracts/meta/index.d.ts.map +1 -0
  152. package/dist/contracts/meta/index.test.d.ts +2 -0
  153. package/dist/contracts/meta/index.test.d.ts.map +1 -0
  154. package/dist/contracts/meta/status.contract.d.ts +77 -0
  155. package/dist/contracts/meta/status.contract.d.ts.map +1 -0
  156. package/dist/contracts/meta/status.contract.test.d.ts +2 -0
  157. package/dist/contracts/meta/status.contract.test.d.ts.map +1 -0
  158. package/dist/contracts/shared/jurisdiction.schema.d.ts +24 -0
  159. package/dist/contracts/shared/jurisdiction.schema.d.ts.map +1 -0
  160. package/dist/core.cjs +3584 -0
  161. package/dist/core.d.ts +533 -76
  162. package/dist/core.d.ts.map +1 -1
  163. package/dist/{index.js → core.js} +1163 -1286
  164. package/dist/handlers/consent/index.d.ts +401 -0
  165. package/dist/handlers/consent/index.d.ts.map +1 -0
  166. package/dist/handlers/consent/post.handler.d.ts +234 -0
  167. package/dist/handlers/consent/post.handler.d.ts.map +1 -0
  168. package/dist/handlers/consent/show-banner.handler.d.ts +57 -0
  169. package/dist/handlers/consent/show-banner.handler.d.ts.map +1 -0
  170. package/dist/handlers/consent/show-banner.handler.test.d.ts +2 -0
  171. package/dist/handlers/consent/show-banner.handler.test.d.ts.map +1 -0
  172. package/dist/handlers/consent/verify.handler.d.ts +169 -0
  173. package/dist/handlers/consent/verify.handler.d.ts.map +1 -0
  174. package/dist/handlers/meta/index.d.ts +78 -0
  175. package/dist/handlers/meta/index.d.ts.map +1 -0
  176. package/dist/handlers/meta/status.handler.d.ts +76 -0
  177. package/dist/handlers/meta/status.handler.d.ts.map +1 -0
  178. package/dist/init.d.ts.map +1 -1
  179. package/dist/pkgs/api-router/hooks/processor.d.ts.map +1 -1
  180. package/dist/pkgs/api-router/types/router-props.d.ts +1 -1
  181. package/dist/pkgs/api-router/types/router-props.d.ts.map +1 -1
  182. package/dist/pkgs/api-router/utils/cors.d.ts +1 -1
  183. package/dist/pkgs/api-router/utils/cors.d.ts.map +1 -1
  184. package/dist/pkgs/data-model/fields/field-types.d.ts +1 -1
  185. package/dist/pkgs/data-model/fields/zod-fields.d.ts +32 -32
  186. package/dist/pkgs/data-model/index.cjs +1433 -1799
  187. package/dist/pkgs/data-model/index.js +20 -385
  188. package/dist/pkgs/data-model/schema/index.cjs +1402 -1768
  189. package/dist/pkgs/data-model/schema/index.js +20 -385
  190. package/dist/pkgs/db-adapters/adapter-factory.d.ts +2 -2
  191. package/dist/pkgs/db-adapters/adapter-factory.d.ts.map +1 -1
  192. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.d.ts +4 -4
  193. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/index.cjs +19 -151
  194. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/index.js +19 -151
  195. package/dist/pkgs/db-adapters/adapters/kysely-adapter/dialect.d.ts +1 -1
  196. package/dist/pkgs/db-adapters/adapters/kysely-adapter/index.cjs +17 -149
  197. package/dist/pkgs/db-adapters/adapters/kysely-adapter/index.js +17 -149
  198. package/dist/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.d.ts +2 -2
  199. package/dist/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.d.ts.map +1 -1
  200. package/dist/pkgs/db-adapters/adapters/memory-adapter/index.cjs +17 -149
  201. package/dist/pkgs/db-adapters/adapters/memory-adapter/index.js +17 -149
  202. package/dist/pkgs/db-adapters/adapters/prisma-adapter/index.cjs +19 -151
  203. package/dist/pkgs/db-adapters/adapters/prisma-adapter/index.js +19 -151
  204. package/dist/pkgs/db-adapters/index.cjs +31 -153
  205. package/dist/pkgs/db-adapters/index.js +31 -153
  206. package/dist/pkgs/migrations/get-schema/get-schema.d.ts +2 -2
  207. package/dist/pkgs/migrations/get-schema/index.d.ts +1 -1
  208. package/dist/pkgs/migrations/index.cjs +30 -153
  209. package/dist/pkgs/migrations/index.js +30 -153
  210. package/dist/pkgs/migrations/schema-comparison.d.ts.map +1 -1
  211. package/dist/pkgs/results/core/error-class.d.ts +23 -21
  212. package/dist/pkgs/results/core/error-class.d.ts.map +1 -1
  213. package/dist/pkgs/results/index.cjs +17 -150
  214. package/dist/pkgs/results/index.d.ts +0 -3
  215. package/dist/pkgs/results/index.d.ts.map +1 -1
  216. package/dist/pkgs/results/index.js +17 -138
  217. package/dist/pkgs/results/orpc-error-handler.d.ts +65 -0
  218. package/dist/pkgs/results/orpc-error-handler.d.ts.map +1 -0
  219. package/dist/pkgs/results/types.d.ts +7 -7
  220. package/dist/pkgs/results/types.d.ts.map +1 -1
  221. package/dist/pkgs/types/context.d.ts +15 -4
  222. package/dist/pkgs/types/context.d.ts.map +1 -1
  223. package/dist/pkgs/types/endpoints.d.ts +3 -4
  224. package/dist/pkgs/types/endpoints.d.ts.map +1 -1
  225. package/dist/pkgs/types/options.d.ts +2 -3
  226. package/dist/pkgs/types/options.d.ts.map +1 -1
  227. package/dist/pkgs/types/plugins.d.ts +2 -3
  228. package/dist/pkgs/types/plugins.d.ts.map +1 -1
  229. package/dist/pkgs/utils/index.d.ts +1 -0
  230. package/dist/pkgs/utils/index.d.ts.map +1 -1
  231. package/dist/pkgs/utils/logger.d.ts +16 -0
  232. package/dist/pkgs/utils/logger.d.ts.map +1 -0
  233. package/dist/router.cjs +1213 -0
  234. package/dist/router.d.ts +480 -0
  235. package/dist/router.d.ts.map +1 -0
  236. package/dist/router.js +1169 -0
  237. package/dist/schema/audit-log/table.d.ts +1 -1
  238. package/dist/schema/consent/table.d.ts +1 -1
  239. package/dist/schema/consent-policy/registry.d.ts +12 -12
  240. package/dist/schema/consent-policy/schema.d.ts +6 -6
  241. package/dist/schema/consent-policy/table.d.ts +7 -7
  242. package/dist/schema/consent-purpose/registry.d.ts +6 -6
  243. package/dist/schema/consent-purpose/schema.d.ts +6 -6
  244. package/dist/schema/consent-purpose/table.d.ts +7 -7
  245. package/dist/schema/consent-record/table.d.ts +1 -1
  246. package/dist/schema/create-registry.d.ts +32 -32
  247. package/dist/schema/definition.d.ts +19 -19
  248. package/dist/schema/domain/registry.d.ts +10 -10
  249. package/dist/schema/domain/schema.d.ts +5 -5
  250. package/dist/schema/domain/table.d.ts +6 -6
  251. package/dist/schema/index.cjs +1409 -1775
  252. package/dist/schema/index.js +20 -385
  253. package/dist/schema/schemas.d.ts +19 -19
  254. package/dist/schema/subject/registry.d.ts +4 -4
  255. package/dist/schema/subject/schema.d.ts +2 -2
  256. package/dist/schema/subject/table.d.ts +3 -3
  257. package/dist/server.d.ts +2 -0
  258. package/dist/server.d.ts.map +1 -0
  259. package/dist/testing/contract-testing.d.ts +37 -0
  260. package/dist/testing/contract-testing.d.ts.map +1 -0
  261. package/dist/types/context.d.ts +1 -1
  262. package/dist/types/index.d.ts +2 -2
  263. package/dist/types/options.d.ts +33 -2
  264. package/dist/types/options.d.ts.map +1 -1
  265. package/dist/types/plugins.d.ts +3 -4
  266. package/dist/types/plugins.d.ts.map +1 -1
  267. package/package.json +22 -30
  268. package/rslib.config.ts +2 -5
  269. package/src/contracts/consent/index.test.ts +5 -0
  270. package/src/contracts/consent/index.ts +9 -0
  271. package/src/contracts/consent/post.contract.test.ts +526 -0
  272. package/src/contracts/consent/post.contract.ts +160 -0
  273. package/src/contracts/consent/show-banner.contract.test.ts +214 -0
  274. package/src/contracts/consent/show-banner.contract.ts +45 -0
  275. package/src/contracts/consent/verify.contract.test.ts +185 -0
  276. package/src/contracts/consent/verify.contract.ts +126 -0
  277. package/src/contracts/index.ts +18 -0
  278. package/src/contracts/meta/index.test.ts +5 -0
  279. package/src/contracts/meta/index.ts +5 -0
  280. package/src/contracts/meta/status.contract.test.ts +338 -0
  281. package/src/contracts/meta/status.contract.ts +37 -0
  282. package/src/contracts/shared/jurisdiction.schema.ts +30 -0
  283. package/src/core.ts +451 -159
  284. package/src/handlers/consent/index.ts +9 -0
  285. package/src/handlers/consent/post.handler.ts +273 -0
  286. package/src/handlers/consent/show-banner.handler.test.ts +148 -0
  287. package/src/handlers/consent/show-banner.handler.ts +150 -0
  288. package/src/handlers/consent/verify.handler.ts +305 -0
  289. package/src/handlers/meta/index.ts +5 -0
  290. package/src/handlers/meta/status.handler.ts +47 -0
  291. package/src/init.ts +8 -5
  292. package/src/pkgs/api-router/hooks/__tests__/processor.test.ts +6 -0
  293. package/src/pkgs/api-router/hooks/processor.ts +2 -0
  294. package/src/pkgs/api-router/types/router-props.ts +1 -1
  295. package/src/pkgs/api-router/utils/cors.ts +1 -1
  296. package/src/pkgs/data-model/fields/field-types.ts +1 -1
  297. package/src/pkgs/data-model/fields/id-generator.ts +1 -1
  298. package/src/pkgs/db-adapters/README.md +3 -3
  299. package/src/pkgs/db-adapters/adapter-factory.ts +8 -4
  300. package/src/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.ts +13 -13
  301. package/src/pkgs/db-adapters/adapters/kysely-adapter/dialect.ts +1 -1
  302. package/src/pkgs/db-adapters/adapters/kysely-adapter/tests/postgres.test.ts +1 -1
  303. package/src/pkgs/db-adapters/adapters/kysely-adapter/tests/sqlite.test.ts +1 -1
  304. package/src/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.ts +2 -2
  305. package/src/pkgs/migrations/get-migration.ts +3 -3
  306. package/src/pkgs/migrations/get-schema/get-schema.ts +2 -2
  307. package/src/pkgs/migrations/get-schema/index.ts +1 -1
  308. package/src/pkgs/migrations/migration-builders.ts +2 -2
  309. package/src/pkgs/migrations/migration-execution.ts +2 -2
  310. package/src/pkgs/migrations/schema-comparison.ts +5 -4
  311. package/src/pkgs/results/__tests__/error-class.test.ts +8 -7
  312. package/src/pkgs/results/core/error-class.ts +31 -43
  313. package/src/pkgs/results/index.ts +0 -10
  314. package/src/pkgs/results/orpc-error-handler.ts +137 -0
  315. package/src/pkgs/results/types.ts +8 -7
  316. package/src/pkgs/types/context.ts +18 -4
  317. package/src/pkgs/types/endpoints.ts +3 -5
  318. package/src/pkgs/types/options.ts +2 -3
  319. package/src/pkgs/types/plugins.ts +2 -3
  320. package/src/pkgs/utils/index.ts +1 -0
  321. package/src/pkgs/utils/logger.ts +38 -0
  322. package/src/router.ts +8 -0
  323. package/src/schema/audit-log/table.ts +1 -1
  324. package/src/schema/consent/table.ts +1 -1
  325. package/src/schema/consent-policy/table.ts +1 -1
  326. package/src/schema/consent-purpose/table.ts +1 -1
  327. package/src/schema/consent-record/table.ts +1 -1
  328. package/src/schema/definition.ts +2 -2
  329. package/src/schema/domain/table.ts +1 -1
  330. package/src/schema/subject/table.ts +1 -1
  331. package/src/server.ts +130 -0
  332. package/src/testing/contract-testing.ts +437 -0
  333. package/src/types/context.ts +1 -1
  334. package/src/types/index.ts +2 -2
  335. package/src/types/options.ts +38 -2
  336. package/src/types/plugins.ts +3 -4
  337. package/dist/index.cjs +0 -3701
  338. package/dist/index.d.ts +0 -11
  339. package/dist/index.d.ts.map +0 -1
  340. package/dist/init.test.d.ts +0 -2
  341. package/dist/init.test.d.ts.map +0 -1
  342. package/dist/integrations/cloudflare.cjs +0 -312
  343. package/dist/integrations/cloudflare.d.ts +0 -32
  344. package/dist/integrations/cloudflare.d.ts.map +0 -1
  345. package/dist/integrations/cloudflare.js +0 -278
  346. package/dist/integrations/next.cjs +0 -276
  347. package/dist/integrations/next.d.ts +0 -68
  348. package/dist/integrations/next.d.ts.map +0 -1
  349. package/dist/integrations/next.js +0 -239
  350. package/dist/integrations/node.cjs +0 -257
  351. package/dist/integrations/node.d.ts +0 -29
  352. package/dist/integrations/node.d.ts.map +0 -1
  353. package/dist/integrations/node.js +0 -223
  354. package/dist/pkgs/api-router/index.d.ts +0 -9
  355. package/dist/pkgs/api-router/index.d.ts.map +0 -1
  356. package/dist/pkgs/api-router/utils/define-route.d.ts +0 -87
  357. package/dist/pkgs/api-router/utils/define-route.d.ts.map +0 -1
  358. package/dist/pkgs/logger/__tests__/console-formatter.test.d.ts +0 -2
  359. package/dist/pkgs/logger/__tests__/console-formatter.test.d.ts.map +0 -1
  360. package/dist/pkgs/logger/__tests__/integration.test.d.ts +0 -2
  361. package/dist/pkgs/logger/__tests__/integration.test.d.ts.map +0 -1
  362. package/dist/pkgs/logger/__tests__/log-levels.test.d.ts +0 -2
  363. package/dist/pkgs/logger/__tests__/log-levels.test.d.ts.map +0 -1
  364. package/dist/pkgs/logger/__tests__/logger-factory.test.d.ts +0 -2
  365. package/dist/pkgs/logger/__tests__/logger-factory.test.d.ts.map +0 -1
  366. package/dist/pkgs/logger/__tests__/result-logging.test.d.ts +0 -2
  367. package/dist/pkgs/logger/__tests__/result-logging.test.d.ts.map +0 -1
  368. package/dist/pkgs/logger/__tests__/types.test.d.ts +0 -2
  369. package/dist/pkgs/logger/__tests__/types.test.d.ts.map +0 -1
  370. package/dist/pkgs/logger/console-formatter.d.ts +0 -56
  371. package/dist/pkgs/logger/console-formatter.d.ts.map +0 -1
  372. package/dist/pkgs/logger/index.cjs +0 -240
  373. package/dist/pkgs/logger/index.d.ts +0 -35
  374. package/dist/pkgs/logger/index.d.ts.map +0 -1
  375. package/dist/pkgs/logger/index.js +0 -185
  376. package/dist/pkgs/logger/log-levels.d.ts +0 -29
  377. package/dist/pkgs/logger/log-levels.d.ts.map +0 -1
  378. package/dist/pkgs/logger/logger-factory.d.ts +0 -42
  379. package/dist/pkgs/logger/logger-factory.d.ts.map +0 -1
  380. package/dist/pkgs/logger/result-logging.d.ts +0 -71
  381. package/dist/pkgs/logger/result-logging.d.ts.map +0 -1
  382. package/dist/pkgs/logger/telemetry.d.ts +0 -14
  383. package/dist/pkgs/logger/telemetry.d.ts.map +0 -1
  384. package/dist/pkgs/logger/types.d.ts +0 -121
  385. package/dist/pkgs/logger/types.d.ts.map +0 -1
  386. package/dist/pkgs/results/__tests__/retrieval-pipeline.test.d.ts +0 -2
  387. package/dist/pkgs/results/__tests__/retrieval-pipeline.test.d.ts.map +0 -1
  388. package/dist/pkgs/results/__tests__/validation-pipeline.test.d.ts +0 -2
  389. package/dist/pkgs/results/__tests__/validation-pipeline.test.d.ts.map +0 -1
  390. package/dist/pkgs/results/h3-integration.d.ts +0 -52
  391. package/dist/pkgs/results/h3-integration.d.ts.map +0 -1
  392. package/dist/pkgs/results/pipeline/retrieval-pipeline.d.ts +0 -101
  393. package/dist/pkgs/results/pipeline/retrieval-pipeline.d.ts.map +0 -1
  394. package/dist/pkgs/results/pipeline/validation-pipeline.d.ts +0 -89
  395. package/dist/pkgs/results/pipeline/validation-pipeline.d.ts.map +0 -1
  396. package/dist/response-types.d.ts +0 -19
  397. package/dist/response-types.d.ts.map +0 -1
  398. package/dist/routes/__test__/index.test.d.ts +0 -17
  399. package/dist/routes/__test__/index.test.d.ts.map +0 -1
  400. package/dist/routes/__test__/set-consent.test.d.ts +0 -2
  401. package/dist/routes/__test__/set-consent.test.d.ts.map +0 -1
  402. package/dist/routes/__test__/show-consent-banner.test.d.ts +0 -2
  403. package/dist/routes/__test__/show-consent-banner.test.d.ts.map +0 -1
  404. package/dist/routes/__test__/status.test.d.ts +0 -2
  405. package/dist/routes/__test__/status.test.d.ts.map +0 -1
  406. package/dist/routes/__test__/verify-consent.test.d.ts +0 -2
  407. package/dist/routes/__test__/verify-consent.test.d.ts.map +0 -1
  408. package/dist/routes/index.d.ts +0 -3
  409. package/dist/routes/index.d.ts.map +0 -1
  410. package/dist/routes/set-consent.d.ts +0 -89
  411. package/dist/routes/set-consent.d.ts.map +0 -1
  412. package/dist/routes/show-consent-banner.d.ts +0 -15
  413. package/dist/routes/show-consent-banner.d.ts.map +0 -1
  414. package/dist/routes/status.d.ts +0 -44
  415. package/dist/routes/status.d.ts.map +0 -1
  416. package/dist/routes/types.d.ts +0 -7
  417. package/dist/routes/types.d.ts.map +0 -1
  418. package/dist/routes/verify-consent.d.ts +0 -38
  419. package/dist/routes/verify-consent.d.ts.map +0 -1
  420. package/src/docs/ADVANCED_JSON_HANDLING.md +0 -99
  421. package/src/docs/neverthrow.md +0 -171
  422. package/src/index.ts +0 -34
  423. package/src/init.test.ts +0 -219
  424. package/src/integrations/cloudflare.ts +0 -269
  425. package/src/integrations/next.ts +0 -204
  426. package/src/integrations/node.ts +0 -141
  427. package/src/pkgs/api-router/index.ts +0 -148
  428. package/src/pkgs/api-router/types/h3.d.ts +0 -42
  429. package/src/pkgs/api-router/utils/define-route.ts +0 -410
  430. package/src/pkgs/logger/README.md +0 -213
  431. package/src/pkgs/logger/__tests__/console-formatter.test.ts +0 -67
  432. package/src/pkgs/logger/__tests__/integration.test.ts +0 -184
  433. package/src/pkgs/logger/__tests__/log-levels.test.ts +0 -77
  434. package/src/pkgs/logger/__tests__/logger-factory.test.ts +0 -156
  435. package/src/pkgs/logger/__tests__/result-logging.test.ts +0 -209
  436. package/src/pkgs/logger/__tests__/types.test.ts +0 -94
  437. package/src/pkgs/logger/console-formatter.ts +0 -75
  438. package/src/pkgs/logger/doc.md +0 -569
  439. package/src/pkgs/logger/index.ts +0 -59
  440. package/src/pkgs/logger/log-levels.ts +0 -46
  441. package/src/pkgs/logger/logger-factory.ts +0 -121
  442. package/src/pkgs/logger/result-logging.ts +0 -134
  443. package/src/pkgs/logger/telemetry.ts +0 -96
  444. package/src/pkgs/logger/types.ts +0 -138
  445. package/src/pkgs/results/__tests__/retrieval-pipeline.test.ts +0 -157
  446. package/src/pkgs/results/__tests__/validation-pipeline.test.ts +0 -151
  447. package/src/pkgs/results/h3-integration.ts +0 -142
  448. package/src/pkgs/results/pipeline/retrieval-pipeline.ts +0 -188
  449. package/src/pkgs/results/pipeline/validation-pipeline.ts +0 -164
  450. package/src/plugins/.keep +0 -0
  451. package/src/response-types.ts +0 -29
  452. package/src/routes/__test__/index.test.ts +0 -112
  453. package/src/routes/__test__/set-consent.test.ts +0 -242
  454. package/src/routes/__test__/show-consent-banner.test.ts +0 -98
  455. package/src/routes/__test__/status.test.ts +0 -64
  456. package/src/routes/__test__/verify-consent.test.ts +0 -266
  457. package/src/routes/index.ts +0 -12
  458. package/src/routes/set-consent.ts +0 -249
  459. package/src/routes/show-consent-banner.ts +0 -131
  460. package/src/routes/status.ts +0 -61
  461. package/src/routes/types.ts +0 -7
  462. package/src/routes/verify-consent.ts +0 -206
@@ -1,236 +1,5 @@
1
1
  "use strict";
2
- var __webpack_modules__ = {
3
- "../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/ZodError.js": function(__unused_webpack_module, exports1, __webpack_require__) {
4
- exports1.ZodError = void 0;
5
- const util_1 = __webpack_require__("../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/helpers/util.js");
6
- util_1.util.arrayToEnum([
7
- "invalid_type",
8
- "invalid_literal",
9
- "custom",
10
- "invalid_union",
11
- "invalid_union_discriminator",
12
- "invalid_enum_value",
13
- "unrecognized_keys",
14
- "invalid_arguments",
15
- "invalid_return_type",
16
- "invalid_date",
17
- "invalid_string",
18
- "too_small",
19
- "too_big",
20
- "invalid_intersection_types",
21
- "not_multiple_of",
22
- "not_finite"
23
- ]);
24
- class ZodError extends Error {
25
- get errors() {
26
- return this.issues;
27
- }
28
- constructor(issues){
29
- super();
30
- this.issues = [];
31
- this.addIssue = (sub)=>{
32
- this.issues = [
33
- ...this.issues,
34
- sub
35
- ];
36
- };
37
- this.addIssues = (subs = [])=>{
38
- this.issues = [
39
- ...this.issues,
40
- ...subs
41
- ];
42
- };
43
- const actualProto = new.target.prototype;
44
- if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
45
- else this.__proto__ = actualProto;
46
- this.name = "ZodError";
47
- this.issues = issues;
48
- }
49
- format(_mapper) {
50
- const mapper = _mapper || function(issue) {
51
- return issue.message;
52
- };
53
- const fieldErrors = {
54
- _errors: []
55
- };
56
- const processError = (error)=>{
57
- for (const issue of error.issues)if ("invalid_union" === issue.code) issue.unionErrors.map(processError);
58
- else if ("invalid_return_type" === issue.code) processError(issue.returnTypeError);
59
- else if ("invalid_arguments" === issue.code) processError(issue.argumentsError);
60
- else if (0 === issue.path.length) fieldErrors._errors.push(mapper(issue));
61
- else {
62
- let curr = fieldErrors;
63
- let i = 0;
64
- while(i < issue.path.length){
65
- const el = issue.path[i];
66
- const terminal = i === issue.path.length - 1;
67
- if (terminal) {
68
- curr[el] = curr[el] || {
69
- _errors: []
70
- };
71
- curr[el]._errors.push(mapper(issue));
72
- } else curr[el] = curr[el] || {
73
- _errors: []
74
- };
75
- curr = curr[el];
76
- i++;
77
- }
78
- }
79
- };
80
- processError(this);
81
- return fieldErrors;
82
- }
83
- static assert(value) {
84
- if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
85
- }
86
- toString() {
87
- return this.message;
88
- }
89
- get message() {
90
- return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2);
91
- }
92
- get isEmpty() {
93
- return 0 === this.issues.length;
94
- }
95
- flatten(mapper = (issue)=>issue.message) {
96
- const fieldErrors = {};
97
- const formErrors = [];
98
- for (const sub of this.issues)if (sub.path.length > 0) {
99
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
100
- fieldErrors[sub.path[0]].push(mapper(sub));
101
- } else formErrors.push(mapper(sub));
102
- return {
103
- formErrors,
104
- fieldErrors
105
- };
106
- }
107
- get formErrors() {
108
- return this.flatten();
109
- }
110
- }
111
- exports1.ZodError = ZodError;
112
- ZodError.create = (issues)=>{
113
- const error = new ZodError(issues);
114
- return error;
115
- };
116
- },
117
- "../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/helpers/util.js": function(__unused_webpack_module, exports1) {
118
- Object.defineProperty(exports1, "__esModule", {
119
- value: true
120
- });
121
- exports1.getParsedType = exports1.ZodParsedType = exports1.objectUtil = exports1.util = void 0;
122
- var util;
123
- (function(util) {
124
- util.assertEqual = (val)=>val;
125
- function assertIs(_arg) {}
126
- util.assertIs = assertIs;
127
- function assertNever(_x) {
128
- throw new Error();
129
- }
130
- util.assertNever = assertNever;
131
- util.arrayToEnum = (items)=>{
132
- const obj = {};
133
- for (const item of items)obj[item] = item;
134
- return obj;
135
- };
136
- util.getValidEnumValues = (obj)=>{
137
- const validKeys = util.objectKeys(obj).filter((k)=>"number" != typeof obj[obj[k]]);
138
- const filtered = {};
139
- for (const k of validKeys)filtered[k] = obj[k];
140
- return util.objectValues(filtered);
141
- };
142
- util.objectValues = (obj)=>util.objectKeys(obj).map(function(e) {
143
- return obj[e];
144
- });
145
- util.objectKeys = "function" == typeof Object.keys ? (obj)=>Object.keys(obj) : (object)=>{
146
- const keys = [];
147
- for(const key in object)if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
148
- return keys;
149
- };
150
- util.find = (arr, checker)=>{
151
- for (const item of arr)if (checker(item)) return item;
152
- };
153
- util.isInteger = "function" == typeof Number.isInteger ? (val)=>Number.isInteger(val) : (val)=>"number" == typeof val && isFinite(val) && Math.floor(val) === val;
154
- function joinValues(array, separator = " | ") {
155
- return array.map((val)=>"string" == typeof val ? `'${val}'` : val).join(separator);
156
- }
157
- util.joinValues = joinValues;
158
- util.jsonStringifyReplacer = (_, value)=>{
159
- if ("bigint" == typeof value) return value.toString();
160
- return value;
161
- };
162
- })(util || (exports1.util = util = {}));
163
- var objectUtil;
164
- (function(objectUtil) {
165
- objectUtil.mergeShapes = (first, second)=>({
166
- ...first,
167
- ...second
168
- });
169
- })(objectUtil || (exports1.objectUtil = objectUtil = {}));
170
- exports1.ZodParsedType = util.arrayToEnum([
171
- "string",
172
- "nan",
173
- "number",
174
- "integer",
175
- "float",
176
- "boolean",
177
- "date",
178
- "bigint",
179
- "symbol",
180
- "function",
181
- "undefined",
182
- "null",
183
- "array",
184
- "object",
185
- "unknown",
186
- "promise",
187
- "void",
188
- "never",
189
- "map",
190
- "set"
191
- ]);
192
- const getParsedType = (data)=>{
193
- const t = typeof data;
194
- switch(t){
195
- case "undefined":
196
- return exports1.ZodParsedType.undefined;
197
- case "string":
198
- return exports1.ZodParsedType.string;
199
- case "number":
200
- return isNaN(data) ? exports1.ZodParsedType.nan : exports1.ZodParsedType.number;
201
- case "boolean":
202
- return exports1.ZodParsedType.boolean;
203
- case "function":
204
- return exports1.ZodParsedType.function;
205
- case "bigint":
206
- return exports1.ZodParsedType.bigint;
207
- case "symbol":
208
- return exports1.ZodParsedType.symbol;
209
- case "object":
210
- if (Array.isArray(data)) return exports1.ZodParsedType.array;
211
- if (null === data) return exports1.ZodParsedType.null;
212
- if (data.then && "function" == typeof data.then && data.catch && "function" == typeof data.catch) return exports1.ZodParsedType.promise;
213
- if ("undefined" != typeof Map && data instanceof Map) return exports1.ZodParsedType.map;
214
- if ("undefined" != typeof Set && data instanceof Set) return exports1.ZodParsedType.set;
215
- if ("undefined" != typeof Date && data instanceof Date) return exports1.ZodParsedType.date;
216
- return exports1.ZodParsedType.object;
217
- default:
218
- return exports1.ZodParsedType.unknown;
219
- }
220
- };
221
- exports1.getParsedType = getParsedType;
222
- }
223
- };
224
- var __webpack_module_cache__ = {};
225
- function __webpack_require__(moduleId) {
226
- var cachedModule = __webpack_module_cache__[moduleId];
227
- if (void 0 !== cachedModule) return cachedModule.exports;
228
- var module = __webpack_module_cache__[moduleId] = {
229
- exports: {}
230
- };
231
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
232
- return module.exports;
233
- }
2
+ var __webpack_require__ = {};
234
3
  (()=>{
235
4
  __webpack_require__.n = (module)=>{
236
5
  var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
@@ -262,1636 +31,1501 @@ function __webpack_require__(moduleId) {
262
31
  };
263
32
  })();
264
33
  var __webpack_exports__ = {};
265
- (()=>{
266
- __webpack_require__.r(__webpack_exports__);
267
- __webpack_require__.d(__webpack_exports__, {
268
- getConsentTable: ()=>getConsentTable,
269
- consentRegistry: ()=>consentRegistry,
270
- domainSchema: ()=>domainSchema,
271
- getDatabaseType: ()=>getDatabaseType,
272
- getSubjectTable: ()=>getSubjectTable,
273
- validateField: ()=>validateField,
274
- auditLogRegistry: ()=>auditLogRegistry,
275
- processAfterHooksForMany: ()=>processAfterHooksForMany,
276
- consentPolicySchema: ()=>consentPolicySchema,
277
- consentPurposeRegistry: ()=>consentPurposeRegistry,
278
- getConsentPolicyTable: ()=>getConsentPolicyTable,
279
- generateId: ()=>generateId,
280
- getDomainTable: ()=>getDomainTable,
281
- purposeSchema: ()=>purposeSchema,
282
- getAuditLogTable: ()=>getAuditLogTable,
283
- updateWithHooks: ()=>update_hooks_updateWithHooks,
284
- policyRegistry: ()=>policyRegistry,
285
- getPurposeTable: ()=>getPurposeTable,
286
- processHooks: ()=>processHooks,
287
- COMMON_TIMEZONES: ()=>COMMON_TIMEZONES,
288
- updateManyWithHooks: ()=>updateManyWithHooks,
289
- consentRecordSchema: ()=>consentRecordSchema,
290
- createWithHooks: ()=>create_hooks_createWithHooks,
291
- subjectRegistry: ()=>subjectRegistry,
292
- getWithHooks: ()=>getWithHooks,
293
- subjectSchema: ()=>subjectSchema,
294
- getConsentRecordTable: ()=>getConsentRecordTable,
295
- consentSchema: ()=>consentSchema,
296
- auditLogSchema: ()=>auditLogSchema,
297
- PolicyTypeSchema: ()=>PolicyTypeSchema,
298
- domainRegistry: ()=>domainRegistry
299
- });
300
- const COMMON_TIMEZONES = {
301
- UTC: 'UTC',
302
- GMT: 'GMT',
303
- EASTERN: 'America/New_York',
304
- CENTRAL: 'America/Chicago',
305
- MOUNTAIN: 'America/Denver',
306
- PACIFIC: 'America/Los_Angeles',
307
- LONDON: 'Europe/London',
308
- PARIS: 'Europe/Paris',
309
- BERLIN: 'Europe/Berlin',
310
- TOKYO: 'Asia/Tokyo',
311
- SHANGHAI: 'Asia/Shanghai',
312
- SINGAPORE: 'Asia/Singapore',
313
- SYDNEY: 'Australia/Sydney',
314
- SAO_PAULO: 'America/Sao_Paulo'
315
- };
316
- const external_base_x_namespaceObject = require("base-x");
317
- var external_base_x_default = /*#__PURE__*/ __webpack_require__.n(external_base_x_namespaceObject);
318
- const b58 = external_base_x_default()('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
319
- function generateId(prefix) {
320
- const buf = crypto.getRandomValues(new Uint8Array(20));
321
- const EPOCH_TIMESTAMP = 1700000000000;
322
- const t = Date.now() - EPOCH_TIMESTAMP;
323
- const high = Math.floor(t / 0x100000000);
324
- const low = t >>> 0;
325
- buf[0] = high >>> 24 & 255;
326
- buf[1] = high >>> 16 & 255;
327
- buf[2] = high >>> 8 & 255;
328
- buf[3] = 255 & high;
329
- buf[4] = low >>> 24 & 255;
330
- buf[5] = low >>> 16 & 255;
331
- buf[6] = low >>> 8 & 255;
332
- buf[7] = 255 & low;
333
- return `${prefix}_${b58.encode(buf)}`;
334
- }
335
- const currentDatabaseType = 'unknown';
336
- function getDatabaseType() {
337
- return currentDatabaseType;
338
- }
339
- const external_zod_namespaceObject = require("zod");
340
- const fieldConfigSchema = external_zod_namespaceObject.z.object({
341
- required: external_zod_namespaceObject.z.boolean().default(true),
342
- returned: external_zod_namespaceObject.z.boolean().default(true),
343
- input: external_zod_namespaceObject.z.boolean().default(true),
344
- defaultValue: external_zod_namespaceObject.z.union([
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ getConsentTable: ()=>getConsentTable,
37
+ consentRegistry: ()=>consentRegistry,
38
+ domainSchema: ()=>domainSchema,
39
+ getDatabaseType: ()=>getDatabaseType,
40
+ getSubjectTable: ()=>getSubjectTable,
41
+ validateField: ()=>validateField,
42
+ auditLogRegistry: ()=>auditLogRegistry,
43
+ processAfterHooksForMany: ()=>processAfterHooksForMany,
44
+ consentPolicySchema: ()=>consentPolicySchema,
45
+ consentPurposeRegistry: ()=>consentPurposeRegistry,
46
+ getConsentPolicyTable: ()=>getConsentPolicyTable,
47
+ generateId: ()=>generateId,
48
+ getDomainTable: ()=>getDomainTable,
49
+ purposeSchema: ()=>purposeSchema,
50
+ getAuditLogTable: ()=>getAuditLogTable,
51
+ updateWithHooks: ()=>update_hooks_updateWithHooks,
52
+ policyRegistry: ()=>policyRegistry,
53
+ getPurposeTable: ()=>getPurposeTable,
54
+ processHooks: ()=>processHooks,
55
+ COMMON_TIMEZONES: ()=>COMMON_TIMEZONES,
56
+ updateManyWithHooks: ()=>updateManyWithHooks,
57
+ consentRecordSchema: ()=>consentRecordSchema,
58
+ createWithHooks: ()=>create_hooks_createWithHooks,
59
+ subjectRegistry: ()=>subjectRegistry,
60
+ getWithHooks: ()=>getWithHooks,
61
+ subjectSchema: ()=>subjectSchema,
62
+ getConsentRecordTable: ()=>getConsentRecordTable,
63
+ consentSchema: ()=>consentSchema,
64
+ auditLogSchema: ()=>auditLogSchema,
65
+ PolicyTypeSchema: ()=>PolicyTypeSchema,
66
+ domainRegistry: ()=>domainRegistry
67
+ });
68
+ const COMMON_TIMEZONES = {
69
+ UTC: 'UTC',
70
+ GMT: 'GMT',
71
+ EASTERN: 'America/New_York',
72
+ CENTRAL: 'America/Chicago',
73
+ MOUNTAIN: 'America/Denver',
74
+ PACIFIC: 'America/Los_Angeles',
75
+ LONDON: 'Europe/London',
76
+ PARIS: 'Europe/Paris',
77
+ BERLIN: 'Europe/Berlin',
78
+ TOKYO: 'Asia/Tokyo',
79
+ SHANGHAI: 'Asia/Shanghai',
80
+ SINGAPORE: 'Asia/Singapore',
81
+ SYDNEY: 'Australia/Sydney',
82
+ SAO_PAULO: 'America/Sao_Paulo'
83
+ };
84
+ const external_base_x_namespaceObject = require("base-x");
85
+ var external_base_x_default = /*#__PURE__*/ __webpack_require__.n(external_base_x_namespaceObject);
86
+ const b58 = external_base_x_default()('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
87
+ function generateId(prefix) {
88
+ const buf = crypto.getRandomValues(new Uint8Array(20));
89
+ const EPOCH_TIMESTAMP = 1700000000000;
90
+ const t = Date.now() - EPOCH_TIMESTAMP;
91
+ const high = Math.floor(t / 0x100000000);
92
+ const low = t >>> 0;
93
+ buf[0] = high >>> 24 & 255;
94
+ buf[1] = high >>> 16 & 255;
95
+ buf[2] = high >>> 8 & 255;
96
+ buf[3] = 255 & high;
97
+ buf[4] = low >>> 24 & 255;
98
+ buf[5] = low >>> 16 & 255;
99
+ buf[6] = low >>> 8 & 255;
100
+ buf[7] = 255 & low;
101
+ return `${prefix}_${b58.encode(buf)}`;
102
+ }
103
+ const currentDatabaseType = 'unknown';
104
+ function getDatabaseType() {
105
+ return currentDatabaseType;
106
+ }
107
+ const external_zod_namespaceObject = require("zod");
108
+ const fieldConfigSchema = external_zod_namespaceObject.z.object({
109
+ required: external_zod_namespaceObject.z.boolean().default(true),
110
+ returned: external_zod_namespaceObject.z.boolean().default(true),
111
+ input: external_zod_namespaceObject.z.boolean().default(true),
112
+ defaultValue: external_zod_namespaceObject.z.union([
113
+ external_zod_namespaceObject.z.any(),
114
+ external_zod_namespaceObject.z["function"]().returns(external_zod_namespaceObject.z.any())
115
+ ]).optional(),
116
+ transform: external_zod_namespaceObject.z.object({
117
+ input: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
345
118
  external_zod_namespaceObject.z.any(),
346
- external_zod_namespaceObject.z["function"]().returns(external_zod_namespaceObject.z.any())
347
- ]).optional(),
348
- transform: external_zod_namespaceObject.z.object({
349
- input: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
350
- external_zod_namespaceObject.z.any(),
351
- external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
352
- ])).optional(),
353
- output: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
354
- external_zod_namespaceObject.z.any(),
355
- external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
356
- ])).optional()
357
- }).optional(),
358
- validator: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
359
- external_zod_namespaceObject.z.string(),
360
- external_zod_namespaceObject.z["null"]()
119
+ external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
361
120
  ])).optional(),
362
- unique: external_zod_namespaceObject.z.boolean().optional(),
363
- indexed: external_zod_namespaceObject.z.boolean().optional(),
364
- sortable: external_zod_namespaceObject.z.boolean().default(true),
365
- fieldName: external_zod_namespaceObject.z.string().optional(),
366
- bigint: external_zod_namespaceObject.z.boolean().default(false)
367
- });
368
- const stringFieldSchema = fieldConfigSchema.extend({
369
- type: external_zod_namespaceObject.z.literal('string'),
370
- minLength: external_zod_namespaceObject.z.number().optional(),
371
- maxLength: external_zod_namespaceObject.z.number().optional(),
372
- pattern: external_zod_namespaceObject.z.string().optional()
373
- });
374
- const numberFieldSchema = fieldConfigSchema.extend({
375
- type: external_zod_namespaceObject.z.literal('number'),
376
- min: external_zod_namespaceObject.z.number().optional(),
377
- max: external_zod_namespaceObject.z.number().optional()
378
- });
379
- const booleanFieldSchema = fieldConfigSchema.extend({
380
- type: external_zod_namespaceObject.z.literal('boolean')
381
- });
382
- const dateFieldSchema = fieldConfigSchema.extend({
383
- type: external_zod_namespaceObject.z.literal('date'),
384
- minDate: external_zod_namespaceObject.z.date().optional(),
385
- maxDate: external_zod_namespaceObject.z.date().optional(),
386
- dateOnly: external_zod_namespaceObject.z.boolean().default(false),
387
- format: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional()
388
- });
389
- const timezoneFieldSchema = fieldConfigSchema.extend({
390
- type: external_zod_namespaceObject.z.literal('timezone'),
391
- validateTimezone: external_zod_namespaceObject.z.boolean().default(true),
392
- suggestedValues: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional(),
393
- restrictToSuggestedValues: external_zod_namespaceObject.z.boolean().default(false)
394
- });
395
- const jsonFieldSchema = fieldConfigSchema.extend({
396
- type: external_zod_namespaceObject.z.literal('json'),
397
- validateJson: external_zod_namespaceObject.z.boolean().default(true)
398
- });
399
- const stringArrayFieldSchema = fieldConfigSchema.extend({
400
- type: external_zod_namespaceObject.z.literal('string[]')
401
- });
402
- const numberArrayFieldSchema = fieldConfigSchema.extend({
403
- type: external_zod_namespaceObject.z.literal('number[]')
404
- });
405
- const fieldSchema = external_zod_namespaceObject.z.discriminatedUnion('type', [
406
- stringFieldSchema,
407
- numberFieldSchema,
408
- booleanFieldSchema,
409
- dateFieldSchema,
410
- timezoneFieldSchema,
411
- jsonFieldSchema,
412
- stringArrayFieldSchema,
413
- numberArrayFieldSchema
414
- ]);
415
- function validateField(field) {
416
- return fieldSchema.parse(field);
417
- }
418
- async function processHooks(data, model, operation, phase, hooks, context) {
419
- let currentData = {
420
- ...data
421
- };
422
- for (const hookSet of hooks){
423
- const modelHooks = hookSet[model];
424
- if (!modelHooks) continue;
425
- const operationHooks = modelHooks[operation];
426
- if (!operationHooks) continue;
427
- const hookFn = operationHooks[phase];
428
- if (hookFn) if ('before' === phase) {
429
- const result = await hookFn(currentData, context);
430
- if (result && 'object' == typeof result && 'kind' in result) switch(result.kind){
431
- case 'abort':
432
- return null;
433
- case 'transform':
434
- {
435
- const transformData = result.data;
436
- currentData = {
437
- ...currentData,
438
- ...transformData
439
- };
440
- break;
441
- }
442
- default:
121
+ output: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
122
+ external_zod_namespaceObject.z.any(),
123
+ external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
124
+ ])).optional()
125
+ }).optional(),
126
+ validator: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
127
+ external_zod_namespaceObject.z.string(),
128
+ external_zod_namespaceObject.z["null"]()
129
+ ])).optional(),
130
+ unique: external_zod_namespaceObject.z.boolean().optional(),
131
+ indexed: external_zod_namespaceObject.z.boolean().optional(),
132
+ sortable: external_zod_namespaceObject.z.boolean().default(true),
133
+ fieldName: external_zod_namespaceObject.z.string().optional(),
134
+ bigint: external_zod_namespaceObject.z.boolean().default(false)
135
+ });
136
+ const stringFieldSchema = fieldConfigSchema.extend({
137
+ type: external_zod_namespaceObject.z.literal('string'),
138
+ minLength: external_zod_namespaceObject.z.number().optional(),
139
+ maxLength: external_zod_namespaceObject.z.number().optional(),
140
+ pattern: external_zod_namespaceObject.z.string().optional()
141
+ });
142
+ const numberFieldSchema = fieldConfigSchema.extend({
143
+ type: external_zod_namespaceObject.z.literal('number'),
144
+ min: external_zod_namespaceObject.z.number().optional(),
145
+ max: external_zod_namespaceObject.z.number().optional()
146
+ });
147
+ const booleanFieldSchema = fieldConfigSchema.extend({
148
+ type: external_zod_namespaceObject.z.literal('boolean')
149
+ });
150
+ const dateFieldSchema = fieldConfigSchema.extend({
151
+ type: external_zod_namespaceObject.z.literal('date'),
152
+ minDate: external_zod_namespaceObject.z.date().optional(),
153
+ maxDate: external_zod_namespaceObject.z.date().optional(),
154
+ dateOnly: external_zod_namespaceObject.z.boolean().default(false),
155
+ format: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional()
156
+ });
157
+ const timezoneFieldSchema = fieldConfigSchema.extend({
158
+ type: external_zod_namespaceObject.z.literal('timezone'),
159
+ validateTimezone: external_zod_namespaceObject.z.boolean().default(true),
160
+ suggestedValues: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional(),
161
+ restrictToSuggestedValues: external_zod_namespaceObject.z.boolean().default(false)
162
+ });
163
+ const jsonFieldSchema = fieldConfigSchema.extend({
164
+ type: external_zod_namespaceObject.z.literal('json'),
165
+ validateJson: external_zod_namespaceObject.z.boolean().default(true)
166
+ });
167
+ const stringArrayFieldSchema = fieldConfigSchema.extend({
168
+ type: external_zod_namespaceObject.z.literal('string[]')
169
+ });
170
+ const numberArrayFieldSchema = fieldConfigSchema.extend({
171
+ type: external_zod_namespaceObject.z.literal('number[]')
172
+ });
173
+ const fieldSchema = external_zod_namespaceObject.z.discriminatedUnion('type', [
174
+ stringFieldSchema,
175
+ numberFieldSchema,
176
+ booleanFieldSchema,
177
+ dateFieldSchema,
178
+ timezoneFieldSchema,
179
+ jsonFieldSchema,
180
+ stringArrayFieldSchema,
181
+ numberArrayFieldSchema
182
+ ]);
183
+ function validateField(field) {
184
+ return fieldSchema.parse(field);
185
+ }
186
+ async function processHooks(data, model, operation, phase, hooks, context) {
187
+ let currentData = {
188
+ ...data
189
+ };
190
+ for (const hookSet of hooks){
191
+ const modelHooks = hookSet[model];
192
+ if (!modelHooks) continue;
193
+ const operationHooks = modelHooks[operation];
194
+ if (!operationHooks) continue;
195
+ const hookFn = operationHooks[phase];
196
+ if (hookFn) if ('before' === phase) {
197
+ const result = await hookFn(currentData, context);
198
+ if (result && 'object' == typeof result && 'kind' in result) switch(result.kind){
199
+ case 'abort':
200
+ return null;
201
+ case 'transform':
202
+ {
203
+ const transformData = result.data;
204
+ currentData = {
205
+ ...currentData,
206
+ ...transformData
207
+ };
443
208
  break;
444
- }
445
- } else await hookFn(currentData, context);
446
- }
447
- return currentData;
209
+ }
210
+ default:
211
+ break;
212
+ }
213
+ } else await hookFn(currentData, context);
448
214
  }
449
- async function processAfterHooksForMany(records, model, hooks, context) {
450
- if (!records.length) return;
451
- for (const record of records)await processHooks(record, model, 'update', 'after', hooks, context);
215
+ return currentData;
216
+ }
217
+ async function processAfterHooksForMany(records, model, hooks, context) {
218
+ if (!records.length) return;
219
+ for (const record of records)await processHooks(record, model, 'update', 'after', hooks, context);
220
+ }
221
+ async function create_hooks_createWithHooks(adapter, ctx, props) {
222
+ const { data, model, customFn, context } = props;
223
+ const hooks = ctx.hooks || [];
224
+ const transformedData = await processHooks(data, model, 'create', 'before', hooks, context);
225
+ if (null === transformedData) return null;
226
+ let created = null;
227
+ if (customFn) {
228
+ created = await customFn.fn(transformedData);
229
+ if (!customFn.executeMainFn && created) return created;
452
230
  }
453
- async function create_hooks_createWithHooks(adapter, ctx, props) {
454
- const { data, model, customFn, context } = props;
455
- const hooks = ctx.hooks || [];
456
- const transformedData = await processHooks(data, model, 'create', 'before', hooks, context);
457
- if (null === transformedData) return null;
458
- let created = null;
459
- if (customFn) {
460
- created = await customFn.fn(transformedData);
461
- if (!customFn.executeMainFn && created) return created;
462
- }
463
- if (!created) created = await adapter.create({
464
- model: model,
465
- data: transformedData
466
- });
467
- if (created) await processHooks(created, model, 'create', 'after', hooks, context);
468
- return created;
231
+ if (!created) created = await adapter.create({
232
+ model: model,
233
+ data: transformedData
234
+ });
235
+ if (created) await processHooks(created, model, 'create', 'after', hooks, context);
236
+ return created;
237
+ }
238
+ async function update_hooks_updateWithHooks(adapter, ctx, props) {
239
+ const { data, where, model, customFn, context } = props;
240
+ const hooks = ctx.hooks || [];
241
+ const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
242
+ if (null === transformedData) return null;
243
+ let updated = null;
244
+ if (customFn) {
245
+ const result = await customFn.fn(transformedData);
246
+ updated = result;
247
+ if (!customFn.executeMainFn && updated) return updated;
469
248
  }
470
- async function update_hooks_updateWithHooks(adapter, ctx, props) {
471
- const { data, where, model, customFn, context } = props;
472
- const hooks = ctx.hooks || [];
473
- const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
474
- if (null === transformedData) return null;
475
- let updated = null;
476
- if (customFn) {
477
- const result = await customFn.fn(transformedData);
478
- updated = result;
479
- if (!customFn.executeMainFn && updated) return updated;
480
- }
481
- if (!updated) updated = await adapter.update({
249
+ if (!updated) updated = await adapter.update({
250
+ model: model,
251
+ update: transformedData,
252
+ where
253
+ });
254
+ if (updated) await processHooks(updated, model, 'update', 'after', hooks, context);
255
+ return updated;
256
+ }
257
+ async function executeCustomFunction(data, customFn) {
258
+ if (!customFn) return {
259
+ result: null,
260
+ shouldContinue: true
261
+ };
262
+ const result = await customFn.fn(data);
263
+ const shouldContinue = !result || !!customFn.executeMainFn;
264
+ return {
265
+ result,
266
+ shouldContinue
267
+ };
268
+ }
269
+ function processUpdateManyResult(result) {
270
+ if (Array.isArray(result)) return result;
271
+ if ('number' == typeof result && result > 0) return [];
272
+ return null;
273
+ }
274
+ async function updateManyWithHooks(adapter, ctx, props) {
275
+ const { data, where, model, customFn, context } = props;
276
+ const hooks = ctx.hooks || [];
277
+ const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
278
+ if (null === transformedData) return null;
279
+ const { result: customResult, shouldContinue } = await executeCustomFunction(transformedData, customFn);
280
+ if (customResult && !shouldContinue) return customResult;
281
+ let updated = customResult;
282
+ if (!updated) {
283
+ const adapterResult = await adapter.updateMany({
482
284
  model: model,
483
285
  update: transformedData,
484
286
  where
485
287
  });
486
- if (updated) await processHooks(updated, model, 'update', 'after', hooks, context);
487
- return updated;
488
- }
489
- async function executeCustomFunction(data, customFn) {
490
- if (!customFn) return {
491
- result: null,
492
- shouldContinue: true
493
- };
494
- const result = await customFn.fn(data);
495
- const shouldContinue = !result || !!customFn.executeMainFn;
496
- return {
497
- result,
498
- shouldContinue
499
- };
500
- }
501
- function processUpdateManyResult(result) {
502
- if (Array.isArray(result)) return result;
503
- if ('number' == typeof result && result > 0) return [];
504
- return null;
505
- }
506
- async function updateManyWithHooks(adapter, ctx, props) {
507
- const { data, where, model, customFn, context } = props;
508
- const hooks = ctx.hooks || [];
509
- const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
510
- if (null === transformedData) return null;
511
- const { result: customResult, shouldContinue } = await executeCustomFunction(transformedData, customFn);
512
- if (customResult && !shouldContinue) return customResult;
513
- let updated = customResult;
514
- if (!updated) {
515
- const adapterResult = await adapter.updateMany({
516
- model: model,
517
- update: transformedData,
518
- where
519
- });
520
- updated = processUpdateManyResult(adapterResult);
521
- }
522
- if (updated && updated.length > 0) await processAfterHooksForMany(updated, model, hooks, context);
523
- return updated;
524
- }
525
- function getWithHooks(adapter, ctx) {
526
- return {
527
- createWithHooks: ({ data, model, customFn, context })=>create_hooks_createWithHooks(adapter, ctx, {
528
- data,
529
- model,
530
- customFn,
531
- context
532
- }),
533
- updateWithHooks: (props)=>update_hooks_updateWithHooks(adapter, ctx, props),
534
- updateManyWithHooks: (props)=>updateManyWithHooks(adapter, ctx, props)
535
- };
536
- }
537
- require("neverthrow");
538
- const external_h3_namespaceObject = require("h3");
539
- const error_codes_ERROR_CODES = Object.freeze({
540
- NOT_FOUND: 'Resource not found',
541
- BAD_REQUEST: 'Bad request',
542
- CONFLICT: 'Conflict with current state',
543
- MISSING_REQUIRED_PARAMETER: 'Missing required parameter',
544
- UNAUTHORIZED: 'Unauthorized',
545
- FORBIDDEN: 'Forbidden',
546
- INTERNAL_SERVER_ERROR: 'Internal server error',
547
- INITIALIZATION_FAILED: 'Initialization failed',
548
- DATABASE_CONNECTION_ERROR: 'Database connection error',
549
- DATABASE_QUERY_ERROR: 'Database query error',
550
- INVALID_CONFIGURATION: 'Invalid configuration',
551
- REQUEST_HANDLER_ERROR: 'Request handler error',
552
- INVALID_REQUEST: 'Invalid request',
553
- UNKNOWN_ERROR: 'Unknown error',
554
- NETWORK_ERROR: 'Network error',
555
- PLUGIN_INITIALIZATION_FAILED: 'Plugin initialization failed',
556
- API_RETRIEVAL_ERROR: 'API retrieval error',
557
- VALIDATION_ERROR: 'Validation error',
558
- UNEXPECTED: 'Unexpected error'
559
- });
560
- const ERROR_CATEGORIES = Object.freeze({
561
- VALIDATION: 'validation',
562
- AUTHORIZATION: 'authorization',
563
- STORAGE: 'storage',
564
- NETWORK: 'network',
565
- PLUGIN: 'plugin',
566
- CONFIGURATION: 'configuration',
567
- UNEXPECTED: 'unexpected'
568
- });
569
- const api_namespaceObject = require("@opentelemetry/api");
570
- const tracing_tracer = api_namespaceObject.trace.getTracer('@doubletie/results');
571
- async function tracing_withSpan(name, fn, attributes = {}) {
572
- return await tracing_tracer.startActiveSpan(name, async (span)=>{
573
- try {
574
- span.setAttributes(attributes);
575
- const result = await fn(span);
576
- span.setStatus({
577
- code: api_namespaceObject.SpanStatusCode.OK
578
- });
579
- span.end();
580
- return result;
581
- } catch (error) {
582
- if (error instanceof error_class_DoubleTieError) {
583
- span.setAttributes({
584
- 'error.type': 'DoubleTieError',
585
- 'error.code': error.code,
586
- 'error.statusCode': error.statusCode,
587
- 'error.message': error.message
588
- });
589
- if (error.meta) span.setAttributes({
590
- 'error.meta': JSON.stringify(error.meta)
591
- });
592
- } else span.setAttributes({
593
- 'error.type': error instanceof Error ? error.constructor.name : 'Unknown',
594
- 'error.message': error instanceof Error ? error.message : String(error)
595
- });
596
- span.setStatus({
597
- code: api_namespaceObject.SpanStatusCode.ERROR,
598
- message: error instanceof Error ? error.message : String(error)
599
- });
600
- span.end();
601
- throw error;
602
- }
603
- });
604
- }
605
- class error_class_DoubleTieError extends external_h3_namespaceObject.H3Error {
606
- code;
607
- category;
608
- meta;
609
- constructor(message, options = {
610
- code: error_codes_ERROR_CODES.UNKNOWN_ERROR,
611
- status: 500,
612
- category: ERROR_CATEGORIES.UNEXPECTED,
613
- cause: void 0,
614
- meta: {}
615
- }){
616
- super(message, {
617
- cause: options.cause
618
- });
619
- this.name = this.constructor.name;
620
- this.code = options.code ?? error_codes_ERROR_CODES.UNKNOWN_ERROR;
621
- this.statusCode = options.status ?? 500;
622
- this.category = options.category ?? ERROR_CATEGORIES.UNEXPECTED;
623
- this.meta = options.meta ?? {};
624
- this.data = {
625
- code: this.code,
626
- category: this.category,
627
- meta: this.meta
628
- };
629
- tracing_withSpan('create_doubletie_error', async (span)=>{
630
- span.setAttributes({
631
- 'error.name': this.name,
632
- 'error.message': message,
633
- 'error.code': this.code,
634
- 'error.status': this.statusCode,
635
- 'error.category': this.category,
636
- 'error.has_cause': !!this.cause,
637
- 'error.cause_type': this.cause instanceof Error ? this.cause.constructor.name : typeof this.cause,
638
- 'error.has_meta': !!this.meta
639
- });
640
- if (this.cause instanceof Error) span.recordException(this.cause);
641
- });
642
- if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
643
- }
644
- static isDoubleTieError(error) {
645
- return error instanceof error_class_DoubleTieError;
646
- }
647
- toJSON() {
648
- const validationErrorMessage = this.meta?.validationErrors ? String(this.meta.validationErrors) : void 0;
649
- const stackTrace = this.stack ? this.stack.split('\n').map((line)=>line.trim()).filter((line)=>line && !line.includes('Error: ')) : [];
650
- return {
651
- statusCode: this.statusCode,
652
- message: validationErrorMessage || this.message,
653
- statusMessage: this.statusMessage,
654
- data: {
655
- code: this.code,
656
- category: this.category,
657
- meta: this.meta,
658
- ...'production' === process.env.NODE_ENV ? {} : {
659
- stack: stackTrace
660
- },
661
- ...validationErrorMessage && this.message ? {
662
- originalMessage: this.message
663
- } : {},
664
- ...this.cause ? {
665
- cause: this.cause instanceof Error ? {
666
- name: this.cause.name,
667
- message: this.cause.message,
668
- stack: this.cause.stack ? this.cause.stack.split('\n').map((line)=>line.trim()) : void 0
669
- } : this.cause
670
- } : {}
671
- }
672
- };
673
- }
674
- static fromResponse(response, data) {
675
- let message = `HTTP error ${response.status}`;
676
- let errorCode = `HTTP ${response.status}`;
677
- let errorMeta = {};
678
- if (data && 'object' == typeof data && null !== data) {
679
- const errorObj = data;
680
- if ('string' == typeof errorObj.message) message = errorObj.message;
681
- if ('string' == typeof errorObj.code) errorCode = errorObj.code;
682
- if ('object' == typeof errorObj.data && null !== errorObj.data) errorMeta = errorObj.data;
683
- }
684
- return new error_class_DoubleTieError(message, {
685
- code: errorCode,
686
- status: response.status,
687
- meta: errorMeta
688
- });
689
- }
690
- withMeta(additionalMeta) {
691
- return new error_class_DoubleTieError(this.message, {
692
- code: this.code,
693
- status: this.statusCode,
694
- category: this.category,
695
- cause: this.cause instanceof Error ? this.cause : void 0,
696
- meta: {
697
- ...this.meta,
698
- ...additionalMeta
699
- }
700
- });
701
- }
702
- static createSubclass(name) {
703
- const ErrorSubclass = class extends error_class_DoubleTieError {
704
- constructor(message, options){
705
- super(message, options);
706
- this.name = name;
707
- }
708
- };
709
- Object.defineProperty(ErrorSubclass, 'name', {
710
- value: name
711
- });
712
- return ErrorSubclass;
713
- }
714
- static formatValidationError(error) {
715
- if (!error.meta) return error.message;
716
- let formattedMessage = `${error.message} (${error.code})`;
717
- if (error.meta.validationErrors) formattedMessage += `\nValidation Errors: ${JSON.stringify(error.meta.validationErrors, null, 2)}`;
718
- const otherMeta = Object.fromEntries(Object.entries(error.meta).filter(([key])=>'validationErrors' !== key));
719
- if (Object.keys(otherMeta).length > 0) formattedMessage += `\nAdditional Context: ${JSON.stringify(otherMeta, null, 2)}`;
720
- return formattedMessage;
721
- }
722
- }
723
- var ZodError = __webpack_require__("../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/ZodError.js");
724
- const colors = {
725
- reset: '\x1b[0m',
726
- bright: '\x1b[1m',
727
- dim: '\x1b[2m',
728
- underscore: '\x1b[4m',
729
- blink: '\x1b[5m',
730
- reverse: '\x1b[7m',
731
- hidden: '\x1b[8m',
732
- fg: {
733
- black: '\x1b[30m',
734
- red: '\x1b[31m',
735
- green: '\x1b[32m',
736
- yellow: '\x1b[33m',
737
- blue: '\x1b[34m',
738
- magenta: '\x1b[35m',
739
- cyan: '\x1b[36m',
740
- white: '\x1b[37m'
741
- },
742
- bg: {
743
- black: '\x1b[40m',
744
- red: '\x1b[41m',
745
- green: '\x1b[42m',
746
- yellow: '\x1b[43m',
747
- blue: '\x1b[44m',
748
- magenta: '\x1b[45m',
749
- cyan: '\x1b[46m',
750
- white: '\x1b[47m'
751
- }
752
- };
753
- const levelColors = {
754
- info: colors.fg.blue,
755
- success: colors.fg.green,
756
- warn: colors.fg.yellow,
757
- error: colors.fg.red,
758
- debug: colors.fg.magenta
759
- };
760
- const formatMessage = (level, message, appName = 'c15t')=>{
761
- const timestamp = new Date().toISOString();
762
- return `${colors.dim}${timestamp}${colors.reset} ${levelColors[level]}${level.toUpperCase()}${colors.reset} ${colors.bright}[${appName}]:${colors.reset} ${message}`;
763
- };
764
- const levels = [
765
- 'error',
766
- 'warn',
767
- 'info',
768
- 'success',
769
- 'debug'
770
- ];
771
- function shouldPublishLog(currentLogLevel, logLevel) {
772
- const currentLevelIndex = levels.indexOf(currentLogLevel);
773
- const messageLevelIndex = levels.indexOf(logLevel);
774
- if ('debug' === currentLogLevel) return 'debug' === logLevel;
775
- return messageLevelIndex <= currentLevelIndex;
288
+ updated = processUpdateManyResult(adapterResult);
776
289
  }
777
- const LOGGER_TRACER_NAME = '@doubletie/logger';
778
- const LOG_LEVEL_TO_SPAN_STATUS = {
779
- error: api_namespaceObject.SpanStatusCode.ERROR,
780
- warn: api_namespaceObject.SpanStatusCode.OK,
781
- info: api_namespaceObject.SpanStatusCode.OK,
782
- success: api_namespaceObject.SpanStatusCode.OK,
783
- debug: api_namespaceObject.SpanStatusCode.OK
784
- };
785
- const telemetry_getTracer = (options)=>{
786
- if (options?.telemetry?.tracer) return options.telemetry.tracer;
787
- return api_namespaceObject.trace.getTracer(LOGGER_TRACER_NAME);
788
- };
789
- const createLogSpan = (level, message, args = [], options)=>{
790
- if (options?.telemetry?.disabled) return null;
791
- const tracer = telemetry_getTracer(options);
792
- const span = tracer.startSpan('log_entry', {
793
- attributes: {
794
- 'log.level': level,
795
- 'log.message': message,
796
- 'log.has_args': args.length > 0,
797
- ...options?.telemetry?.defaultAttributes || {}
798
- }
799
- });
800
- if (args.length > 0 && 'object' == typeof args[0] && null !== args[0]) {
801
- const data = args[0];
802
- for (const [key, value] of Object.entries(data))if (null != value) span.setAttribute(`log.data.${key}`, String(value));
803
- }
804
- span.setStatus({
805
- code: LOG_LEVEL_TO_SPAN_STATUS[level],
806
- message: 'error' === level || 'warn' === level ? message : void 0
807
- });
808
- return span;
290
+ if (updated && updated.length > 0) await processAfterHooksForMany(updated, model, hooks, context);
291
+ return updated;
292
+ }
293
+ function getWithHooks(adapter, ctx) {
294
+ return {
295
+ createWithHooks: ({ data, model, customFn, context })=>create_hooks_createWithHooks(adapter, ctx, {
296
+ data,
297
+ model,
298
+ customFn,
299
+ context
300
+ }),
301
+ updateWithHooks: (props)=>update_hooks_updateWithHooks(adapter, ctx, props),
302
+ updateManyWithHooks: (props)=>updateManyWithHooks(adapter, ctx, props)
809
303
  };
810
- const withLogSpan = async (level, message, args, operation, options)=>{
811
- const span = createLogSpan(level, message, args, options);
812
- if (!span) return operation();
304
+ }
305
+ require("neverthrow");
306
+ const server_namespaceObject = require("@orpc/server");
307
+ const error_codes_ERROR_CODES = Object.freeze({
308
+ NOT_FOUND: 'Resource not found',
309
+ BAD_REQUEST: 'Bad request',
310
+ CONFLICT: 'Conflict with current state',
311
+ MISSING_REQUIRED_PARAMETER: 'Missing required parameter',
312
+ UNAUTHORIZED: 'Unauthorized',
313
+ FORBIDDEN: 'Forbidden',
314
+ INTERNAL_SERVER_ERROR: 'Internal server error',
315
+ INITIALIZATION_FAILED: 'Initialization failed',
316
+ DATABASE_CONNECTION_ERROR: 'Database connection error',
317
+ DATABASE_QUERY_ERROR: 'Database query error',
318
+ INVALID_CONFIGURATION: 'Invalid configuration',
319
+ REQUEST_HANDLER_ERROR: 'Request handler error',
320
+ INVALID_REQUEST: 'Invalid request',
321
+ UNKNOWN_ERROR: 'Unknown error',
322
+ NETWORK_ERROR: 'Network error',
323
+ PLUGIN_INITIALIZATION_FAILED: 'Plugin initialization failed',
324
+ API_RETRIEVAL_ERROR: 'API retrieval error',
325
+ VALIDATION_ERROR: 'Validation error',
326
+ UNEXPECTED: 'Unexpected error'
327
+ });
328
+ const ERROR_CATEGORIES = Object.freeze({
329
+ VALIDATION: 'validation',
330
+ AUTHORIZATION: 'authorization',
331
+ STORAGE: 'storage',
332
+ NETWORK: 'network',
333
+ PLUGIN: 'plugin',
334
+ CONFIGURATION: 'configuration',
335
+ UNEXPECTED: 'unexpected'
336
+ });
337
+ const api_namespaceObject = require("@opentelemetry/api");
338
+ const tracer = api_namespaceObject.trace.getTracer('@doubletie/results');
339
+ async function tracing_withSpan(name, fn, attributes = {}) {
340
+ return await tracer.startActiveSpan(name, async (span)=>{
813
341
  try {
814
- const result = await operation();
342
+ span.setAttributes(attributes);
343
+ const result = await fn(span);
344
+ span.setStatus({
345
+ code: api_namespaceObject.SpanStatusCode.OK
346
+ });
347
+ span.end();
815
348
  return result;
816
349
  } catch (error) {
350
+ if (error instanceof error_class_DoubleTieError) {
351
+ span.setAttributes({
352
+ 'error.type': 'DoubleTieError',
353
+ 'error.code': error.code,
354
+ 'error.statusCode': error.statusCode,
355
+ 'error.message': error.message
356
+ });
357
+ if (error.meta) span.setAttributes({
358
+ 'error.meta': JSON.stringify(error.meta)
359
+ });
360
+ } else span.setAttributes({
361
+ 'error.type': error instanceof Error ? error.constructor.name : 'Unknown',
362
+ 'error.message': error instanceof Error ? error.message : String(error)
363
+ });
817
364
  span.setStatus({
818
365
  code: api_namespaceObject.SpanStatusCode.ERROR,
819
366
  message: error instanceof Error ? error.message : String(error)
820
367
  });
821
- throw error;
822
- } finally{
823
368
  span.end();
369
+ throw error;
824
370
  }
825
- };
826
- const createLogger = (options)=>{
827
- if (options && 'object' == typeof options && levels.every((level)=>'function' == typeof options[level])) return options;
828
- const loggerOptions = options;
829
- const enabled = loggerOptions?.disabled !== true;
830
- const logLevel = loggerOptions?.level ?? 'error';
831
- const appName = loggerOptions?.appName ?? 'c15t';
832
- const logFunc = async (level, message, args = [])=>{
833
- if (!enabled || !shouldPublishLog(logLevel, level)) return;
834
- await withLogSpan(level, message, args, async ()=>{
835
- const formattedMessage = formatMessage(level, message, appName);
836
- if (!loggerOptions || 'function' != typeof loggerOptions.log) {
837
- if ('error' === level) console.error(formattedMessage, ...args);
838
- else if ('warn' === level) console.warn(formattedMessage, ...args);
839
- else if ('info' === level) console.log(formattedMessage, ...args);
840
- else if ('debug' === level) console.debug(formattedMessage, ...args);
841
- else if ('success' === level) console.log(formattedMessage, ...args);
842
- return;
843
- }
844
- loggerOptions.log('success' === level ? 'info' : level, message, ...args);
845
- });
846
- };
847
- return Object.fromEntries(levels.map((level)=>[
848
- level,
849
- (...[message, ...args])=>logFunc(level, message, args).catch((error)=>{
850
- console.error('Logger error:', error);
851
- })
852
- ]));
853
- };
854
- const logger_factory_logger = createLogger();
855
- const auditLogSchema = external_zod_namespaceObject.z.object({
856
- id: external_zod_namespaceObject.z.string(),
857
- entityType: external_zod_namespaceObject.z.string(),
858
- entityId: external_zod_namespaceObject.z.string(),
859
- actionType: external_zod_namespaceObject.z.string(),
860
- subjectId: external_zod_namespaceObject.z.string().optional(),
861
- ipAddress: external_zod_namespaceObject.z.string().optional(),
862
- userAgent: external_zod_namespaceObject.z.string().optional(),
863
- changes: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
864
- metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
865
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date())
866
371
  });
867
- function getAuditLogTable(options, auditLogFields) {
868
- const auditLogConfig = options.tables?.auditLog;
869
- const subjectConfig = options.tables?.subject;
870
- return {
871
- entityName: auditLogConfig?.entityName || 'auditLog',
872
- entityPrefix: auditLogConfig?.entityPrefix || 'log',
873
- schema: auditLogSchema,
874
- fields: {
875
- entityType: {
876
- type: 'string',
877
- required: true,
878
- fieldName: auditLogConfig?.fields?.entityType || 'entityType'
879
- },
880
- entityId: {
881
- type: 'string',
882
- required: true,
883
- fieldName: auditLogConfig?.fields?.entityId || 'entityId'
884
- },
885
- actionType: {
886
- type: 'string',
887
- required: true,
888
- fieldName: auditLogConfig?.fields?.actionType || 'actionType'
889
- },
890
- subjectId: {
891
- type: 'string',
892
- required: false,
893
- fieldName: auditLogConfig?.fields?.subjectId || 'subjectId',
894
- references: {
895
- model: subjectConfig?.entityName || 'subject',
896
- field: 'id'
897
- }
898
- },
899
- ipAddress: {
900
- type: 'string',
901
- required: false,
902
- fieldName: auditLogConfig?.fields?.ipAddress || 'ipAddress'
903
- },
904
- userAgent: {
905
- type: 'string',
906
- required: false,
907
- fieldName: auditLogConfig?.fields?.userAgent || 'userAgent'
908
- },
909
- changes: {
910
- type: 'json',
911
- required: false,
912
- fieldName: auditLogConfig?.fields?.changes || 'changes'
913
- },
914
- metadata: {
915
- type: 'json',
916
- required: false,
917
- fieldName: auditLogConfig?.fields?.metadata || 'metadata'
918
- },
919
- createdAt: {
920
- type: 'date',
921
- defaultValue: ()=>new Date(),
922
- required: true,
923
- fieldName: auditLogConfig?.fields?.createdAt || 'createdAt'
924
- },
925
- eventTimezone: {
926
- type: 'timezone',
927
- required: true,
928
- defaultValue: COMMON_TIMEZONES.UTC,
929
- fieldName: auditLogConfig?.fields?.eventTimezone || 'eventTimezone'
930
- },
931
- ...auditLogFields || {},
932
- ...auditLogConfig?.additionalFields || {}
933
- },
934
- indexes: [
935
- {
936
- name: 'entity_index',
937
- fields: [
938
- 'entityType',
939
- 'entityId'
940
- ]
941
- },
942
- {
943
- name: 'action_type_index',
944
- fields: [
945
- 'actionType'
946
- ]
947
- },
948
- {
949
- name: 'subject_id_index',
950
- fields: [
951
- 'subjectId'
952
- ]
953
- },
954
- {
955
- name: 'created_at_index',
956
- fields: [
957
- 'createdAt'
958
- ]
959
- }
960
- ],
961
- order: 5
962
- };
372
+ }
373
+ class error_class_DoubleTieError extends server_namespaceObject.ORPCError {
374
+ category;
375
+ meta;
376
+ statusCode;
377
+ constructor(message, options = {
378
+ code: error_codes_ERROR_CODES.UNKNOWN_ERROR,
379
+ status: 500,
380
+ category: ERROR_CATEGORIES.UNEXPECTED,
381
+ cause: void 0,
382
+ meta: {}
383
+ }){
384
+ super(options.code ?? error_codes_ERROR_CODES.UNKNOWN_ERROR, {
385
+ message,
386
+ cause: options.cause,
387
+ data: options.meta ?? {}
388
+ });
389
+ this.name = 'DoubleTieError';
390
+ this.category = options.category ?? ERROR_CATEGORIES.UNEXPECTED;
391
+ this.meta = options.meta ?? {};
392
+ this.statusCode = options.status ?? 500;
393
+ tracing_withSpan('create_doubletie_error', async (span)=>{
394
+ span.setAttributes({
395
+ 'error.name': this.constructor.name,
396
+ 'error.message': message,
397
+ 'error.code': this.code,
398
+ 'error.status': this.statusCode,
399
+ 'error.category': this.category,
400
+ 'error.has_cause': !!this.cause,
401
+ 'error.cause_type': this.cause instanceof Error ? this.cause.constructor.name : typeof this.cause,
402
+ 'error.has_meta': !!this.meta
403
+ });
404
+ if (this.cause instanceof Error) span.recordException(this.cause);
405
+ });
406
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
963
407
  }
964
- const PolicyTypeSchema = external_zod_namespaceObject.z["enum"]([
965
- 'cookie_banner',
966
- 'privacy_policy',
967
- 'dpa',
968
- 'terms_and_conditions',
969
- 'marketing_communications',
970
- 'age_verification',
971
- 'other'
972
- ]);
973
- const consentPolicySchema = external_zod_namespaceObject.z.object({
974
- id: external_zod_namespaceObject.z.string(),
975
- version: external_zod_namespaceObject.z.string(),
976
- type: PolicyTypeSchema,
977
- name: external_zod_namespaceObject.z.string(),
978
- effectiveDate: external_zod_namespaceObject.z.date(),
979
- expirationDate: external_zod_namespaceObject.z.date().nullable().optional(),
980
- content: external_zod_namespaceObject.z.string(),
981
- contentHash: external_zod_namespaceObject.z.string(),
982
- isActive: external_zod_namespaceObject.z.boolean().default(true),
983
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
984
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
985
- });
986
- function getConsentPolicyTable(options, policyFields) {
987
- const consentPolicyConfig = options.tables?.consentPolicy;
988
- return {
989
- entityName: consentPolicyConfig?.entityName || 'consentPolicy',
990
- entityPrefix: consentPolicyConfig?.entityPrefix || 'pol',
991
- schema: consentPolicySchema,
992
- fields: {
993
- version: {
994
- type: 'string',
995
- required: true,
996
- fieldName: consentPolicyConfig?.fields?.version || 'version'
997
- },
998
- type: {
999
- type: 'string',
1000
- required: true,
1001
- fieldName: consentPolicyConfig?.fields?.type || 'type'
1002
- },
1003
- name: {
1004
- type: 'string',
1005
- required: true,
1006
- fieldName: consentPolicyConfig?.fields?.name || 'name'
1007
- },
1008
- effectiveDate: {
1009
- type: 'date',
1010
- required: true,
1011
- fieldName: consentPolicyConfig?.fields?.effectiveDate || 'effectiveDate'
1012
- },
1013
- expirationDate: {
1014
- type: 'date',
1015
- required: false,
1016
- fieldName: consentPolicyConfig?.fields?.expirationDate || 'expirationDate'
1017
- },
1018
- content: {
1019
- type: 'string',
1020
- required: true,
1021
- fieldName: consentPolicyConfig?.fields?.content || 'content'
1022
- },
1023
- contentHash: {
1024
- type: 'string',
1025
- required: true,
1026
- fieldName: consentPolicyConfig?.fields?.contentHash || 'contentHash'
1027
- },
1028
- isActive: {
1029
- type: 'boolean',
1030
- defaultValue: true,
1031
- required: true,
1032
- fieldName: consentPolicyConfig?.fields?.isActive || 'isActive'
1033
- },
1034
- createdAt: {
1035
- type: 'date',
1036
- defaultValue: ()=>new Date(),
1037
- required: true,
1038
- fieldName: consentPolicyConfig?.fields?.createdAt || 'createdAt'
1039
- },
1040
- ...policyFields || {},
1041
- ...consentPolicyConfig?.additionalFields || {}
1042
- },
1043
- order: 2
1044
- };
408
+ static isDoubleTieError(error) {
409
+ return error instanceof error_class_DoubleTieError;
1045
410
  }
1046
- const purposeSchema = external_zod_namespaceObject.z.object({
1047
- id: external_zod_namespaceObject.z.string(),
1048
- code: external_zod_namespaceObject.z.string(),
1049
- name: external_zod_namespaceObject.z.string(),
1050
- description: external_zod_namespaceObject.z.string(),
1051
- isEssential: external_zod_namespaceObject.z.boolean().default(false),
1052
- dataCategory: external_zod_namespaceObject.z.string().optional(),
1053
- legalBasis: external_zod_namespaceObject.z.string().optional(),
1054
- isActive: external_zod_namespaceObject.z.boolean().default(true),
1055
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1056
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1057
- });
1058
- function getPurposeTable(options, purposeFields) {
1059
- const purposeConfig = options.tables?.consentPurpose;
411
+ toJSON() {
412
+ const validationErrorMessage = this.meta?.validationErrors ? String(this.meta.validationErrors) : void 0;
413
+ const stackTrace = this.stack ? this.stack.split('\n').map((line)=>line.trim()).filter((line)=>line && !line.includes('Error: ')) : [];
1060
414
  return {
1061
- entityName: purposeConfig?.entityName || 'consentPurpose',
1062
- entityPrefix: purposeConfig?.entityPrefix || 'pur',
1063
- schema: purposeSchema,
1064
- fields: {
1065
- code: {
1066
- type: 'string',
1067
- required: true,
1068
- fieldName: purposeConfig?.fields?.code || 'code'
1069
- },
1070
- name: {
1071
- type: 'string',
1072
- required: true,
1073
- fieldName: purposeConfig?.fields?.name || 'name'
1074
- },
1075
- description: {
1076
- type: 'string',
1077
- required: true,
1078
- fieldName: purposeConfig?.fields?.description || "description"
1079
- },
1080
- isEssential: {
1081
- type: 'boolean',
1082
- defaultValue: ()=>false,
1083
- required: true,
1084
- fieldName: purposeConfig?.fields?.isEssential || 'isEssential'
1085
- },
1086
- dataCategory: {
1087
- type: 'string',
1088
- required: false,
1089
- fieldName: purposeConfig?.fields?.dataCategory || 'dataCategory'
1090
- },
1091
- legalBasis: {
1092
- type: 'string',
1093
- required: false,
1094
- fieldName: purposeConfig?.fields?.legalBasis || 'legalBasis'
1095
- },
1096
- isActive: {
1097
- type: 'boolean',
1098
- defaultValue: true,
1099
- required: true,
1100
- fieldName: purposeConfig?.fields?.isActive || 'isActive'
1101
- },
1102
- createdAt: {
1103
- type: 'date',
1104
- defaultValue: ()=>new Date(),
1105
- required: true,
1106
- fieldName: purposeConfig?.fields?.createdAt || 'createdAt'
1107
- },
1108
- updatedAt: {
1109
- type: 'date',
1110
- defaultValue: ()=>new Date(),
1111
- required: true,
1112
- fieldName: purposeConfig?.fields?.updatedAt || 'updatedAt'
415
+ code: this.code,
416
+ message: validationErrorMessage || this.message,
417
+ status: this.statusCode,
418
+ defined: true,
419
+ data: {
420
+ category: this.category,
421
+ meta: this.meta,
422
+ ...'production' === process.env.NODE_ENV ? {} : {
423
+ stack: stackTrace
1113
424
  },
1114
- ...purposeFields || {},
1115
- ...purposeConfig?.additionalFields || {}
1116
- },
1117
- order: 1
425
+ ...validationErrorMessage && this.message ? {
426
+ originalMessage: this.message
427
+ } : {},
428
+ ...this.cause ? {
429
+ cause: this.cause instanceof Error ? {
430
+ name: this.cause.name,
431
+ message: this.cause.message,
432
+ stack: this.cause.stack ? this.cause.stack.split('\n').map((line)=>line.trim()) : void 0
433
+ } : this.cause
434
+ } : {}
435
+ }
1118
436
  };
1119
437
  }
1120
- const consentRecordSchema = external_zod_namespaceObject.z.object({
1121
- id: external_zod_namespaceObject.z.string(),
1122
- subjectId: external_zod_namespaceObject.z.string(),
1123
- consentId: external_zod_namespaceObject.z.string().optional(),
1124
- actionType: external_zod_namespaceObject.z.string(),
1125
- details: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
1126
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1127
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1128
- });
1129
- function getConsentRecordTable(options, recordFields) {
1130
- const recordConfig = options.tables?.record;
1131
- const subjectConfig = options.tables?.subject;
1132
- const consentConfig = options.tables?.consent;
1133
- return {
1134
- entityName: recordConfig?.entityName || 'consentRecord',
1135
- entityPrefix: recordConfig?.entityPrefix || 'rec',
1136
- schema: consentRecordSchema,
1137
- fields: {
1138
- subjectId: {
1139
- type: 'string',
1140
- required: true,
1141
- fieldName: recordConfig?.fields?.subjectId || 'subjectId',
1142
- references: {
1143
- model: subjectConfig?.entityName || 'subject',
1144
- field: 'id'
1145
- }
1146
- },
1147
- consentId: {
1148
- type: 'string',
1149
- required: false,
1150
- fieldName: recordConfig?.fields?.consentId || 'consentId',
1151
- references: {
1152
- model: consentConfig?.entityName || 'consent',
1153
- field: 'id'
1154
- }
1155
- },
1156
- actionType: {
1157
- type: 'string',
1158
- required: true,
1159
- fieldName: recordConfig?.fields?.actionType || 'actionType'
1160
- },
1161
- details: {
1162
- type: 'json',
1163
- required: false,
1164
- fieldName: recordConfig?.fields?.details || 'details'
1165
- },
1166
- createdAt: {
1167
- type: 'date',
1168
- defaultValue: ()=>new Date(),
1169
- required: true,
1170
- fieldName: recordConfig?.fields?.createdAt || 'createdAt'
1171
- },
1172
- ...recordFields || {},
1173
- ...recordConfig?.additionalFields || {}
1174
- },
1175
- order: 4
1176
- };
438
+ static fromResponse(response, data) {
439
+ let message = `HTTP error ${response.status}`;
440
+ let errorCode = `HTTP ${response.status}`;
441
+ let errorMeta = {};
442
+ if (data && 'object' == typeof data && null !== data) {
443
+ const errorObj = data;
444
+ if ('string' == typeof errorObj.message) message = errorObj.message;
445
+ if ('string' == typeof errorObj.code) errorCode = errorObj.code;
446
+ if ('object' == typeof errorObj.data && null !== errorObj.data) errorMeta = errorObj.data;
447
+ }
448
+ return new error_class_DoubleTieError(message, {
449
+ code: errorCode,
450
+ status: response.status,
451
+ meta: errorMeta
452
+ });
1177
453
  }
1178
- const consentSchema = external_zod_namespaceObject.z.object({
1179
- id: external_zod_namespaceObject.z.string(),
1180
- subjectId: external_zod_namespaceObject.z.string(),
1181
- domainId: external_zod_namespaceObject.z.string(),
1182
- purposeIds: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()),
1183
- metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).nullable().optional(),
1184
- policyId: external_zod_namespaceObject.z.string().optional(),
1185
- ipAddress: external_zod_namespaceObject.z.string().nullable().optional(),
1186
- userAgent: external_zod_namespaceObject.z.string().nullable().optional(),
1187
- status: external_zod_namespaceObject.z["enum"]([
1188
- 'active',
1189
- 'withdrawn',
1190
- 'expired'
1191
- ]).default('active'),
1192
- withdrawalReason: external_zod_namespaceObject.z.string().nullable().optional(),
1193
- givenAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1194
- validUntil: external_zod_namespaceObject.z.date().nullable().optional(),
1195
- isActive: external_zod_namespaceObject.z.boolean().default(true)
1196
- });
1197
- function getConsentTable(options, consentFields) {
1198
- const consentConfig = options.tables?.consent;
1199
- const subjectConfig = options.tables?.subject;
1200
- const domainConfig = options.tables?.domain;
1201
- const policyConfig = options.tables?.consentPolicy;
1202
- return {
1203
- entityName: consentConfig?.entityName || 'consent',
1204
- entityPrefix: consentConfig?.entityPrefix || 'cns',
1205
- schema: consentSchema,
1206
- fields: {
1207
- subjectId: {
1208
- type: 'string',
1209
- required: true,
1210
- fieldName: consentConfig?.fields?.subjectId || 'subjectId',
1211
- references: {
1212
- model: subjectConfig?.entityName || 'subject',
1213
- field: 'id'
1214
- }
1215
- },
1216
- domainId: {
1217
- type: 'string',
1218
- required: true,
1219
- fieldName: consentConfig?.fields?.domainId || 'domainId',
1220
- references: {
1221
- model: domainConfig?.entityName || 'domain',
1222
- field: 'id'
1223
- }
1224
- },
1225
- purposeIds: {
1226
- type: 'json',
1227
- required: false,
1228
- fieldName: consentConfig?.fields?.purposeIds || 'purposeIds'
1229
- },
1230
- metadata: {
1231
- type: 'json',
1232
- required: false,
1233
- fieldName: consentConfig?.fields?.metadata || 'metadata'
1234
- },
1235
- policyId: {
1236
- type: 'string',
1237
- required: false,
1238
- fieldName: consentConfig?.fields?.policyId || 'policyId',
1239
- references: {
1240
- model: policyConfig?.entityName || 'consentPolicy',
1241
- field: 'id'
1242
- }
1243
- },
1244
- ipAddress: {
1245
- type: 'string',
1246
- required: false,
1247
- fieldName: consentConfig?.fields?.ipAddress || 'ipAddress'
1248
- },
1249
- userAgent: {
1250
- type: 'string',
1251
- required: false,
1252
- fieldName: consentConfig?.fields?.userAgent || 'userAgent'
1253
- },
1254
- status: {
1255
- type: 'string',
1256
- defaultValue: ()=>'active',
1257
- required: true,
1258
- fieldName: consentConfig?.fields?.status || 'status'
1259
- },
1260
- withdrawalReason: {
1261
- type: 'string',
1262
- required: false,
1263
- fieldName: consentConfig?.fields?.withdrawalReason || 'withdrawalReason'
1264
- },
1265
- givenAt: {
1266
- type: 'date',
1267
- defaultValue: ()=>new Date(),
1268
- required: true,
1269
- fieldName: consentConfig?.fields?.givenAt || 'givenAt'
1270
- },
1271
- validUntil: {
1272
- type: 'date',
1273
- required: false,
1274
- fieldName: consentConfig?.fields?.validUntil || 'validUntil',
1275
- transform: {
1276
- input: (val, data)=>{
1277
- if (val) return val;
1278
- const expiresIn = consentConfig?.expiresIn || 31536000;
1279
- const givenAt = data.givenAt instanceof Date ? data.givenAt : new Date();
1280
- if (expiresIn > 0) {
1281
- const validUntil = new Date(givenAt);
1282
- validUntil.setSeconds(validUntil.getSeconds() + expiresIn);
1283
- return validUntil;
1284
- }
1285
- }
1286
- }
1287
- },
1288
- isActive: {
1289
- type: 'boolean',
1290
- defaultValue: true,
1291
- required: true,
1292
- fieldName: consentConfig?.fields?.isActive || 'isActive'
1293
- },
1294
- ...consentFields || {},
1295
- ...consentConfig?.additionalFields || {}
1296
- },
1297
- order: 3
1298
- };
454
+ withMeta(additionalMeta) {
455
+ return new error_class_DoubleTieError(this.message, {
456
+ code: this.code,
457
+ status: this.statusCode,
458
+ category: this.category,
459
+ cause: this.cause instanceof Error ? this.cause : void 0,
460
+ meta: {
461
+ ...this.meta,
462
+ ...additionalMeta
463
+ }
464
+ });
1299
465
  }
1300
- const domainSchema = external_zod_namespaceObject.z.object({
1301
- id: external_zod_namespaceObject.z.string(),
1302
- name: external_zod_namespaceObject.z.string().min(1),
1303
- description: external_zod_namespaceObject.z.string().optional(),
1304
- allowedOrigins: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional().default([]),
1305
- isVerified: external_zod_namespaceObject.z.boolean().default(true),
1306
- isActive: external_zod_namespaceObject.z.boolean().default(true),
1307
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1308
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1309
- });
1310
- function getDomainTable(options, domainFields) {
1311
- const domainConfig = options.tables?.domain;
1312
- return {
1313
- entityName: domainConfig?.entityName || 'domain',
1314
- entityPrefix: domainConfig?.entityPrefix || 'dom',
1315
- schema: domainSchema,
1316
- fields: {
1317
- name: {
1318
- type: 'string',
1319
- required: true,
1320
- unique: true,
1321
- fieldName: domainConfig?.fields?.name || 'name'
1322
- },
1323
- description: {
1324
- type: 'string',
1325
- required: false,
1326
- fieldName: domainConfig?.fields?.description || "description"
1327
- },
1328
- allowedOrigins: {
1329
- type: 'json',
1330
- defaultValue: ()=>[],
1331
- required: false,
1332
- fieldName: domainConfig?.fields?.allowedOrigins || 'allowedOrigins'
1333
- },
1334
- isVerified: {
1335
- type: 'boolean',
1336
- defaultValue: true,
1337
- required: true,
1338
- fieldName: domainConfig?.fields?.isVerified || 'isVerified'
1339
- },
1340
- isActive: {
1341
- type: 'boolean',
1342
- defaultValue: true,
1343
- required: true,
1344
- fieldName: domainConfig?.fields?.isActive || 'isActive'
1345
- },
1346
- createdAt: {
1347
- type: 'date',
1348
- defaultValue: ()=>new Date(),
1349
- required: true,
1350
- fieldName: domainConfig?.fields?.createdAt || 'createdAt'
1351
- },
1352
- updatedAt: {
1353
- type: 'date',
1354
- required: false,
1355
- fieldName: domainConfig?.fields?.updatedAt || 'updatedAt'
1356
- },
1357
- ...domainFields || {},
1358
- ...domainConfig?.additionalFields || {}
1359
- },
1360
- order: 1
466
+ static createSubclass(name) {
467
+ const ErrorSubclass = class extends error_class_DoubleTieError {
468
+ constructor(message, options){
469
+ super(message, options);
470
+ Object.defineProperty(this, 'name', {
471
+ value: name
472
+ });
473
+ }
1361
474
  };
475
+ Object.defineProperty(ErrorSubclass, 'name', {
476
+ value: name
477
+ });
478
+ return ErrorSubclass;
1362
479
  }
1363
- const subjectSchema = external_zod_namespaceObject.z.object({
1364
- id: external_zod_namespaceObject.z.string(),
1365
- isIdentified: external_zod_namespaceObject.z.boolean().default(false),
1366
- externalId: external_zod_namespaceObject.z.string().nullable().optional(),
1367
- identityProvider: external_zod_namespaceObject.z.string().optional(),
1368
- lastIpAddress: external_zod_namespaceObject.z.string().optional(),
1369
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1370
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1371
- });
1372
- function getSubjectTable(options, subjectFields) {
1373
- const subjectConfig = options.tables?.subject;
1374
- return {
1375
- entityName: subjectConfig?.entityName || 'subject',
1376
- entityPrefix: subjectConfig?.entityPrefix || 'sub',
1377
- schema: subjectSchema,
1378
- fields: {
1379
- isIdentified: {
1380
- type: 'boolean',
1381
- defaultValue: ()=>false,
1382
- required: true,
1383
- fieldName: subjectConfig?.fields?.isIdentified || 'isIdentified'
1384
- },
1385
- externalId: {
1386
- type: 'string',
1387
- required: false,
1388
- fieldName: subjectConfig?.fields?.externalId || 'externalId'
1389
- },
1390
- identityProvider: {
1391
- type: 'string',
1392
- required: false,
1393
- fieldName: subjectConfig?.fields?.identityProvider || 'identityProvider'
1394
- },
1395
- lastIpAddress: {
1396
- type: 'string',
1397
- required: false,
1398
- fieldName: subjectConfig?.fields?.lastIpAddress || 'lastIpAddress'
1399
- },
1400
- createdAt: {
1401
- type: 'date',
1402
- defaultValue: ()=>new Date(),
1403
- required: true,
1404
- fieldName: subjectConfig?.fields?.createdAt || 'createdAt'
1405
- },
1406
- updatedAt: {
1407
- type: 'date',
1408
- defaultValue: ()=>new Date(),
1409
- required: true,
1410
- fieldName: subjectConfig?.fields?.updatedAt || 'updatedAt'
1411
- },
1412
- subjectTimezone: {
1413
- type: 'timezone',
1414
- required: false,
1415
- defaultValue: COMMON_TIMEZONES.UTC,
1416
- fieldName: subjectConfig?.fields?.subjectTimezone || 'subjectTimezone'
1417
- },
1418
- ...subjectFields || {},
1419
- ...subjectConfig?.additionalFields || {}
1420
- },
1421
- order: 1
1422
- };
480
+ static formatValidationError(error) {
481
+ if (!error.meta) return error.message;
482
+ let formattedMessage = `${error.message} (${error.code})`;
483
+ if (error.meta.validationErrors) formattedMessage += `\nValidation Errors: ${JSON.stringify(error.meta.validationErrors, null, 2)}`;
484
+ const otherMeta = Object.fromEntries(Object.entries(error.meta).filter(([key])=>'validationErrors' !== key));
485
+ if (Object.keys(otherMeta).length > 0) formattedMessage += `\nAdditional Context: ${JSON.stringify(otherMeta, null, 2)}`;
486
+ return formattedMessage;
1423
487
  }
1424
- const getConsentTables = (options)=>{
1425
- const pluginSchema = options.plugins?.reduce((acc, plugin)=>{
1426
- const schema = plugin.schema;
1427
- if (!schema) return acc;
1428
- for (const [key, value] of Object.entries(schema))acc[key] = {
1429
- fields: {
1430
- ...acc[key]?.fields,
1431
- ...value.fields
1432
- },
1433
- entityName: key
1434
- };
1435
- return acc;
1436
- }, {});
1437
- const { subject, consentPurpose, consentPolicy, domain, geoLocation, consent, consentPurposeJunction, record, consentGeoLocation, consentWithdrawal, auditLog, ...pluginTables } = pluginSchema || {};
1438
- return {
1439
- subject: getSubjectTable(options, subject?.fields),
1440
- consentPurpose: getPurposeTable(options, consentPurpose?.fields),
1441
- consentPolicy: getConsentPolicyTable(options, consentPolicy?.fields),
1442
- domain: getDomainTable(options, domain?.fields),
1443
- consent: getConsentTable(options, consent?.fields),
1444
- consentRecord: getConsentRecordTable(options, record?.fields),
1445
- auditLog: getAuditLogTable(options, auditLog?.fields),
1446
- ...pluginTables
1447
- };
488
+ }
489
+ const logger_namespaceObject = require("@doubletie/logger");
490
+ const auditLogSchema = external_zod_namespaceObject.z.object({
491
+ id: external_zod_namespaceObject.z.string(),
492
+ entityType: external_zod_namespaceObject.z.string(),
493
+ entityId: external_zod_namespaceObject.z.string(),
494
+ actionType: external_zod_namespaceObject.z.string(),
495
+ subjectId: external_zod_namespaceObject.z.string().optional(),
496
+ ipAddress: external_zod_namespaceObject.z.string().optional(),
497
+ userAgent: external_zod_namespaceObject.z.string().optional(),
498
+ changes: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
499
+ metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
500
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date())
501
+ });
502
+ function getAuditLogTable(options, auditLogFields) {
503
+ const auditLogConfig = options.tables?.auditLog;
504
+ const subjectConfig = options.tables?.subject;
505
+ return {
506
+ entityName: auditLogConfig?.entityName || 'auditLog',
507
+ entityPrefix: auditLogConfig?.entityPrefix || 'log',
508
+ schema: auditLogSchema,
509
+ fields: {
510
+ entityType: {
511
+ type: 'string',
512
+ required: true,
513
+ fieldName: auditLogConfig?.fields?.entityType || 'entityType'
514
+ },
515
+ entityId: {
516
+ type: 'string',
517
+ required: true,
518
+ fieldName: auditLogConfig?.fields?.entityId || 'entityId'
519
+ },
520
+ actionType: {
521
+ type: 'string',
522
+ required: true,
523
+ fieldName: auditLogConfig?.fields?.actionType || 'actionType'
524
+ },
525
+ subjectId: {
526
+ type: 'string',
527
+ required: false,
528
+ fieldName: auditLogConfig?.fields?.subjectId || 'subjectId',
529
+ references: {
530
+ model: subjectConfig?.entityName || 'subject',
531
+ field: 'id'
532
+ }
533
+ },
534
+ ipAddress: {
535
+ type: 'string',
536
+ required: false,
537
+ fieldName: auditLogConfig?.fields?.ipAddress || 'ipAddress'
538
+ },
539
+ userAgent: {
540
+ type: 'string',
541
+ required: false,
542
+ fieldName: auditLogConfig?.fields?.userAgent || 'userAgent'
543
+ },
544
+ changes: {
545
+ type: 'json',
546
+ required: false,
547
+ fieldName: auditLogConfig?.fields?.changes || 'changes'
548
+ },
549
+ metadata: {
550
+ type: 'json',
551
+ required: false,
552
+ fieldName: auditLogConfig?.fields?.metadata || 'metadata'
553
+ },
554
+ createdAt: {
555
+ type: 'date',
556
+ defaultValue: ()=>new Date(),
557
+ required: true,
558
+ fieldName: auditLogConfig?.fields?.createdAt || 'createdAt'
559
+ },
560
+ eventTimezone: {
561
+ type: 'timezone',
562
+ required: true,
563
+ defaultValue: COMMON_TIMEZONES.UTC,
564
+ fieldName: auditLogConfig?.fields?.eventTimezone || 'eventTimezone'
565
+ },
566
+ ...auditLogFields || {},
567
+ ...auditLogConfig?.additionalFields || {}
568
+ },
569
+ indexes: [
570
+ {
571
+ name: 'entity_index',
572
+ fields: [
573
+ 'entityType',
574
+ 'entityId'
575
+ ]
576
+ },
577
+ {
578
+ name: 'action_type_index',
579
+ fields: [
580
+ 'actionType'
581
+ ]
582
+ },
583
+ {
584
+ name: 'subject_id_index',
585
+ fields: [
586
+ 'subjectId'
587
+ ]
588
+ },
589
+ {
590
+ name: 'created_at_index',
591
+ fields: [
592
+ 'createdAt'
593
+ ]
594
+ }
595
+ ],
596
+ order: 5
1448
597
  };
1449
- function validateEntityOutput(tableName, data, options) {
1450
- const tables = getConsentTables(options);
1451
- const table = tables[tableName];
1452
- if (!table) throw new Error(`Table ${tableName} not found`);
1453
- const processedData = {
1454
- ...data
1455
- };
1456
- for (const [field, def] of Object.entries(table.fields))if ('date' === def.type && 'string' == typeof processedData[field]) processedData[field] = new Date(processedData[field]);
1457
- try {
1458
- return table.schema.parse(processedData);
1459
- } catch (error) {
1460
- if (error instanceof ZodError.ZodError) logger_factory_logger.error(`[validateEntityOutput] Validation failed for table ${String(tableName)}`, {
1461
- table,
1462
- issues: error.issues
1463
- });
1464
- throw error;
1465
- }
1466
- }
1467
- function subjectRegistry({ adapter, ...ctx }) {
1468
- const { createWithHooks } = getWithHooks(adapter, ctx);
1469
- return {
1470
- createSubject: async (subject, context)=>{
1471
- const createdSubject = await createWithHooks({
1472
- data: {
1473
- createdAt: new Date(),
1474
- updatedAt: new Date(),
1475
- ...subject
1476
- },
1477
- model: 'subject',
1478
- customFn: void 0,
1479
- context
1480
- });
1481
- return createdSubject ? validateEntityOutput('subject', createdSubject, ctx.options) : null;
598
+ }
599
+ const PolicyTypeSchema = external_zod_namespaceObject.z["enum"]([
600
+ 'cookie_banner',
601
+ 'privacy_policy',
602
+ 'dpa',
603
+ 'terms_and_conditions',
604
+ 'marketing_communications',
605
+ 'age_verification',
606
+ 'other'
607
+ ]);
608
+ const consentPolicySchema = external_zod_namespaceObject.z.object({
609
+ id: external_zod_namespaceObject.z.string(),
610
+ version: external_zod_namespaceObject.z.string(),
611
+ type: PolicyTypeSchema,
612
+ name: external_zod_namespaceObject.z.string(),
613
+ effectiveDate: external_zod_namespaceObject.z.date(),
614
+ expirationDate: external_zod_namespaceObject.z.date().nullable().optional(),
615
+ content: external_zod_namespaceObject.z.string(),
616
+ contentHash: external_zod_namespaceObject.z.string(),
617
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
618
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
619
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
620
+ });
621
+ function getConsentPolicyTable(options, policyFields) {
622
+ const consentPolicyConfig = options.tables?.consentPolicy;
623
+ return {
624
+ entityName: consentPolicyConfig?.entityName || 'consentPolicy',
625
+ entityPrefix: consentPolicyConfig?.entityPrefix || 'pol',
626
+ schema: consentPolicySchema,
627
+ fields: {
628
+ version: {
629
+ type: 'string',
630
+ required: true,
631
+ fieldName: consentPolicyConfig?.fields?.version || 'version'
1482
632
  },
1483
- findOrCreateSubject: async function({ subjectId, externalSubjectId, ipAddress = 'unknown', context }) {
1484
- if (subjectId && externalSubjectId) {
1485
- const [subjectById, subjectByExternalId] = await Promise.all([
1486
- this.findSubjectById(subjectId),
1487
- this.findSubjectByExternalId(externalSubjectId)
1488
- ]);
1489
- if (!subjectById || !subjectByExternalId) {
1490
- ctx.logger?.error('Subject validation failed: One or both subjects not found', {
1491
- providedSubjectId: subjectId,
1492
- providedExternalId: externalSubjectId,
1493
- subjectByIdFound: !!subjectById,
1494
- subjectByExternalIdFound: !!subjectByExternalId
1495
- });
1496
- throw new error_class_DoubleTieError('The specified subject could not be found. Please verify the subject identifiers and try again.', {
1497
- code: error_codes_ERROR_CODES.NOT_FOUND,
1498
- status: 404,
1499
- meta: {
1500
- providedSubjectId: subjectId,
1501
- providedExternalId: externalSubjectId
1502
- }
1503
- });
1504
- }
1505
- if (subjectById.id !== subjectByExternalId.id) {
1506
- ctx.logger?.warn('Subject validation failed: IDs do not match the same subject', {
1507
- providedSubjectId: subjectId,
1508
- providedExternalId: externalSubjectId,
1509
- subjectByIdId: subjectById.id,
1510
- subjectByExternalIdId: subjectByExternalId.id
1511
- });
1512
- throw new error_class_DoubleTieError('The provided subjectId and externalSubjectId do not match the same subject. Please ensure both identifiers refer to the same subject.', {
1513
- code: error_codes_ERROR_CODES.CONFLICT,
1514
- status: 409,
1515
- meta: {
1516
- providedSubjectId: subjectId,
1517
- providedExternalId: externalSubjectId,
1518
- subjectByIdId: subjectById.id,
1519
- subjectByExternalIdId: subjectByExternalId.id
1520
- }
1521
- });
1522
- }
1523
- return subjectById;
633
+ type: {
634
+ type: 'string',
635
+ required: true,
636
+ fieldName: consentPolicyConfig?.fields?.type || 'type'
637
+ },
638
+ name: {
639
+ type: 'string',
640
+ required: true,
641
+ fieldName: consentPolicyConfig?.fields?.name || 'name'
642
+ },
643
+ effectiveDate: {
644
+ type: 'date',
645
+ required: true,
646
+ fieldName: consentPolicyConfig?.fields?.effectiveDate || 'effectiveDate'
647
+ },
648
+ expirationDate: {
649
+ type: 'date',
650
+ required: false,
651
+ fieldName: consentPolicyConfig?.fields?.expirationDate || 'expirationDate'
652
+ },
653
+ content: {
654
+ type: 'string',
655
+ required: true,
656
+ fieldName: consentPolicyConfig?.fields?.content || 'content'
657
+ },
658
+ contentHash: {
659
+ type: 'string',
660
+ required: true,
661
+ fieldName: consentPolicyConfig?.fields?.contentHash || 'contentHash'
662
+ },
663
+ isActive: {
664
+ type: 'boolean',
665
+ defaultValue: true,
666
+ required: true,
667
+ fieldName: consentPolicyConfig?.fields?.isActive || 'isActive'
668
+ },
669
+ createdAt: {
670
+ type: 'date',
671
+ defaultValue: ()=>new Date(),
672
+ required: true,
673
+ fieldName: consentPolicyConfig?.fields?.createdAt || 'createdAt'
674
+ },
675
+ ...policyFields || {},
676
+ ...consentPolicyConfig?.additionalFields || {}
677
+ },
678
+ order: 2
679
+ };
680
+ }
681
+ const purposeSchema = external_zod_namespaceObject.z.object({
682
+ id: external_zod_namespaceObject.z.string(),
683
+ code: external_zod_namespaceObject.z.string(),
684
+ name: external_zod_namespaceObject.z.string(),
685
+ description: external_zod_namespaceObject.z.string(),
686
+ isEssential: external_zod_namespaceObject.z.boolean().default(false),
687
+ dataCategory: external_zod_namespaceObject.z.string().optional(),
688
+ legalBasis: external_zod_namespaceObject.z.string().optional(),
689
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
690
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
691
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
692
+ });
693
+ function getPurposeTable(options, purposeFields) {
694
+ const purposeConfig = options.tables?.consentPurpose;
695
+ return {
696
+ entityName: purposeConfig?.entityName || 'consentPurpose',
697
+ entityPrefix: purposeConfig?.entityPrefix || 'pur',
698
+ schema: purposeSchema,
699
+ fields: {
700
+ code: {
701
+ type: 'string',
702
+ required: true,
703
+ fieldName: purposeConfig?.fields?.code || 'code'
704
+ },
705
+ name: {
706
+ type: 'string',
707
+ required: true,
708
+ fieldName: purposeConfig?.fields?.name || 'name'
709
+ },
710
+ description: {
711
+ type: 'string',
712
+ required: true,
713
+ fieldName: purposeConfig?.fields?.description || "description"
714
+ },
715
+ isEssential: {
716
+ type: 'boolean',
717
+ defaultValue: ()=>false,
718
+ required: true,
719
+ fieldName: purposeConfig?.fields?.isEssential || 'isEssential'
720
+ },
721
+ dataCategory: {
722
+ type: 'string',
723
+ required: false,
724
+ fieldName: purposeConfig?.fields?.dataCategory || 'dataCategory'
725
+ },
726
+ legalBasis: {
727
+ type: 'string',
728
+ required: false,
729
+ fieldName: purposeConfig?.fields?.legalBasis || 'legalBasis'
730
+ },
731
+ isActive: {
732
+ type: 'boolean',
733
+ defaultValue: true,
734
+ required: true,
735
+ fieldName: purposeConfig?.fields?.isActive || 'isActive'
736
+ },
737
+ createdAt: {
738
+ type: 'date',
739
+ defaultValue: ()=>new Date(),
740
+ required: true,
741
+ fieldName: purposeConfig?.fields?.createdAt || 'createdAt'
742
+ },
743
+ updatedAt: {
744
+ type: 'date',
745
+ defaultValue: ()=>new Date(),
746
+ required: true,
747
+ fieldName: purposeConfig?.fields?.updatedAt || 'updatedAt'
748
+ },
749
+ ...purposeFields || {},
750
+ ...purposeConfig?.additionalFields || {}
751
+ },
752
+ order: 1
753
+ };
754
+ }
755
+ const consentRecordSchema = external_zod_namespaceObject.z.object({
756
+ id: external_zod_namespaceObject.z.string(),
757
+ subjectId: external_zod_namespaceObject.z.string(),
758
+ consentId: external_zod_namespaceObject.z.string().optional(),
759
+ actionType: external_zod_namespaceObject.z.string(),
760
+ details: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
761
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
762
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
763
+ });
764
+ function getConsentRecordTable(options, recordFields) {
765
+ const recordConfig = options.tables?.record;
766
+ const subjectConfig = options.tables?.subject;
767
+ const consentConfig = options.tables?.consent;
768
+ return {
769
+ entityName: recordConfig?.entityName || 'consentRecord',
770
+ entityPrefix: recordConfig?.entityPrefix || 'rec',
771
+ schema: consentRecordSchema,
772
+ fields: {
773
+ subjectId: {
774
+ type: 'string',
775
+ required: true,
776
+ fieldName: recordConfig?.fields?.subjectId || 'subjectId',
777
+ references: {
778
+ model: subjectConfig?.entityName || 'subject',
779
+ field: 'id'
1524
780
  }
1525
- if (subjectId) {
1526
- const subject = await this.findSubjectById(subjectId);
1527
- if (subject) return subject;
1528
- throw new error_class_DoubleTieError('Subject not found by subjectId', {
1529
- code: error_codes_ERROR_CODES.NOT_FOUND,
1530
- status: 404
1531
- });
781
+ },
782
+ consentId: {
783
+ type: 'string',
784
+ required: false,
785
+ fieldName: recordConfig?.fields?.consentId || 'consentId',
786
+ references: {
787
+ model: consentConfig?.entityName || 'consent',
788
+ field: 'id'
1532
789
  }
1533
- if (externalSubjectId) try {
1534
- const subject = await this.findSubjectByExternalId(externalSubjectId);
1535
- if (subject) {
1536
- ctx.logger?.debug('Found existing subject by external ID', {
1537
- externalSubjectId
1538
- });
1539
- return subject;
1540
- }
1541
- ctx.logger?.info('Creating new subject with external ID', {
1542
- externalSubjectId
1543
- });
1544
- return await this.createSubject({
1545
- externalId: externalSubjectId,
1546
- identityProvider: 'external',
1547
- lastIpAddress: ipAddress,
1548
- isIdentified: true
1549
- }, context);
1550
- } catch (error) {
1551
- if (error instanceof Error && error.message.includes('unique constraint')) {
1552
- ctx.logger?.info('Handling duplicate key violation for external ID', {
1553
- externalSubjectId
1554
- });
1555
- const subject = await this.findSubjectByExternalId(externalSubjectId);
1556
- if (subject) return subject;
790
+ },
791
+ actionType: {
792
+ type: 'string',
793
+ required: true,
794
+ fieldName: recordConfig?.fields?.actionType || 'actionType'
795
+ },
796
+ details: {
797
+ type: 'json',
798
+ required: false,
799
+ fieldName: recordConfig?.fields?.details || 'details'
800
+ },
801
+ createdAt: {
802
+ type: 'date',
803
+ defaultValue: ()=>new Date(),
804
+ required: true,
805
+ fieldName: recordConfig?.fields?.createdAt || 'createdAt'
806
+ },
807
+ ...recordFields || {},
808
+ ...recordConfig?.additionalFields || {}
809
+ },
810
+ order: 4
811
+ };
812
+ }
813
+ const consentSchema = external_zod_namespaceObject.z.object({
814
+ id: external_zod_namespaceObject.z.string(),
815
+ subjectId: external_zod_namespaceObject.z.string(),
816
+ domainId: external_zod_namespaceObject.z.string(),
817
+ purposeIds: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()),
818
+ metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).nullable().optional(),
819
+ policyId: external_zod_namespaceObject.z.string().optional(),
820
+ ipAddress: external_zod_namespaceObject.z.string().nullable().optional(),
821
+ userAgent: external_zod_namespaceObject.z.string().nullable().optional(),
822
+ status: external_zod_namespaceObject.z["enum"]([
823
+ 'active',
824
+ 'withdrawn',
825
+ 'expired'
826
+ ]).default('active'),
827
+ withdrawalReason: external_zod_namespaceObject.z.string().nullable().optional(),
828
+ givenAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
829
+ validUntil: external_zod_namespaceObject.z.date().nullable().optional(),
830
+ isActive: external_zod_namespaceObject.z.boolean().default(true)
831
+ });
832
+ function getConsentTable(options, consentFields) {
833
+ const consentConfig = options.tables?.consent;
834
+ const subjectConfig = options.tables?.subject;
835
+ const domainConfig = options.tables?.domain;
836
+ const policyConfig = options.tables?.consentPolicy;
837
+ return {
838
+ entityName: consentConfig?.entityName || 'consent',
839
+ entityPrefix: consentConfig?.entityPrefix || 'cns',
840
+ schema: consentSchema,
841
+ fields: {
842
+ subjectId: {
843
+ type: 'string',
844
+ required: true,
845
+ fieldName: consentConfig?.fields?.subjectId || 'subjectId',
846
+ references: {
847
+ model: subjectConfig?.entityName || 'subject',
848
+ field: 'id'
849
+ }
850
+ },
851
+ domainId: {
852
+ type: 'string',
853
+ required: true,
854
+ fieldName: consentConfig?.fields?.domainId || 'domainId',
855
+ references: {
856
+ model: domainConfig?.entityName || 'domain',
857
+ field: 'id'
858
+ }
859
+ },
860
+ purposeIds: {
861
+ type: 'json',
862
+ required: false,
863
+ fieldName: consentConfig?.fields?.purposeIds || 'purposeIds'
864
+ },
865
+ metadata: {
866
+ type: 'json',
867
+ required: false,
868
+ fieldName: consentConfig?.fields?.metadata || 'metadata'
869
+ },
870
+ policyId: {
871
+ type: 'string',
872
+ required: false,
873
+ fieldName: consentConfig?.fields?.policyId || 'policyId',
874
+ references: {
875
+ model: policyConfig?.entityName || 'consentPolicy',
876
+ field: 'id'
877
+ }
878
+ },
879
+ ipAddress: {
880
+ type: 'string',
881
+ required: false,
882
+ fieldName: consentConfig?.fields?.ipAddress || 'ipAddress'
883
+ },
884
+ userAgent: {
885
+ type: 'string',
886
+ required: false,
887
+ fieldName: consentConfig?.fields?.userAgent || 'userAgent'
888
+ },
889
+ status: {
890
+ type: 'string',
891
+ defaultValue: ()=>'active',
892
+ required: true,
893
+ fieldName: consentConfig?.fields?.status || 'status'
894
+ },
895
+ withdrawalReason: {
896
+ type: 'string',
897
+ required: false,
898
+ fieldName: consentConfig?.fields?.withdrawalReason || 'withdrawalReason'
899
+ },
900
+ givenAt: {
901
+ type: 'date',
902
+ defaultValue: ()=>new Date(),
903
+ required: true,
904
+ fieldName: consentConfig?.fields?.givenAt || 'givenAt'
905
+ },
906
+ validUntil: {
907
+ type: 'date',
908
+ required: false,
909
+ fieldName: consentConfig?.fields?.validUntil || 'validUntil',
910
+ transform: {
911
+ input: (val, data)=>{
912
+ if (val) return val;
913
+ const expiresIn = consentConfig?.expiresIn || 31536000;
914
+ const givenAt = data.givenAt instanceof Date ? data.givenAt : new Date();
915
+ if (expiresIn > 0) {
916
+ const validUntil = new Date(givenAt);
917
+ validUntil.setSeconds(validUntil.getSeconds() + expiresIn);
918
+ return validUntil;
919
+ }
1557
920
  }
1558
- ctx.logger?.error('Failed to create or find subject with external ID', {
1559
- externalSubjectId,
1560
- error: error instanceof Error ? error.message : 'Unknown error'
921
+ }
922
+ },
923
+ isActive: {
924
+ type: 'boolean',
925
+ defaultValue: true,
926
+ required: true,
927
+ fieldName: consentConfig?.fields?.isActive || 'isActive'
928
+ },
929
+ ...consentFields || {},
930
+ ...consentConfig?.additionalFields || {}
931
+ },
932
+ order: 3
933
+ };
934
+ }
935
+ const domainSchema = external_zod_namespaceObject.z.object({
936
+ id: external_zod_namespaceObject.z.string(),
937
+ name: external_zod_namespaceObject.z.string().min(1),
938
+ description: external_zod_namespaceObject.z.string().optional(),
939
+ allowedOrigins: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional().default([]),
940
+ isVerified: external_zod_namespaceObject.z.boolean().default(true),
941
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
942
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
943
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
944
+ });
945
+ function getDomainTable(options, domainFields) {
946
+ const domainConfig = options.tables?.domain;
947
+ return {
948
+ entityName: domainConfig?.entityName || 'domain',
949
+ entityPrefix: domainConfig?.entityPrefix || 'dom',
950
+ schema: domainSchema,
951
+ fields: {
952
+ name: {
953
+ type: 'string',
954
+ required: true,
955
+ unique: true,
956
+ fieldName: domainConfig?.fields?.name || 'name'
957
+ },
958
+ description: {
959
+ type: 'string',
960
+ required: false,
961
+ fieldName: domainConfig?.fields?.description || "description"
962
+ },
963
+ allowedOrigins: {
964
+ type: 'json',
965
+ defaultValue: ()=>[],
966
+ required: false,
967
+ fieldName: domainConfig?.fields?.allowedOrigins || 'allowedOrigins'
968
+ },
969
+ isVerified: {
970
+ type: 'boolean',
971
+ defaultValue: true,
972
+ required: true,
973
+ fieldName: domainConfig?.fields?.isVerified || 'isVerified'
974
+ },
975
+ isActive: {
976
+ type: 'boolean',
977
+ defaultValue: true,
978
+ required: true,
979
+ fieldName: domainConfig?.fields?.isActive || 'isActive'
980
+ },
981
+ createdAt: {
982
+ type: 'date',
983
+ defaultValue: ()=>new Date(),
984
+ required: true,
985
+ fieldName: domainConfig?.fields?.createdAt || 'createdAt'
986
+ },
987
+ updatedAt: {
988
+ type: 'date',
989
+ required: false,
990
+ fieldName: domainConfig?.fields?.updatedAt || 'updatedAt'
991
+ },
992
+ ...domainFields || {},
993
+ ...domainConfig?.additionalFields || {}
994
+ },
995
+ order: 1
996
+ };
997
+ }
998
+ const subjectSchema = external_zod_namespaceObject.z.object({
999
+ id: external_zod_namespaceObject.z.string(),
1000
+ isIdentified: external_zod_namespaceObject.z.boolean().default(false),
1001
+ externalId: external_zod_namespaceObject.z.string().nullable().optional(),
1002
+ identityProvider: external_zod_namespaceObject.z.string().optional(),
1003
+ lastIpAddress: external_zod_namespaceObject.z.string().optional(),
1004
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1005
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1006
+ });
1007
+ function getSubjectTable(options, subjectFields) {
1008
+ const subjectConfig = options.tables?.subject;
1009
+ return {
1010
+ entityName: subjectConfig?.entityName || 'subject',
1011
+ entityPrefix: subjectConfig?.entityPrefix || 'sub',
1012
+ schema: subjectSchema,
1013
+ fields: {
1014
+ isIdentified: {
1015
+ type: 'boolean',
1016
+ defaultValue: ()=>false,
1017
+ required: true,
1018
+ fieldName: subjectConfig?.fields?.isIdentified || 'isIdentified'
1019
+ },
1020
+ externalId: {
1021
+ type: 'string',
1022
+ required: false,
1023
+ fieldName: subjectConfig?.fields?.externalId || 'externalId'
1024
+ },
1025
+ identityProvider: {
1026
+ type: 'string',
1027
+ required: false,
1028
+ fieldName: subjectConfig?.fields?.identityProvider || 'identityProvider'
1029
+ },
1030
+ lastIpAddress: {
1031
+ type: 'string',
1032
+ required: false,
1033
+ fieldName: subjectConfig?.fields?.lastIpAddress || 'lastIpAddress'
1034
+ },
1035
+ createdAt: {
1036
+ type: 'date',
1037
+ defaultValue: ()=>new Date(),
1038
+ required: true,
1039
+ fieldName: subjectConfig?.fields?.createdAt || 'createdAt'
1040
+ },
1041
+ updatedAt: {
1042
+ type: 'date',
1043
+ defaultValue: ()=>new Date(),
1044
+ required: true,
1045
+ fieldName: subjectConfig?.fields?.updatedAt || 'updatedAt'
1046
+ },
1047
+ subjectTimezone: {
1048
+ type: 'timezone',
1049
+ required: false,
1050
+ defaultValue: COMMON_TIMEZONES.UTC,
1051
+ fieldName: subjectConfig?.fields?.subjectTimezone || 'subjectTimezone'
1052
+ },
1053
+ ...subjectFields || {},
1054
+ ...subjectConfig?.additionalFields || {}
1055
+ },
1056
+ order: 1
1057
+ };
1058
+ }
1059
+ const getConsentTables = (options)=>{
1060
+ const pluginSchema = options.plugins?.reduce((acc, plugin)=>{
1061
+ const schema = plugin.schema;
1062
+ if (!schema) return acc;
1063
+ for (const [key, value] of Object.entries(schema))acc[key] = {
1064
+ fields: {
1065
+ ...acc[key]?.fields,
1066
+ ...value.fields
1067
+ },
1068
+ entityName: key
1069
+ };
1070
+ return acc;
1071
+ }, {});
1072
+ const { subject, consentPurpose, consentPolicy, domain, geoLocation, consent, consentPurposeJunction, record, consentGeoLocation, consentWithdrawal, auditLog, ...pluginTables } = pluginSchema || {};
1073
+ return {
1074
+ subject: getSubjectTable(options, subject?.fields),
1075
+ consentPurpose: getPurposeTable(options, consentPurpose?.fields),
1076
+ consentPolicy: getConsentPolicyTable(options, consentPolicy?.fields),
1077
+ domain: getDomainTable(options, domain?.fields),
1078
+ consent: getConsentTable(options, consent?.fields),
1079
+ consentRecord: getConsentRecordTable(options, record?.fields),
1080
+ auditLog: getAuditLogTable(options, auditLog?.fields),
1081
+ ...pluginTables
1082
+ };
1083
+ };
1084
+ function validateEntityOutput(tableName, data, options) {
1085
+ const tables = getConsentTables(options);
1086
+ const table = tables[tableName];
1087
+ if (!table) throw new Error(`Table ${tableName} not found`);
1088
+ const processedData = {
1089
+ ...data
1090
+ };
1091
+ for (const [field, def] of Object.entries(table.fields))if ('date' === def.type && 'string' == typeof processedData[field]) processedData[field] = new Date(processedData[field]);
1092
+ try {
1093
+ return table.schema.parse(processedData);
1094
+ } catch (error) {
1095
+ if (error instanceof external_zod_namespaceObject.ZodError) logger_namespaceObject.logger.error(`[validateEntityOutput] Validation failed for table ${String(tableName)}`, {
1096
+ table,
1097
+ issues: error.issues
1098
+ });
1099
+ throw error;
1100
+ }
1101
+ }
1102
+ function subjectRegistry({ adapter, ...ctx }) {
1103
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1104
+ return {
1105
+ createSubject: async (subject, context)=>{
1106
+ const createdSubject = await createWithHooks({
1107
+ data: {
1108
+ createdAt: new Date(),
1109
+ updatedAt: new Date(),
1110
+ ...subject
1111
+ },
1112
+ model: 'subject',
1113
+ customFn: void 0,
1114
+ context
1115
+ });
1116
+ return createdSubject ? validateEntityOutput('subject', createdSubject, ctx.options) : null;
1117
+ },
1118
+ findOrCreateSubject: async function({ subjectId, externalSubjectId, ipAddress = 'unknown', context }) {
1119
+ if (subjectId && externalSubjectId) {
1120
+ const [subjectById, subjectByExternalId] = await Promise.all([
1121
+ this.findSubjectById(subjectId),
1122
+ this.findSubjectByExternalId(externalSubjectId)
1123
+ ]);
1124
+ if (!subjectById || !subjectByExternalId) {
1125
+ ctx.logger?.error('Subject validation failed: One or both subjects not found', {
1126
+ providedSubjectId: subjectId,
1127
+ providedExternalId: externalSubjectId,
1128
+ subjectByIdFound: !!subjectById,
1129
+ subjectByExternalIdFound: !!subjectByExternalId
1561
1130
  });
1562
- throw new error_class_DoubleTieError('Failed to create or find subject with external ID', {
1563
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1564
- status: 500,
1131
+ throw new error_class_DoubleTieError('The specified subject could not be found. Please verify the subject identifiers and try again.', {
1132
+ code: error_codes_ERROR_CODES.NOT_FOUND,
1133
+ status: 404,
1565
1134
  meta: {
1566
- error: error instanceof Error ? error.message : 'Unknown error'
1135
+ providedSubjectId: subjectId,
1136
+ providedExternalId: externalSubjectId
1567
1137
  }
1568
1138
  });
1569
1139
  }
1570
- try {
1571
- ctx.logger?.info('Creating new anonymous subject');
1572
- return await this.createSubject({
1573
- externalId: null,
1574
- identityProvider: 'anonymous',
1575
- lastIpAddress: ipAddress,
1576
- isIdentified: false
1577
- }, context);
1578
- } catch (error) {
1579
- ctx.logger?.error('Failed to create anonymous subject', {
1580
- ipAddress,
1581
- error: error instanceof Error ? error.message : 'Unknown error'
1140
+ if (subjectById.id !== subjectByExternalId.id) {
1141
+ ctx.logger?.warn('Subject validation failed: IDs do not match the same subject', {
1142
+ providedSubjectId: subjectId,
1143
+ providedExternalId: externalSubjectId,
1144
+ subjectByIdId: subjectById.id,
1145
+ subjectByExternalIdId: subjectByExternalId.id
1582
1146
  });
1583
- throw new error_class_DoubleTieError('Failed to create anonymous subject', {
1584
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1585
- status: 500,
1147
+ throw new error_class_DoubleTieError('The provided subjectId and externalSubjectId do not match the same subject. Please ensure both identifiers refer to the same subject.', {
1148
+ code: error_codes_ERROR_CODES.CONFLICT,
1149
+ status: 409,
1586
1150
  meta: {
1587
- error: error instanceof Error ? error.message : 'Unknown error'
1151
+ providedSubjectId: subjectId,
1152
+ providedExternalId: externalSubjectId,
1153
+ subjectByIdId: subjectById.id,
1154
+ subjectByExternalIdId: subjectByExternalId.id
1588
1155
  }
1589
1156
  });
1590
1157
  }
1591
- },
1592
- findSubjectById: async (subjectId)=>{
1593
- const subject = await adapter.findOne({
1594
- model: 'subject',
1595
- where: [
1596
- {
1597
- field: 'id',
1598
- value: subjectId
1599
- }
1600
- ]
1601
- });
1602
- return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
1603
- },
1604
- findSubjectByExternalId: async (externalId)=>{
1605
- const subject = await adapter.findOne({
1606
- model: 'subject',
1607
- where: [
1608
- {
1609
- field: 'externalId',
1610
- value: externalId
1611
- }
1612
- ]
1158
+ return subjectById;
1159
+ }
1160
+ if (subjectId) {
1161
+ const subject = await this.findSubjectById(subjectId);
1162
+ if (subject) return subject;
1163
+ throw new error_class_DoubleTieError('Subject not found by subjectId', {
1164
+ code: error_codes_ERROR_CODES.NOT_FOUND,
1165
+ status: 404
1613
1166
  });
1614
- return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
1615
1167
  }
1616
- };
1617
- }
1618
- function consentRegistry({ adapter, ...ctx }) {
1619
- const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
1620
- const registry = {
1621
- createConsent: async (consent, context)=>{
1622
- const createdConsent = await createWithHooks({
1623
- data: {
1624
- createdAt: new Date(),
1625
- ...consent
1626
- },
1627
- model: 'consent',
1628
- context
1168
+ if (externalSubjectId) try {
1169
+ const subject = await this.findSubjectByExternalId(externalSubjectId);
1170
+ if (subject) {
1171
+ ctx.logger?.debug('Found existing subject by external ID', {
1172
+ externalSubjectId
1173
+ });
1174
+ return subject;
1175
+ }
1176
+ ctx.logger?.info('Creating new subject with external ID', {
1177
+ externalSubjectId
1629
1178
  });
1630
- if (!createdConsent) throw new error_class_DoubleTieError('Failed to create consent - operation returned null', {
1631
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1632
- status: 500
1179
+ return await this.createSubject({
1180
+ externalId: externalSubjectId,
1181
+ identityProvider: 'external',
1182
+ lastIpAddress: ipAddress,
1183
+ isIdentified: true
1184
+ }, context);
1185
+ } catch (error) {
1186
+ if (error instanceof Error && error.message.includes('unique constraint')) {
1187
+ ctx.logger?.info('Handling duplicate key violation for external ID', {
1188
+ externalSubjectId
1189
+ });
1190
+ const subject = await this.findSubjectByExternalId(externalSubjectId);
1191
+ if (subject) return subject;
1192
+ }
1193
+ ctx.logger?.error('Failed to create or find subject with external ID', {
1194
+ externalSubjectId,
1195
+ error: error instanceof Error ? error.message : 'Unknown error'
1633
1196
  });
1634
- return createdConsent;
1635
- },
1636
- updateConsent: async (consentId, data, context)=>{
1637
- const consent = await updateWithHooks({
1638
- data: {
1639
- ...data
1640
- },
1641
- where: [
1642
- {
1643
- field: 'id',
1644
- value: consentId
1645
- }
1646
- ],
1647
- model: 'consent',
1648
- context
1197
+ throw new error_class_DoubleTieError('Failed to create or find subject with external ID', {
1198
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1199
+ status: 500,
1200
+ meta: {
1201
+ error: error instanceof Error ? error.message : 'Unknown error'
1202
+ }
1649
1203
  });
1650
- return consent ? validateEntityOutput('consent', consent, ctx.options) : null;
1651
1204
  }
1652
- };
1653
- return registry;
1654
- }
1655
- const external_node_crypto_namespaceObject = require("node:crypto");
1656
- function generatePolicyPlaceholder(name, date) {
1657
- const content = `[PLACEHOLDER] This is an automatically generated version of the ${name} policy.\n\nThis placeholder content should be replaced with actual policy terms before being presented to users.\n\nGenerated on: ${date.toISOString()}`;
1658
- const contentHash = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(content).digest('hex');
1659
- return {
1660
- content,
1661
- contentHash
1662
- };
1663
- }
1664
- function policyRegistry({ adapter, ...ctx }) {
1665
- const { createWithHooks } = getWithHooks(adapter, ctx);
1666
- const registry = {
1667
- createConsentPolicy: async (policy, context)=>{
1668
- const createdPolicy = await createWithHooks({
1669
- data: {
1670
- createdAt: new Date(),
1671
- ...policy
1672
- },
1673
- model: 'consentPolicy',
1674
- context
1205
+ try {
1206
+ ctx.logger?.info('Creating new anonymous subject');
1207
+ return await this.createSubject({
1208
+ externalId: null,
1209
+ identityProvider: 'anonymous',
1210
+ lastIpAddress: ipAddress,
1211
+ isIdentified: false
1212
+ }, context);
1213
+ } catch (error) {
1214
+ ctx.logger?.error('Failed to create anonymous subject', {
1215
+ ipAddress,
1216
+ error: error instanceof Error ? error.message : 'Unknown error'
1675
1217
  });
1676
- if (!createdPolicy) throw new error_class_DoubleTieError('Failed to create consent policy - operation returned null', {
1218
+ throw new error_class_DoubleTieError('Failed to create anonymous subject', {
1677
1219
  code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1678
- status: 500
1679
- });
1680
- return createdPolicy;
1681
- },
1682
- findPolicies: async (params = {})=>{
1683
- const whereConditions = [];
1684
- if (!params.includeInactive) whereConditions.push({
1685
- field: 'isActive',
1686
- value: true
1687
- });
1688
- if (params.domainId) whereConditions.push({
1689
- field: 'id',
1690
- value: params.domainId
1691
- });
1692
- if (params.version) whereConditions.push({
1693
- field: 'version',
1694
- value: params.version
1695
- });
1696
- const policies = await adapter.findMany({
1697
- model: 'consentPolicy',
1698
- where: whereConditions,
1699
- sortBy: {
1700
- field: 'effectiveDate',
1701
- direction: 'desc'
1220
+ status: 500,
1221
+ meta: {
1222
+ error: error instanceof Error ? error.message : 'Unknown error'
1702
1223
  }
1703
1224
  });
1704
- return policies.map((policy)=>validateEntityOutput('consentPolicy', policy, ctx.options));
1705
- },
1706
- findConsentPolicyById: async (policyId)=>{
1707
- const policy = await adapter.findOne({
1708
- model: 'consentPolicy',
1709
- where: [
1710
- {
1711
- field: 'id',
1712
- value: policyId
1713
- }
1714
- ]
1715
- });
1716
- return policy ? validateEntityOutput('consentPolicy', policy, ctx.options) : null;
1717
- },
1718
- findOrCreatePolicy: async (type)=>adapter.transaction({
1719
- callback: async (txAdapter)=>{
1720
- const now = new Date();
1721
- const txRegistry = policyRegistry({
1722
- adapter: txAdapter,
1723
- ...ctx
1724
- });
1725
- const rawLatestPolicy = await txAdapter.findOne({
1726
- model: 'consentPolicy',
1727
- where: [
1728
- {
1729
- field: 'isActive',
1730
- value: true
1731
- },
1732
- {
1733
- field: 'type',
1734
- value: type
1735
- }
1736
- ],
1737
- sortBy: {
1738
- field: 'effectiveDate',
1739
- direction: 'desc'
1740
- }
1741
- });
1742
- const latestPolicy = rawLatestPolicy ? validateEntityOutput('consentPolicy', rawLatestPolicy, ctx.options) : null;
1743
- if (latestPolicy) return latestPolicy;
1744
- const { content: defaultContent, contentHash } = generatePolicyPlaceholder(type, now);
1745
- return txRegistry.createConsentPolicy({
1746
- version: '1.0.0',
1747
- type,
1748
- name: type,
1749
- effectiveDate: now,
1750
- content: defaultContent,
1751
- contentHash,
1752
- isActive: true,
1753
- updatedAt: now,
1754
- expirationDate: null
1755
- });
1225
+ }
1226
+ },
1227
+ findSubjectById: async (subjectId)=>{
1228
+ const subject = await adapter.findOne({
1229
+ model: 'subject',
1230
+ where: [
1231
+ {
1232
+ field: 'id',
1233
+ value: subjectId
1756
1234
  }
1757
- })
1758
- };
1759
- return registry;
1760
- }
1761
- function consentPurposeRegistry({ adapter, ...ctx }) {
1762
- const { createWithHooks } = getWithHooks(adapter, ctx);
1763
- return {
1764
- createConsentPurpose: async (consentPurpose, context)=>{
1765
- const createdPurpose = await createWithHooks({
1766
- data: {
1767
- id: consentPurpose.id || '',
1768
- createdAt: new Date(),
1769
- updatedAt: new Date(),
1770
- ...consentPurpose
1771
- },
1772
- model: 'consentPurpose',
1773
- context
1774
- });
1775
- if (!createdPurpose) throw new error_class_DoubleTieError('Failed to create consent purpose - operation returned null', {
1776
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1777
- status: 500
1778
- });
1779
- return validateEntityOutput('consentPurpose', createdPurpose, ctx.options);
1780
- },
1781
- findConsentPurposeByCode: async (code)=>{
1782
- const consentPurpose = await adapter.findOne({
1783
- model: 'consentPurpose',
1784
- where: [
1785
- {
1786
- field: 'code',
1787
- value: code
1235
+ ]
1236
+ });
1237
+ return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
1238
+ },
1239
+ findSubjectByExternalId: async (externalId)=>{
1240
+ const subject = await adapter.findOne({
1241
+ model: 'subject',
1242
+ where: [
1243
+ {
1244
+ field: 'externalId',
1245
+ value: externalId
1246
+ }
1247
+ ]
1248
+ });
1249
+ return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
1250
+ }
1251
+ };
1252
+ }
1253
+ function consentRegistry({ adapter, ...ctx }) {
1254
+ const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
1255
+ const registry = {
1256
+ createConsent: async (consent, context)=>{
1257
+ const createdConsent = await createWithHooks({
1258
+ data: {
1259
+ createdAt: new Date(),
1260
+ ...consent
1261
+ },
1262
+ model: 'consent',
1263
+ context
1264
+ });
1265
+ if (!createdConsent) throw new error_class_DoubleTieError('Failed to create consent - operation returned null', {
1266
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1267
+ status: 500
1268
+ });
1269
+ return createdConsent;
1270
+ },
1271
+ updateConsent: async (consentId, data, context)=>{
1272
+ const consent = await updateWithHooks({
1273
+ data: {
1274
+ ...data
1275
+ },
1276
+ where: [
1277
+ {
1278
+ field: 'id',
1279
+ value: consentId
1280
+ }
1281
+ ],
1282
+ model: 'consent',
1283
+ context
1284
+ });
1285
+ return consent ? validateEntityOutput('consent', consent, ctx.options) : null;
1286
+ }
1287
+ };
1288
+ return registry;
1289
+ }
1290
+ const external_node_crypto_namespaceObject = require("node:crypto");
1291
+ function generatePolicyPlaceholder(name, date) {
1292
+ const content = `[PLACEHOLDER] This is an automatically generated version of the ${name} policy.\n\nThis placeholder content should be replaced with actual policy terms before being presented to users.\n\nGenerated on: ${date.toISOString()}`;
1293
+ const contentHash = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(content).digest('hex');
1294
+ return {
1295
+ content,
1296
+ contentHash
1297
+ };
1298
+ }
1299
+ function policyRegistry({ adapter, ...ctx }) {
1300
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1301
+ const registry = {
1302
+ createConsentPolicy: async (policy, context)=>{
1303
+ const createdPolicy = await createWithHooks({
1304
+ data: {
1305
+ createdAt: new Date(),
1306
+ ...policy
1307
+ },
1308
+ model: 'consentPolicy',
1309
+ context
1310
+ });
1311
+ if (!createdPolicy) throw new error_class_DoubleTieError('Failed to create consent policy - operation returned null', {
1312
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1313
+ status: 500
1314
+ });
1315
+ return createdPolicy;
1316
+ },
1317
+ findPolicies: async (params = {})=>{
1318
+ const whereConditions = [];
1319
+ if (!params.includeInactive) whereConditions.push({
1320
+ field: 'isActive',
1321
+ value: true
1322
+ });
1323
+ if (params.domainId) whereConditions.push({
1324
+ field: 'id',
1325
+ value: params.domainId
1326
+ });
1327
+ if (params.version) whereConditions.push({
1328
+ field: 'version',
1329
+ value: params.version
1330
+ });
1331
+ const policies = await adapter.findMany({
1332
+ model: 'consentPolicy',
1333
+ where: whereConditions,
1334
+ sortBy: {
1335
+ field: 'effectiveDate',
1336
+ direction: 'desc'
1337
+ }
1338
+ });
1339
+ return policies.map((policy)=>validateEntityOutput('consentPolicy', policy, ctx.options));
1340
+ },
1341
+ findConsentPolicyById: async (policyId)=>{
1342
+ const policy = await adapter.findOne({
1343
+ model: 'consentPolicy',
1344
+ where: [
1345
+ {
1346
+ field: 'id',
1347
+ value: policyId
1348
+ }
1349
+ ]
1350
+ });
1351
+ return policy ? validateEntityOutput('consentPolicy', policy, ctx.options) : null;
1352
+ },
1353
+ findOrCreatePolicy: async (type)=>adapter.transaction({
1354
+ callback: async (txAdapter)=>{
1355
+ const now = new Date();
1356
+ const txRegistry = policyRegistry({
1357
+ adapter: txAdapter,
1358
+ ...ctx
1359
+ });
1360
+ const rawLatestPolicy = await txAdapter.findOne({
1361
+ model: 'consentPolicy',
1362
+ where: [
1363
+ {
1364
+ field: 'isActive',
1365
+ value: true
1366
+ },
1367
+ {
1368
+ field: 'type',
1369
+ value: type
1370
+ }
1371
+ ],
1372
+ sortBy: {
1373
+ field: 'effectiveDate',
1374
+ direction: 'desc'
1788
1375
  }
1789
- ]
1790
- });
1791
- return consentPurpose ? validateEntityOutput('consentPurpose', consentPurpose, ctx.options) : null;
1792
- }
1793
- };
1794
- }
1795
- function domainRegistry({ adapter, ...ctx }) {
1796
- const { createWithHooks } = getWithHooks(adapter, ctx);
1797
- const registry = {
1798
- createDomain: async (domain, context)=>{
1799
- const createdDomain = await createWithHooks({
1800
- data: {
1801
- ...domain,
1802
- createdAt: new Date(),
1803
- updatedAt: new Date()
1804
- },
1805
- model: 'domain',
1806
- customFn: void 0,
1807
- context
1808
- });
1809
- if (!createdDomain) throw new error_class_DoubleTieError('Failed to create domain - operation returned null', {
1810
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1811
- status: 500
1812
- });
1813
- return createdDomain;
1814
- },
1815
- findOrCreateDomain: async function(name, context) {
1816
- const existingDomain = await this.findDomainByName(name);
1817
- if (existingDomain) return existingDomain;
1818
- const domain = await this.createDomain({
1819
- name,
1820
- description: `Auto-created domain for ${name}`,
1821
- isActive: true,
1822
- isVerified: true,
1823
- allowedOrigins: []
1824
- }, context);
1825
- if (!domain) throw new error_class_DoubleTieError('Failed to create domain', {
1826
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1827
- status: 503
1828
- });
1829
- return domain;
1830
- },
1831
- findDomains: async (params = {})=>{
1832
- const whereConditions = [];
1833
- if (!params.includeInactive) whereConditions.push({
1834
- field: 'isActive',
1835
- value: true
1836
- });
1837
- if (params.name) whereConditions.push({
1376
+ });
1377
+ const latestPolicy = rawLatestPolicy ? validateEntityOutput('consentPolicy', rawLatestPolicy, ctx.options) : null;
1378
+ if (latestPolicy) return latestPolicy;
1379
+ const { content: defaultContent, contentHash } = generatePolicyPlaceholder(type, now);
1380
+ return txRegistry.createConsentPolicy({
1381
+ version: '1.0.0',
1382
+ type,
1383
+ name: type,
1384
+ effectiveDate: now,
1385
+ content: defaultContent,
1386
+ contentHash,
1387
+ isActive: true,
1388
+ updatedAt: now,
1389
+ expirationDate: null
1390
+ });
1391
+ }
1392
+ })
1393
+ };
1394
+ return registry;
1395
+ }
1396
+ function consentPurposeRegistry({ adapter, ...ctx }) {
1397
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1398
+ return {
1399
+ createConsentPurpose: async (consentPurpose, context)=>{
1400
+ const createdPurpose = await createWithHooks({
1401
+ data: {
1402
+ id: consentPurpose.id || '',
1403
+ createdAt: new Date(),
1404
+ updatedAt: new Date(),
1405
+ ...consentPurpose
1406
+ },
1407
+ model: 'consentPurpose',
1408
+ context
1409
+ });
1410
+ if (!createdPurpose) throw new error_class_DoubleTieError('Failed to create consent purpose - operation returned null', {
1411
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1412
+ status: 500
1413
+ });
1414
+ return validateEntityOutput('consentPurpose', createdPurpose, ctx.options);
1415
+ },
1416
+ findConsentPurposeByCode: async (code)=>{
1417
+ const consentPurpose = await adapter.findOne({
1418
+ model: 'consentPurpose',
1419
+ where: [
1420
+ {
1421
+ field: 'code',
1422
+ value: code
1423
+ }
1424
+ ]
1425
+ });
1426
+ return consentPurpose ? validateEntityOutput('consentPurpose', consentPurpose, ctx.options) : null;
1427
+ }
1428
+ };
1429
+ }
1430
+ function domainRegistry({ adapter, ...ctx }) {
1431
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1432
+ const registry = {
1433
+ createDomain: async (domain, context)=>{
1434
+ const createdDomain = await createWithHooks({
1435
+ data: {
1436
+ ...domain,
1437
+ createdAt: new Date(),
1438
+ updatedAt: new Date()
1439
+ },
1440
+ model: 'domain',
1441
+ customFn: void 0,
1442
+ context
1443
+ });
1444
+ if (!createdDomain) throw new error_class_DoubleTieError('Failed to create domain - operation returned null', {
1445
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1446
+ status: 500
1447
+ });
1448
+ return createdDomain;
1449
+ },
1450
+ findOrCreateDomain: async function(name, context) {
1451
+ const existingDomain = await this.findDomainByName(name);
1452
+ if (existingDomain) return existingDomain;
1453
+ const domain = await this.createDomain({
1454
+ name,
1455
+ description: `Auto-created domain for ${name}`,
1456
+ isActive: true,
1457
+ isVerified: true,
1458
+ allowedOrigins: []
1459
+ }, context);
1460
+ if (!domain) throw new error_class_DoubleTieError('Failed to create domain', {
1461
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1462
+ status: 503
1463
+ });
1464
+ return domain;
1465
+ },
1466
+ findDomains: async (params = {})=>{
1467
+ const whereConditions = [];
1468
+ if (!params.includeInactive) whereConditions.push({
1469
+ field: 'isActive',
1470
+ value: true
1471
+ });
1472
+ if (params.name) whereConditions.push({
1473
+ field: 'name',
1474
+ value: params.name
1475
+ });
1476
+ const domains = await adapter.findMany({
1477
+ model: 'domain',
1478
+ where: whereConditions,
1479
+ sortBy: {
1838
1480
  field: 'name',
1839
- value: params.name
1840
- });
1841
- const domains = await adapter.findMany({
1842
- model: 'domain',
1843
- where: whereConditions,
1844
- sortBy: {
1481
+ direction: 'asc'
1482
+ }
1483
+ });
1484
+ return domains.map((domain)=>validateEntityOutput('domain', domain, ctx.options));
1485
+ },
1486
+ findDomain: async (name)=>{
1487
+ const domains = await registry.findDomains({
1488
+ name,
1489
+ includeInactive: false
1490
+ });
1491
+ return domains[0] || null;
1492
+ },
1493
+ findDomainByName: async (name)=>{
1494
+ const domain = await adapter.findOne({
1495
+ model: 'domain',
1496
+ where: [
1497
+ {
1845
1498
  field: 'name',
1846
- direction: 'asc'
1499
+ value: name
1847
1500
  }
1848
- });
1849
- return domains.map((domain)=>validateEntityOutput('domain', domain, ctx.options));
1850
- },
1851
- findDomain: async (name)=>{
1852
- const domains = await registry.findDomains({
1853
- name,
1854
- includeInactive: false
1855
- });
1856
- return domains[0] || null;
1857
- },
1858
- findDomainByName: async (name)=>{
1859
- const domain = await adapter.findOne({
1860
- model: 'domain',
1861
- where: [
1862
- {
1863
- field: 'name',
1864
- value: name
1865
- }
1866
- ]
1867
- });
1868
- return domain ? validateEntityOutput('domain', domain, ctx.options) : null;
1869
- }
1870
- };
1871
- return registry;
1872
- }
1873
- function auditLogRegistry({ adapter, ...ctx }) {
1874
- const { createWithHooks } = getWithHooks(adapter, ctx);
1875
- return {
1876
- createAuditLog: async (auditLog, context)=>{
1877
- const createdLog = await createWithHooks({
1878
- data: {
1879
- createdAt: new Date(),
1880
- ...auditLog
1881
- },
1882
- model: 'auditLog',
1883
- customFn: void 0,
1884
- context
1885
- });
1886
- if (!createdLog) throw new error_class_DoubleTieError('Failed to create audit log - operation returned null', {
1887
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1888
- status: 500
1889
- });
1890
- return createdLog;
1891
- }
1892
- };
1893
- }
1894
- })();
1501
+ ]
1502
+ });
1503
+ return domain ? validateEntityOutput('domain', domain, ctx.options) : null;
1504
+ }
1505
+ };
1506
+ return registry;
1507
+ }
1508
+ function auditLogRegistry({ adapter, ...ctx }) {
1509
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1510
+ return {
1511
+ createAuditLog: async (auditLog, context)=>{
1512
+ const createdLog = await createWithHooks({
1513
+ data: {
1514
+ createdAt: new Date(),
1515
+ ...auditLog
1516
+ },
1517
+ model: 'auditLog',
1518
+ customFn: void 0,
1519
+ context
1520
+ });
1521
+ if (!createdLog) throw new error_class_DoubleTieError('Failed to create audit log - operation returned null', {
1522
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1523
+ status: 500
1524
+ });
1525
+ return createdLog;
1526
+ }
1527
+ };
1528
+ }
1895
1529
  exports.COMMON_TIMEZONES = __webpack_exports__.COMMON_TIMEZONES;
1896
1530
  exports.PolicyTypeSchema = __webpack_exports__.PolicyTypeSchema;
1897
1531
  exports.auditLogRegistry = __webpack_exports__.auditLogRegistry;