@c15t/backend 1.0.0 → 1.1.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 (478) hide show
  1. package/.turbo/turbo-build.log +33 -39
  2. package/.turbo/turbo-fmt.log +7 -0
  3. package/.turbo/turbo-test.log +531 -0
  4. package/README.md +19 -7
  5. package/coverage/coverage-final.json +84 -0
  6. package/coverage/coverage-summary.json +85 -0
  7. package/coverage/html/backend/index.html +116 -0
  8. package/coverage/html/backend/rslib.config.ts.html +415 -0
  9. package/coverage/html/backend/src/contracts/consent/index.html +161 -0
  10. package/coverage/html/backend/src/contracts/consent/index.ts.html +112 -0
  11. package/coverage/html/backend/src/contracts/consent/post.contract.ts.html +559 -0
  12. package/coverage/html/backend/src/contracts/consent/show-banner.contract.ts.html +220 -0
  13. package/coverage/html/backend/src/contracts/consent/verify.contract.ts.html +463 -0
  14. package/coverage/html/backend/src/contracts/index.html +116 -0
  15. package/coverage/html/backend/src/contracts/index.ts.html +139 -0
  16. package/coverage/html/backend/src/contracts/meta/index.html +131 -0
  17. package/coverage/html/backend/src/contracts/meta/index.ts.html +100 -0
  18. package/coverage/html/backend/src/contracts/meta/status.contract.ts.html +196 -0
  19. package/coverage/html/backend/src/contracts/shared/index.html +116 -0
  20. package/coverage/html/backend/src/contracts/shared/jurisdiction.schema.ts.html +175 -0
  21. package/coverage/html/backend/src/core.ts.html +1624 -0
  22. package/coverage/html/backend/src/handlers/consent/index.html +161 -0
  23. package/coverage/html/backend/src/handlers/consent/index.ts.html +112 -0
  24. package/coverage/html/backend/src/handlers/consent/post.handler.ts.html +889 -0
  25. package/coverage/html/backend/src/handlers/consent/show-banner.handler.ts.html +535 -0
  26. package/coverage/html/backend/src/handlers/consent/verify.handler.ts.html +1000 -0
  27. package/coverage/html/backend/src/handlers/meta/index.html +131 -0
  28. package/coverage/html/backend/src/handlers/meta/index.ts.html +100 -0
  29. package/coverage/html/backend/src/handlers/meta/status.handler.ts.html +226 -0
  30. package/coverage/html/backend/src/index.html +161 -0
  31. package/coverage/html/backend/src/init.ts.html +1018 -0
  32. package/coverage/html/backend/src/pkgs/api-router/hooks/index.html +116 -0
  33. package/coverage/html/backend/src/pkgs/api-router/hooks/processor.ts.html +544 -0
  34. package/coverage/html/backend/src/pkgs/api-router/index.html +116 -0
  35. package/coverage/html/backend/src/pkgs/api-router/telemetry.ts.html +334 -0
  36. package/coverage/html/backend/src/pkgs/api-router/utils/cors.ts.html +304 -0
  37. package/coverage/html/backend/src/pkgs/api-router/utils/index.html +131 -0
  38. package/coverage/html/backend/src/pkgs/api-router/utils/ip.ts.html +361 -0
  39. package/coverage/html/backend/src/pkgs/data-model/fields/field-factory.ts.html +709 -0
  40. package/coverage/html/backend/src/pkgs/data-model/fields/id-generator.ts.html +256 -0
  41. package/coverage/html/backend/src/pkgs/data-model/fields/index.html +161 -0
  42. package/coverage/html/backend/src/pkgs/data-model/fields/superjson-utils.ts.html +136 -0
  43. package/coverage/html/backend/src/pkgs/data-model/fields/zod-fields.ts.html +496 -0
  44. package/coverage/html/backend/src/pkgs/data-model/hooks/create-hooks.ts.html +349 -0
  45. package/coverage/html/backend/src/pkgs/data-model/hooks/index.html +176 -0
  46. package/coverage/html/backend/src/pkgs/data-model/hooks/update-hooks.ts.html +358 -0
  47. package/coverage/html/backend/src/pkgs/data-model/hooks/update-many-hooks.ts.html +613 -0
  48. package/coverage/html/backend/src/pkgs/data-model/hooks/utils.ts.html +538 -0
  49. package/coverage/html/backend/src/pkgs/data-model/hooks/with-hooks-factory.ts.html +289 -0
  50. package/coverage/html/backend/src/pkgs/db-adapters/adapter-factory.ts.html +289 -0
  51. package/coverage/html/backend/src/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.ts.html +2203 -0
  52. package/coverage/html/backend/src/pkgs/db-adapters/adapters/drizzle-adapter/index.html +116 -0
  53. package/coverage/html/backend/src/pkgs/db-adapters/adapters/index.html +116 -0
  54. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/dialect.ts.html +670 -0
  55. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/index.html +131 -0
  56. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/kysely-adapter.ts.html +3634 -0
  57. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/tests/index.html +116 -0
  58. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.ts.html +1417 -0
  59. package/coverage/html/backend/src/pkgs/db-adapters/adapters/memory-adapter/index.html +116 -0
  60. package/coverage/html/backend/src/pkgs/db-adapters/adapters/memory-adapter/memory-adapter.ts.html +2071 -0
  61. package/coverage/html/backend/src/pkgs/db-adapters/adapters/prisma-adapter/index.html +116 -0
  62. package/coverage/html/backend/src/pkgs/db-adapters/adapters/prisma-adapter/prisma-adapter.ts.html +1834 -0
  63. package/coverage/html/backend/src/pkgs/db-adapters/adapters/test.ts.html +316 -0
  64. package/coverage/html/backend/src/pkgs/db-adapters/index.html +131 -0
  65. package/coverage/html/backend/src/pkgs/db-adapters/utils.ts.html +238 -0
  66. package/coverage/html/backend/src/pkgs/migrations/get-migration.ts.html +343 -0
  67. package/coverage/html/backend/src/pkgs/migrations/get-schema/get-schema.ts.html +217 -0
  68. package/coverage/html/backend/src/pkgs/migrations/get-schema/index.html +146 -0
  69. package/coverage/html/backend/src/pkgs/migrations/get-schema/process-fields.ts.html +280 -0
  70. package/coverage/html/backend/src/pkgs/migrations/get-schema/process-tables.ts.html +289 -0
  71. package/coverage/html/backend/src/pkgs/migrations/index.html +176 -0
  72. package/coverage/html/backend/src/pkgs/migrations/migration-builders.ts.html +595 -0
  73. package/coverage/html/backend/src/pkgs/migrations/migration-execution.ts.html +301 -0
  74. package/coverage/html/backend/src/pkgs/migrations/schema-comparison.ts.html +694 -0
  75. package/coverage/html/backend/src/pkgs/migrations/type-mapping.ts.html +817 -0
  76. package/coverage/html/backend/src/pkgs/results/core/error-class.ts.html +976 -0
  77. package/coverage/html/backend/src/pkgs/results/core/error-codes.ts.html +703 -0
  78. package/coverage/html/backend/src/pkgs/results/core/index.html +146 -0
  79. package/coverage/html/backend/src/pkgs/results/core/tracing.ts.html +280 -0
  80. package/coverage/html/backend/src/pkgs/results/create-telemetry-options.ts.html +271 -0
  81. package/coverage/html/backend/src/pkgs/results/index.html +131 -0
  82. package/coverage/html/backend/src/pkgs/results/orpc-error-handler.ts.html +496 -0
  83. package/coverage/html/backend/src/pkgs/results/results/index.html +131 -0
  84. package/coverage/html/backend/src/pkgs/results/results/recovery-utils.ts.html +628 -0
  85. package/coverage/html/backend/src/pkgs/results/results/result-helpers.ts.html +1234 -0
  86. package/coverage/html/backend/src/pkgs/utils/env.ts.html +337 -0
  87. package/coverage/html/backend/src/pkgs/utils/index.html +146 -0
  88. package/coverage/html/backend/src/pkgs/utils/logger.ts.html +199 -0
  89. package/coverage/html/backend/src/pkgs/utils/url.ts.html +400 -0
  90. package/coverage/html/backend/src/router.ts.html +109 -0
  91. package/coverage/html/backend/src/schema/audit-log/index.html +146 -0
  92. package/coverage/html/backend/src/schema/audit-log/registry.ts.html +436 -0
  93. package/coverage/html/backend/src/schema/audit-log/schema.ts.html +223 -0
  94. package/coverage/html/backend/src/schema/audit-log/table.ts.html +640 -0
  95. package/coverage/html/backend/src/schema/consent/index.html +146 -0
  96. package/coverage/html/backend/src/schema/consent/registry.ts.html +616 -0
  97. package/coverage/html/backend/src/schema/consent/schema.ts.html +238 -0
  98. package/coverage/html/backend/src/schema/consent/table.ts.html +748 -0
  99. package/coverage/html/backend/src/schema/consent-policy/index.html +146 -0
  100. package/coverage/html/backend/src/schema/consent-policy/registry.ts.html +1063 -0
  101. package/coverage/html/backend/src/schema/consent-policy/schema.ts.html +265 -0
  102. package/coverage/html/backend/src/schema/consent-policy/table.ts.html +535 -0
  103. package/coverage/html/backend/src/schema/consent-purpose/index.html +146 -0
  104. package/coverage/html/backend/src/schema/consent-purpose/registry.ts.html +589 -0
  105. package/coverage/html/backend/src/schema/consent-purpose/schema.ts.html +259 -0
  106. package/coverage/html/backend/src/schema/consent-purpose/table.ts.html +547 -0
  107. package/coverage/html/backend/src/schema/consent-record/index.html +131 -0
  108. package/coverage/html/backend/src/schema/consent-record/schema.ts.html +211 -0
  109. package/coverage/html/backend/src/schema/consent-record/table.ts.html +457 -0
  110. package/coverage/html/backend/src/schema/create-registry.ts.html +148 -0
  111. package/coverage/html/backend/src/schema/definition.ts.html +685 -0
  112. package/coverage/html/backend/src/schema/domain/index.html +146 -0
  113. package/coverage/html/backend/src/schema/domain/registry.ts.html +973 -0
  114. package/coverage/html/backend/src/schema/domain/schema.ts.html +214 -0
  115. package/coverage/html/backend/src/schema/domain/table.ts.html +496 -0
  116. package/coverage/html/backend/src/schema/index.html +146 -0
  117. package/coverage/html/backend/src/schema/schemas.ts.html +166 -0
  118. package/coverage/html/backend/src/schema/subject/index.html +146 -0
  119. package/coverage/html/backend/src/schema/subject/registry.ts.html +973 -0
  120. package/coverage/html/backend/src/schema/subject/schema.ts.html +208 -0
  121. package/coverage/html/backend/src/schema/subject/table.ts.html +499 -0
  122. package/coverage/html/backend/src/server.ts.html +475 -0
  123. package/coverage/html/backend/src/testing/contract-testing.ts.html +1348 -0
  124. package/coverage/html/backend/src/testing/index.html +116 -0
  125. package/coverage/html/base.css +224 -0
  126. package/coverage/html/block-navigation.js +87 -0
  127. package/coverage/html/favicon.png +0 -0
  128. package/coverage/html/index.html +626 -0
  129. package/coverage/html/prettify.css +1 -0
  130. package/coverage/html/prettify.js +2 -0
  131. package/coverage/html/sort-arrow-sprite.png +0 -0
  132. package/coverage/html/sorter.js +196 -0
  133. package/dist/contracts/consent/index.d.ts +401 -0
  134. package/dist/contracts/consent/index.d.ts.map +1 -0
  135. package/dist/contracts/consent/index.test.d.ts +2 -0
  136. package/dist/contracts/consent/index.test.d.ts.map +1 -0
  137. package/dist/contracts/consent/post.contract.d.ts +212 -0
  138. package/dist/contracts/consent/post.contract.d.ts.map +1 -0
  139. package/dist/contracts/consent/post.contract.test.d.ts +2 -0
  140. package/dist/contracts/consent/post.contract.test.d.ts.map +1 -0
  141. package/dist/contracts/consent/show-banner.contract.d.ts +45 -0
  142. package/dist/contracts/consent/show-banner.contract.d.ts.map +1 -0
  143. package/dist/contracts/consent/show-banner.contract.test.d.ts +2 -0
  144. package/dist/contracts/consent/show-banner.contract.test.d.ts.map +1 -0
  145. package/dist/contracts/consent/verify.contract.d.ts +147 -0
  146. package/dist/contracts/consent/verify.contract.d.ts.map +1 -0
  147. package/dist/contracts/consent/verify.contract.test.d.ts +2 -0
  148. package/dist/contracts/consent/verify.contract.test.d.ts.map +1 -0
  149. package/dist/contracts/index.d.ts +963 -0
  150. package/dist/contracts/index.d.ts.map +1 -0
  151. package/dist/contracts/meta/index.d.ts +78 -0
  152. package/dist/contracts/meta/index.d.ts.map +1 -0
  153. package/dist/contracts/meta/index.test.d.ts +2 -0
  154. package/dist/contracts/meta/index.test.d.ts.map +1 -0
  155. package/dist/contracts/meta/status.contract.d.ts +77 -0
  156. package/dist/contracts/meta/status.contract.d.ts.map +1 -0
  157. package/dist/contracts/meta/status.contract.test.d.ts +2 -0
  158. package/dist/contracts/meta/status.contract.test.d.ts.map +1 -0
  159. package/dist/contracts/shared/jurisdiction.schema.d.ts +24 -0
  160. package/dist/contracts/shared/jurisdiction.schema.d.ts.map +1 -0
  161. package/dist/core.cjs +3584 -0
  162. package/dist/core.d.ts +533 -78
  163. package/dist/core.d.ts.map +1 -1
  164. package/dist/{index.js → core.js} +1164 -1292
  165. package/dist/handlers/consent/index.d.ts +401 -0
  166. package/dist/handlers/consent/index.d.ts.map +1 -0
  167. package/dist/handlers/consent/post.handler.d.ts +234 -0
  168. package/dist/handlers/consent/post.handler.d.ts.map +1 -0
  169. package/dist/handlers/consent/show-banner.handler.d.ts +57 -0
  170. package/dist/handlers/consent/show-banner.handler.d.ts.map +1 -0
  171. package/dist/handlers/consent/show-banner.handler.test.d.ts +2 -0
  172. package/dist/handlers/consent/show-banner.handler.test.d.ts.map +1 -0
  173. package/dist/handlers/consent/verify.handler.d.ts +169 -0
  174. package/dist/handlers/consent/verify.handler.d.ts.map +1 -0
  175. package/dist/handlers/meta/index.d.ts +78 -0
  176. package/dist/handlers/meta/index.d.ts.map +1 -0
  177. package/dist/handlers/meta/status.handler.d.ts +76 -0
  178. package/dist/handlers/meta/status.handler.d.ts.map +1 -0
  179. package/dist/init.d.ts +0 -1
  180. package/dist/init.d.ts.map +1 -1
  181. package/dist/pkgs/api-router/hooks/processor.d.ts.map +1 -1
  182. package/dist/pkgs/api-router/types/router-props.d.ts +1 -1
  183. package/dist/pkgs/api-router/types/router-props.d.ts.map +1 -1
  184. package/dist/pkgs/api-router/utils/cors.d.ts +1 -1
  185. package/dist/pkgs/api-router/utils/cors.d.ts.map +1 -1
  186. package/dist/pkgs/data-model/fields/field-types.d.ts +1 -1
  187. package/dist/pkgs/data-model/fields/zod-fields.d.ts +32 -32
  188. package/dist/pkgs/data-model/index.cjs +1433 -1799
  189. package/dist/pkgs/data-model/index.js +20 -385
  190. package/dist/pkgs/data-model/schema/index.cjs +1402 -1768
  191. package/dist/pkgs/data-model/schema/index.js +20 -385
  192. package/dist/pkgs/db-adapters/adapter-factory.d.ts +2 -2
  193. package/dist/pkgs/db-adapters/adapter-factory.d.ts.map +1 -1
  194. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.d.ts +4 -7
  195. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.d.ts.map +1 -1
  196. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/index.cjs +19 -151
  197. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/index.js +19 -151
  198. package/dist/pkgs/db-adapters/adapters/kysely-adapter/dialect.d.ts +1 -3
  199. package/dist/pkgs/db-adapters/adapters/kysely-adapter/dialect.d.ts.map +1 -1
  200. package/dist/pkgs/db-adapters/adapters/kysely-adapter/index.cjs +17 -149
  201. package/dist/pkgs/db-adapters/adapters/kysely-adapter/index.js +17 -149
  202. package/dist/pkgs/db-adapters/adapters/kysely-adapter/kysely-adapter.d.ts +0 -1
  203. package/dist/pkgs/db-adapters/adapters/kysely-adapter/kysely-adapter.d.ts.map +1 -1
  204. package/dist/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.d.ts +2 -2
  205. package/dist/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.d.ts.map +1 -1
  206. package/dist/pkgs/db-adapters/adapters/kysely-adapter/types.d.ts +0 -2
  207. package/dist/pkgs/db-adapters/adapters/kysely-adapter/types.d.ts.map +1 -1
  208. package/dist/pkgs/db-adapters/adapters/memory-adapter/index.cjs +17 -149
  209. package/dist/pkgs/db-adapters/adapters/memory-adapter/index.js +17 -149
  210. package/dist/pkgs/db-adapters/adapters/memory-adapter/memory-adapter.d.ts +0 -1
  211. package/dist/pkgs/db-adapters/adapters/memory-adapter/memory-adapter.d.ts.map +1 -1
  212. package/dist/pkgs/db-adapters/adapters/prisma-adapter/index.cjs +19 -151
  213. package/dist/pkgs/db-adapters/adapters/prisma-adapter/index.js +19 -151
  214. package/dist/pkgs/db-adapters/adapters/prisma-adapter/prisma-adapter.d.ts +0 -1
  215. package/dist/pkgs/db-adapters/adapters/prisma-adapter/prisma-adapter.d.ts.map +1 -1
  216. package/dist/pkgs/db-adapters/index.cjs +31 -153
  217. package/dist/pkgs/db-adapters/index.js +31 -153
  218. package/dist/pkgs/migrations/get-schema/get-schema.d.ts +2 -2
  219. package/dist/pkgs/migrations/get-schema/index.d.ts +1 -1
  220. package/dist/pkgs/migrations/index.cjs +30 -153
  221. package/dist/pkgs/migrations/index.js +30 -153
  222. package/dist/pkgs/migrations/schema-comparison.d.ts.map +1 -1
  223. package/dist/pkgs/results/core/error-class.d.ts +23 -21
  224. package/dist/pkgs/results/core/error-class.d.ts.map +1 -1
  225. package/dist/pkgs/results/index.cjs +17 -150
  226. package/dist/pkgs/results/index.d.ts +0 -3
  227. package/dist/pkgs/results/index.d.ts.map +1 -1
  228. package/dist/pkgs/results/index.js +17 -138
  229. package/dist/pkgs/results/orpc-error-handler.d.ts +65 -0
  230. package/dist/pkgs/results/orpc-error-handler.d.ts.map +1 -0
  231. package/dist/pkgs/results/types.d.ts +7 -7
  232. package/dist/pkgs/results/types.d.ts.map +1 -1
  233. package/dist/pkgs/types/context.d.ts +15 -8
  234. package/dist/pkgs/types/context.d.ts.map +1 -1
  235. package/dist/pkgs/types/endpoints.d.ts +3 -4
  236. package/dist/pkgs/types/endpoints.d.ts.map +1 -1
  237. package/dist/pkgs/types/options.d.ts +2 -4
  238. package/dist/pkgs/types/options.d.ts.map +1 -1
  239. package/dist/pkgs/types/plugins.d.ts +2 -3
  240. package/dist/pkgs/types/plugins.d.ts.map +1 -1
  241. package/dist/pkgs/utils/index.d.ts +1 -0
  242. package/dist/pkgs/utils/index.d.ts.map +1 -1
  243. package/dist/pkgs/utils/logger.d.ts +16 -0
  244. package/dist/pkgs/utils/logger.d.ts.map +1 -0
  245. package/dist/router.cjs +1213 -0
  246. package/dist/router.d.ts +480 -0
  247. package/dist/router.d.ts.map +1 -0
  248. package/dist/router.js +1169 -0
  249. package/dist/schema/audit-log/table.d.ts +1 -1
  250. package/dist/schema/consent/table.d.ts +1 -1
  251. package/dist/schema/consent-policy/registry.d.ts +12 -12
  252. package/dist/schema/consent-policy/schema.d.ts +6 -6
  253. package/dist/schema/consent-policy/table.d.ts +7 -7
  254. package/dist/schema/consent-purpose/registry.d.ts +6 -6
  255. package/dist/schema/consent-purpose/schema.d.ts +6 -6
  256. package/dist/schema/consent-purpose/table.d.ts +7 -7
  257. package/dist/schema/consent-record/table.d.ts +1 -1
  258. package/dist/schema/create-registry.d.ts +32 -32
  259. package/dist/schema/definition.d.ts +19 -19
  260. package/dist/schema/domain/registry.d.ts +10 -10
  261. package/dist/schema/domain/schema.d.ts +5 -5
  262. package/dist/schema/domain/table.d.ts +6 -6
  263. package/dist/schema/index.cjs +1409 -1775
  264. package/dist/schema/index.js +20 -385
  265. package/dist/schema/schemas.d.ts +19 -19
  266. package/dist/schema/subject/registry.d.ts +4 -4
  267. package/dist/schema/subject/schema.d.ts +2 -2
  268. package/dist/schema/subject/table.d.ts +3 -3
  269. package/dist/server.d.ts +2 -0
  270. package/dist/server.d.ts.map +1 -0
  271. package/dist/testing/contract-testing.d.ts +37 -0
  272. package/dist/testing/contract-testing.d.ts.map +1 -0
  273. package/dist/types/context.d.ts +1 -1
  274. package/dist/types/index.d.ts +2 -2
  275. package/dist/types/options.d.ts +33 -3
  276. package/dist/types/options.d.ts.map +1 -1
  277. package/dist/types/plugins.d.ts +3 -4
  278. package/dist/types/plugins.d.ts.map +1 -1
  279. package/package.json +20 -28
  280. package/rslib.config.ts +2 -5
  281. package/src/contracts/consent/index.test.ts +5 -0
  282. package/src/contracts/consent/index.ts +9 -0
  283. package/src/contracts/consent/post.contract.test.ts +526 -0
  284. package/src/contracts/consent/post.contract.ts +160 -0
  285. package/src/contracts/consent/show-banner.contract.test.ts +214 -0
  286. package/src/contracts/consent/show-banner.contract.ts +45 -0
  287. package/src/contracts/consent/verify.contract.test.ts +185 -0
  288. package/src/contracts/consent/verify.contract.ts +126 -0
  289. package/src/contracts/index.ts +18 -0
  290. package/src/contracts/meta/index.test.ts +5 -0
  291. package/src/contracts/meta/index.ts +5 -0
  292. package/src/contracts/meta/status.contract.test.ts +338 -0
  293. package/src/contracts/meta/status.contract.ts +37 -0
  294. package/src/contracts/shared/jurisdiction.schema.ts +30 -0
  295. package/src/core.ts +451 -161
  296. package/src/handlers/consent/index.ts +9 -0
  297. package/src/handlers/consent/post.handler.ts +273 -0
  298. package/src/handlers/consent/show-banner.handler.test.ts +148 -0
  299. package/src/handlers/consent/show-banner.handler.ts +150 -0
  300. package/src/handlers/consent/verify.handler.ts +305 -0
  301. package/src/handlers/meta/index.ts +5 -0
  302. package/src/handlers/meta/status.handler.ts +47 -0
  303. package/src/init.ts +8 -26
  304. package/src/pkgs/api-router/hooks/__tests__/processor.test.ts +6 -0
  305. package/src/pkgs/api-router/hooks/processor.ts +2 -0
  306. package/src/pkgs/api-router/types/router-props.ts +1 -1
  307. package/src/pkgs/api-router/utils/cors.ts +1 -1
  308. package/src/pkgs/data-model/fields/field-types.ts +1 -1
  309. package/src/pkgs/data-model/fields/id-generator.ts +1 -1
  310. package/src/pkgs/db-adapters/README.md +3 -3
  311. package/src/pkgs/db-adapters/adapter-factory.ts +8 -4
  312. package/src/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.ts +13 -16
  313. package/src/pkgs/db-adapters/adapters/kysely-adapter/dialect.ts +1 -3
  314. package/src/pkgs/db-adapters/adapters/kysely-adapter/kysely-adapter.ts +0 -1
  315. package/src/pkgs/db-adapters/adapters/kysely-adapter/tests/postgres.test.ts +1 -1
  316. package/src/pkgs/db-adapters/adapters/kysely-adapter/tests/sqlite.test.ts +1 -1
  317. package/src/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.ts +2 -2
  318. package/src/pkgs/db-adapters/adapters/kysely-adapter/types.ts +0 -2
  319. package/src/pkgs/db-adapters/adapters/memory-adapter/memory-adapter.ts +0 -1
  320. package/src/pkgs/db-adapters/adapters/prisma-adapter/prisma-adapter.ts +0 -1
  321. package/src/pkgs/migrations/get-migration.ts +3 -3
  322. package/src/pkgs/migrations/get-schema/get-schema.ts +2 -2
  323. package/src/pkgs/migrations/get-schema/index.ts +1 -1
  324. package/src/pkgs/migrations/migration-builders.ts +2 -2
  325. package/src/pkgs/migrations/migration-execution.ts +2 -2
  326. package/src/pkgs/migrations/schema-comparison.ts +5 -4
  327. package/src/pkgs/results/__tests__/error-class.test.ts +8 -7
  328. package/src/pkgs/results/core/error-class.ts +31 -43
  329. package/src/pkgs/results/index.ts +0 -10
  330. package/src/pkgs/results/orpc-error-handler.ts +137 -0
  331. package/src/pkgs/results/types.ts +8 -7
  332. package/src/pkgs/types/context.ts +18 -9
  333. package/src/pkgs/types/endpoints.ts +3 -5
  334. package/src/pkgs/types/options.ts +2 -4
  335. package/src/pkgs/types/plugins.ts +2 -3
  336. package/src/pkgs/utils/index.ts +1 -0
  337. package/src/pkgs/utils/logger.ts +38 -0
  338. package/src/router.ts +8 -0
  339. package/src/schema/audit-log/table.ts +1 -1
  340. package/src/schema/consent/table.ts +1 -1
  341. package/src/schema/consent-policy/table.ts +1 -1
  342. package/src/schema/consent-purpose/table.ts +1 -1
  343. package/src/schema/consent-record/table.ts +1 -1
  344. package/src/schema/definition.ts +2 -2
  345. package/src/schema/domain/table.ts +1 -1
  346. package/src/schema/subject/table.ts +1 -1
  347. package/src/server.ts +130 -0
  348. package/src/testing/contract-testing.ts +437 -0
  349. package/src/types/context.ts +1 -1
  350. package/src/types/index.ts +2 -2
  351. package/src/types/options.ts +38 -3
  352. package/src/types/plugins.ts +3 -4
  353. package/dist/index.cjs +0 -3706
  354. package/dist/index.d.ts +0 -11
  355. package/dist/index.d.ts.map +0 -1
  356. package/dist/init.test.d.ts +0 -2
  357. package/dist/init.test.d.ts.map +0 -1
  358. package/dist/integrations/cloudflare.cjs +0 -312
  359. package/dist/integrations/cloudflare.d.ts +0 -32
  360. package/dist/integrations/cloudflare.d.ts.map +0 -1
  361. package/dist/integrations/cloudflare.js +0 -278
  362. package/dist/integrations/next.cjs +0 -276
  363. package/dist/integrations/next.d.ts +0 -68
  364. package/dist/integrations/next.d.ts.map +0 -1
  365. package/dist/integrations/next.js +0 -239
  366. package/dist/integrations/node.cjs +0 -257
  367. package/dist/integrations/node.d.ts +0 -29
  368. package/dist/integrations/node.d.ts.map +0 -1
  369. package/dist/integrations/node.js +0 -223
  370. package/dist/pkgs/api-router/index.d.ts +0 -9
  371. package/dist/pkgs/api-router/index.d.ts.map +0 -1
  372. package/dist/pkgs/api-router/utils/define-route.d.ts +0 -87
  373. package/dist/pkgs/api-router/utils/define-route.d.ts.map +0 -1
  374. package/dist/pkgs/logger/__tests__/console-formatter.test.d.ts +0 -2
  375. package/dist/pkgs/logger/__tests__/console-formatter.test.d.ts.map +0 -1
  376. package/dist/pkgs/logger/__tests__/integration.test.d.ts +0 -2
  377. package/dist/pkgs/logger/__tests__/integration.test.d.ts.map +0 -1
  378. package/dist/pkgs/logger/__tests__/log-levels.test.d.ts +0 -2
  379. package/dist/pkgs/logger/__tests__/log-levels.test.d.ts.map +0 -1
  380. package/dist/pkgs/logger/__tests__/logger-factory.test.d.ts +0 -2
  381. package/dist/pkgs/logger/__tests__/logger-factory.test.d.ts.map +0 -1
  382. package/dist/pkgs/logger/__tests__/result-logging.test.d.ts +0 -2
  383. package/dist/pkgs/logger/__tests__/result-logging.test.d.ts.map +0 -1
  384. package/dist/pkgs/logger/__tests__/types.test.d.ts +0 -2
  385. package/dist/pkgs/logger/__tests__/types.test.d.ts.map +0 -1
  386. package/dist/pkgs/logger/console-formatter.d.ts +0 -56
  387. package/dist/pkgs/logger/console-formatter.d.ts.map +0 -1
  388. package/dist/pkgs/logger/index.cjs +0 -240
  389. package/dist/pkgs/logger/index.d.ts +0 -35
  390. package/dist/pkgs/logger/index.d.ts.map +0 -1
  391. package/dist/pkgs/logger/index.js +0 -185
  392. package/dist/pkgs/logger/log-levels.d.ts +0 -29
  393. package/dist/pkgs/logger/log-levels.d.ts.map +0 -1
  394. package/dist/pkgs/logger/logger-factory.d.ts +0 -42
  395. package/dist/pkgs/logger/logger-factory.d.ts.map +0 -1
  396. package/dist/pkgs/logger/result-logging.d.ts +0 -71
  397. package/dist/pkgs/logger/result-logging.d.ts.map +0 -1
  398. package/dist/pkgs/logger/telemetry.d.ts +0 -14
  399. package/dist/pkgs/logger/telemetry.d.ts.map +0 -1
  400. package/dist/pkgs/logger/types.d.ts +0 -121
  401. package/dist/pkgs/logger/types.d.ts.map +0 -1
  402. package/dist/pkgs/results/__tests__/retrieval-pipeline.test.d.ts +0 -2
  403. package/dist/pkgs/results/__tests__/retrieval-pipeline.test.d.ts.map +0 -1
  404. package/dist/pkgs/results/__tests__/validation-pipeline.test.d.ts +0 -2
  405. package/dist/pkgs/results/__tests__/validation-pipeline.test.d.ts.map +0 -1
  406. package/dist/pkgs/results/h3-integration.d.ts +0 -52
  407. package/dist/pkgs/results/h3-integration.d.ts.map +0 -1
  408. package/dist/pkgs/results/pipeline/retrieval-pipeline.d.ts +0 -101
  409. package/dist/pkgs/results/pipeline/retrieval-pipeline.d.ts.map +0 -1
  410. package/dist/pkgs/results/pipeline/validation-pipeline.d.ts +0 -89
  411. package/dist/pkgs/results/pipeline/validation-pipeline.d.ts.map +0 -1
  412. package/dist/response-types.d.ts +0 -19
  413. package/dist/response-types.d.ts.map +0 -1
  414. package/dist/routes/__test__/index.test.d.ts +0 -17
  415. package/dist/routes/__test__/index.test.d.ts.map +0 -1
  416. package/dist/routes/__test__/set-consent.test.d.ts +0 -2
  417. package/dist/routes/__test__/set-consent.test.d.ts.map +0 -1
  418. package/dist/routes/__test__/show-consent-banner.test.d.ts +0 -2
  419. package/dist/routes/__test__/show-consent-banner.test.d.ts.map +0 -1
  420. package/dist/routes/__test__/status.test.d.ts +0 -2
  421. package/dist/routes/__test__/status.test.d.ts.map +0 -1
  422. package/dist/routes/__test__/verify-consent.test.d.ts +0 -2
  423. package/dist/routes/__test__/verify-consent.test.d.ts.map +0 -1
  424. package/dist/routes/index.d.ts +0 -3
  425. package/dist/routes/index.d.ts.map +0 -1
  426. package/dist/routes/set-consent.d.ts +0 -89
  427. package/dist/routes/set-consent.d.ts.map +0 -1
  428. package/dist/routes/show-consent-banner.d.ts +0 -15
  429. package/dist/routes/show-consent-banner.d.ts.map +0 -1
  430. package/dist/routes/status.d.ts +0 -44
  431. package/dist/routes/status.d.ts.map +0 -1
  432. package/dist/routes/types.d.ts +0 -7
  433. package/dist/routes/types.d.ts.map +0 -1
  434. package/dist/routes/verify-consent.d.ts +0 -38
  435. package/dist/routes/verify-consent.d.ts.map +0 -1
  436. package/src/docs/ADVANCED_JSON_HANDLING.md +0 -99
  437. package/src/docs/neverthrow.md +0 -171
  438. package/src/index.ts +0 -34
  439. package/src/init.test.ts +0 -236
  440. package/src/integrations/cloudflare.ts +0 -269
  441. package/src/integrations/next.ts +0 -204
  442. package/src/integrations/node.ts +0 -141
  443. package/src/pkgs/api-router/index.ts +0 -148
  444. package/src/pkgs/api-router/types/h3.d.ts +0 -42
  445. package/src/pkgs/api-router/utils/define-route.ts +0 -410
  446. package/src/pkgs/logger/README.md +0 -213
  447. package/src/pkgs/logger/__tests__/console-formatter.test.ts +0 -67
  448. package/src/pkgs/logger/__tests__/integration.test.ts +0 -184
  449. package/src/pkgs/logger/__tests__/log-levels.test.ts +0 -77
  450. package/src/pkgs/logger/__tests__/logger-factory.test.ts +0 -156
  451. package/src/pkgs/logger/__tests__/result-logging.test.ts +0 -209
  452. package/src/pkgs/logger/__tests__/types.test.ts +0 -94
  453. package/src/pkgs/logger/console-formatter.ts +0 -75
  454. package/src/pkgs/logger/doc.md +0 -569
  455. package/src/pkgs/logger/index.ts +0 -59
  456. package/src/pkgs/logger/log-levels.ts +0 -46
  457. package/src/pkgs/logger/logger-factory.ts +0 -121
  458. package/src/pkgs/logger/result-logging.ts +0 -134
  459. package/src/pkgs/logger/telemetry.ts +0 -96
  460. package/src/pkgs/logger/types.ts +0 -138
  461. package/src/pkgs/results/__tests__/retrieval-pipeline.test.ts +0 -157
  462. package/src/pkgs/results/__tests__/validation-pipeline.test.ts +0 -151
  463. package/src/pkgs/results/h3-integration.ts +0 -142
  464. package/src/pkgs/results/pipeline/retrieval-pipeline.ts +0 -188
  465. package/src/pkgs/results/pipeline/validation-pipeline.ts +0 -164
  466. package/src/plugins/.keep +0 -0
  467. package/src/response-types.ts +0 -29
  468. package/src/routes/__test__/index.test.ts +0 -112
  469. package/src/routes/__test__/set-consent.test.ts +0 -242
  470. package/src/routes/__test__/show-consent-banner.test.ts +0 -98
  471. package/src/routes/__test__/status.test.ts +0 -64
  472. package/src/routes/__test__/verify-consent.test.ts +0 -266
  473. package/src/routes/index.ts +0 -12
  474. package/src/routes/set-consent.ts +0 -249
  475. package/src/routes/show-consent-banner.ts +0 -131
  476. package/src/routes/status.ts +0 -61
  477. package/src/routes/types.ts +0 -7
  478. package/src/routes/verify-consent.ts +0 -206
@@ -1,3 +1,11 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__ from "@doubletie/logger";
2
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_openapi_a95cc8e7__ from "@orpc/openapi";
3
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_openapi_fetch_89b49e61__ from "@orpc/openapi/fetch";
4
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_server_plugins_e445fd4f__ from "@orpc/server/plugins";
5
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_zod_716a28d4__ from "@orpc/zod";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_neverthrow__ from "neverthrow";
7
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__ from "@orpc/server";
8
+ import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__ from "@opentelemetry/api";
1
9
  import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_resources_c7ac8648__ from "@opentelemetry/resources";
2
10
  import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_sdk_node_50b75088__ from "@opentelemetry/sdk-node";
3
11
  import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_sdk_trace_base_5031a705__ from "@opentelemetry/sdk-trace-base";
@@ -5,372 +13,10 @@ import * as __WEBPACK_EXTERNAL_MODULE_defu__ from "defu";
5
13
  import * as __WEBPACK_EXTERNAL_MODULE_superjson__ from "superjson";
6
14
  import * as __WEBPACK_EXTERNAL_MODULE_base_x_aeb88370__ from "base-x";
7
15
  import * as __WEBPACK_EXTERNAL_MODULE_zod__ from "zod";
8
- import * as __WEBPACK_EXTERNAL_MODULE_neverthrow__ from "neverthrow";
9
- import * as __WEBPACK_EXTERNAL_MODULE_h3__ from "h3";
10
- import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__ from "@opentelemetry/api";
11
16
  import * as __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__ from "node:crypto";
12
17
  import * as __WEBPACK_EXTERNAL_MODULE_kysely__ from "kysely";
13
18
  import "drizzle-orm";
14
- var __webpack_modules__ = {
15
- "../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/ZodError.js": function(__unused_webpack_module, exports, __webpack_require__) {
16
- exports.ZodError = void 0;
17
- const util_1 = __webpack_require__("../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/helpers/util.js");
18
- util_1.util.arrayToEnum([
19
- "invalid_type",
20
- "invalid_literal",
21
- "custom",
22
- "invalid_union",
23
- "invalid_union_discriminator",
24
- "invalid_enum_value",
25
- "unrecognized_keys",
26
- "invalid_arguments",
27
- "invalid_return_type",
28
- "invalid_date",
29
- "invalid_string",
30
- "too_small",
31
- "too_big",
32
- "invalid_intersection_types",
33
- "not_multiple_of",
34
- "not_finite"
35
- ]);
36
- class ZodError extends Error {
37
- get errors() {
38
- return this.issues;
39
- }
40
- constructor(issues){
41
- super();
42
- this.issues = [];
43
- this.addIssue = (sub)=>{
44
- this.issues = [
45
- ...this.issues,
46
- sub
47
- ];
48
- };
49
- this.addIssues = (subs = [])=>{
50
- this.issues = [
51
- ...this.issues,
52
- ...subs
53
- ];
54
- };
55
- const actualProto = new.target.prototype;
56
- if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
57
- else this.__proto__ = actualProto;
58
- this.name = "ZodError";
59
- this.issues = issues;
60
- }
61
- format(_mapper) {
62
- const mapper = _mapper || function(issue) {
63
- return issue.message;
64
- };
65
- const fieldErrors = {
66
- _errors: []
67
- };
68
- const processError = (error)=>{
69
- for (const issue of error.issues)if ("invalid_union" === issue.code) issue.unionErrors.map(processError);
70
- else if ("invalid_return_type" === issue.code) processError(issue.returnTypeError);
71
- else if ("invalid_arguments" === issue.code) processError(issue.argumentsError);
72
- else if (0 === issue.path.length) fieldErrors._errors.push(mapper(issue));
73
- else {
74
- let curr = fieldErrors;
75
- let i = 0;
76
- while(i < issue.path.length){
77
- const el = issue.path[i];
78
- const terminal = i === issue.path.length - 1;
79
- if (terminal) {
80
- curr[el] = curr[el] || {
81
- _errors: []
82
- };
83
- curr[el]._errors.push(mapper(issue));
84
- } else curr[el] = curr[el] || {
85
- _errors: []
86
- };
87
- curr = curr[el];
88
- i++;
89
- }
90
- }
91
- };
92
- processError(this);
93
- return fieldErrors;
94
- }
95
- static assert(value) {
96
- if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
97
- }
98
- toString() {
99
- return this.message;
100
- }
101
- get message() {
102
- return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2);
103
- }
104
- get isEmpty() {
105
- return 0 === this.issues.length;
106
- }
107
- flatten(mapper = (issue)=>issue.message) {
108
- const fieldErrors = {};
109
- const formErrors = [];
110
- for (const sub of this.issues)if (sub.path.length > 0) {
111
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
112
- fieldErrors[sub.path[0]].push(mapper(sub));
113
- } else formErrors.push(mapper(sub));
114
- return {
115
- formErrors,
116
- fieldErrors
117
- };
118
- }
119
- get formErrors() {
120
- return this.flatten();
121
- }
122
- }
123
- exports.ZodError = ZodError;
124
- ZodError.create = (issues)=>{
125
- const error = new ZodError(issues);
126
- return error;
127
- };
128
- },
129
- "../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/helpers/util.js": function(__unused_webpack_module, exports) {
130
- Object.defineProperty(exports, "__esModule", {
131
- value: true
132
- });
133
- exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0;
134
- var util;
135
- (function(util) {
136
- util.assertEqual = (val)=>val;
137
- function assertIs(_arg) {}
138
- util.assertIs = assertIs;
139
- function assertNever(_x) {
140
- throw new Error();
141
- }
142
- util.assertNever = assertNever;
143
- util.arrayToEnum = (items)=>{
144
- const obj = {};
145
- for (const item of items)obj[item] = item;
146
- return obj;
147
- };
148
- util.getValidEnumValues = (obj)=>{
149
- const validKeys = util.objectKeys(obj).filter((k)=>"number" != typeof obj[obj[k]]);
150
- const filtered = {};
151
- for (const k of validKeys)filtered[k] = obj[k];
152
- return util.objectValues(filtered);
153
- };
154
- util.objectValues = (obj)=>util.objectKeys(obj).map(function(e) {
155
- return obj[e];
156
- });
157
- util.objectKeys = "function" == typeof Object.keys ? (obj)=>Object.keys(obj) : (object)=>{
158
- const keys = [];
159
- for(const key in object)if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
160
- return keys;
161
- };
162
- util.find = (arr, checker)=>{
163
- for (const item of arr)if (checker(item)) return item;
164
- };
165
- util.isInteger = "function" == typeof Number.isInteger ? (val)=>Number.isInteger(val) : (val)=>"number" == typeof val && isFinite(val) && Math.floor(val) === val;
166
- function joinValues(array, separator = " | ") {
167
- return array.map((val)=>"string" == typeof val ? `'${val}'` : val).join(separator);
168
- }
169
- util.joinValues = joinValues;
170
- util.jsonStringifyReplacer = (_, value)=>{
171
- if ("bigint" == typeof value) return value.toString();
172
- return value;
173
- };
174
- })(util || (exports.util = util = {}));
175
- var objectUtil;
176
- (function(objectUtil) {
177
- objectUtil.mergeShapes = (first, second)=>({
178
- ...first,
179
- ...second
180
- });
181
- })(objectUtil || (exports.objectUtil = objectUtil = {}));
182
- exports.ZodParsedType = util.arrayToEnum([
183
- "string",
184
- "nan",
185
- "number",
186
- "integer",
187
- "float",
188
- "boolean",
189
- "date",
190
- "bigint",
191
- "symbol",
192
- "function",
193
- "undefined",
194
- "null",
195
- "array",
196
- "object",
197
- "unknown",
198
- "promise",
199
- "void",
200
- "never",
201
- "map",
202
- "set"
203
- ]);
204
- const getParsedType = (data)=>{
205
- const t = typeof data;
206
- switch(t){
207
- case "undefined":
208
- return exports.ZodParsedType.undefined;
209
- case "string":
210
- return exports.ZodParsedType.string;
211
- case "number":
212
- return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number;
213
- case "boolean":
214
- return exports.ZodParsedType.boolean;
215
- case "function":
216
- return exports.ZodParsedType.function;
217
- case "bigint":
218
- return exports.ZodParsedType.bigint;
219
- case "symbol":
220
- return exports.ZodParsedType.symbol;
221
- case "object":
222
- if (Array.isArray(data)) return exports.ZodParsedType.array;
223
- if (null === data) return exports.ZodParsedType.null;
224
- if (data.then && "function" == typeof data.then && data.catch && "function" == typeof data.catch) return exports.ZodParsedType.promise;
225
- if ("undefined" != typeof Map && data instanceof Map) return exports.ZodParsedType.map;
226
- if ("undefined" != typeof Set && data instanceof Set) return exports.ZodParsedType.set;
227
- if ("undefined" != typeof Date && data instanceof Date) return exports.ZodParsedType.date;
228
- return exports.ZodParsedType.object;
229
- default:
230
- return exports.ZodParsedType.unknown;
231
- }
232
- };
233
- exports.getParsedType = getParsedType;
234
- }
235
- };
236
- var __webpack_module_cache__ = {};
237
- function __webpack_require__(moduleId) {
238
- var cachedModule = __webpack_module_cache__[moduleId];
239
- if (void 0 !== cachedModule) return cachedModule.exports;
240
- var module = __webpack_module_cache__[moduleId] = {
241
- exports: {}
242
- };
243
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
244
- return module.exports;
245
- }
246
- (()=>{
247
- __webpack_require__.r = (exports)=>{
248
- if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports, Symbol.toStringTag, {
249
- value: 'Module'
250
- });
251
- Object.defineProperty(exports, '__esModule', {
252
- value: true
253
- });
254
- };
255
- })();
256
- var pkgs_types_namespaceObject = {};
257
- __webpack_require__.r(pkgs_types_namespaceObject);
258
- function utils_applyDefaultValue(inputValue, field, operation) {
259
- if ('update' === operation) return inputValue;
260
- if (null == inputValue && field.defaultValue) {
261
- if ('function' == typeof field.defaultValue) return field.defaultValue();
262
- return field.defaultValue;
263
- }
264
- return inputValue;
265
- }
266
- const COMMON_TIMEZONES = {
267
- UTC: 'UTC',
268
- GMT: 'GMT',
269
- EASTERN: 'America/New_York',
270
- CENTRAL: 'America/Chicago',
271
- MOUNTAIN: 'America/Denver',
272
- PACIFIC: 'America/Los_Angeles',
273
- LONDON: 'Europe/London',
274
- PARIS: 'Europe/Paris',
275
- BERLIN: 'Europe/Berlin',
276
- TOKYO: 'Asia/Tokyo',
277
- SHANGHAI: 'Asia/Shanghai',
278
- SINGAPORE: 'Asia/Singapore',
279
- SYDNEY: 'Australia/Sydney',
280
- SAO_PAULO: 'America/Sao_Paulo'
281
- };
282
- const b58 = (0, __WEBPACK_EXTERNAL_MODULE_base_x_aeb88370__["default"])('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
283
- function id_generator_generateId(prefix) {
284
- const buf = crypto.getRandomValues(new Uint8Array(20));
285
- const EPOCH_TIMESTAMP = 1700000000000;
286
- const t = Date.now() - EPOCH_TIMESTAMP;
287
- const high = Math.floor(t / 0x100000000);
288
- const low = t >>> 0;
289
- buf[0] = high >>> 24 & 255;
290
- buf[1] = high >>> 16 & 255;
291
- buf[2] = high >>> 8 & 255;
292
- buf[3] = 255 & high;
293
- buf[4] = low >>> 24 & 255;
294
- buf[5] = low >>> 16 & 255;
295
- buf[6] = low >>> 8 & 255;
296
- buf[7] = 255 & low;
297
- return `${prefix}_${b58.encode(buf)}`;
298
- }
299
- const fieldConfigSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
300
- required: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
301
- returned: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
302
- input: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
303
- defaultValue: __WEBPACK_EXTERNAL_MODULE_zod__.z.union([
304
- __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
305
- __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
306
- ]).optional(),
307
- transform: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
308
- input: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
309
- __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
310
- __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
311
- ])).optional(),
312
- output: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
313
- __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
314
- __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
315
- ])).optional()
316
- }).optional(),
317
- validator: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
318
- __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
319
- __WEBPACK_EXTERNAL_MODULE_zod__.z["null"]()
320
- ])).optional(),
321
- unique: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
322
- indexed: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
323
- sortable: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
324
- fieldName: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
325
- bigint: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
326
- });
327
- const stringFieldSchema = fieldConfigSchema.extend({
328
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string'),
329
- minLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
330
- maxLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
331
- pattern: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional()
332
- });
333
- const numberFieldSchema = fieldConfigSchema.extend({
334
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number'),
335
- min: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
336
- max: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional()
337
- });
338
- const booleanFieldSchema = fieldConfigSchema.extend({
339
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('boolean')
340
- });
341
- const dateFieldSchema = fieldConfigSchema.extend({
342
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('date'),
343
- minDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
344
- maxDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
345
- dateOnly: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false),
346
- format: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional()
347
- });
348
- const timezoneFieldSchema = fieldConfigSchema.extend({
349
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('timezone'),
350
- validateTimezone: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
351
- suggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional(),
352
- restrictToSuggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
353
- });
354
- const jsonFieldSchema = fieldConfigSchema.extend({
355
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('json'),
356
- validateJson: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true)
357
- });
358
- const stringArrayFieldSchema = fieldConfigSchema.extend({
359
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string[]')
360
- });
361
- const numberArrayFieldSchema = fieldConfigSchema.extend({
362
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number[]')
363
- });
364
- __WEBPACK_EXTERNAL_MODULE_zod__.z.discriminatedUnion('type', [
365
- stringFieldSchema,
366
- numberFieldSchema,
367
- booleanFieldSchema,
368
- dateFieldSchema,
369
- timezoneFieldSchema,
370
- jsonFieldSchema,
371
- stringArrayFieldSchema,
372
- numberArrayFieldSchema
373
- ]);
19
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__ from "@orpc/contract";
374
20
  const error_codes_ERROR_CODES = Object.freeze({
375
21
  NOT_FOUND: 'Resource not found',
376
22
  BAD_REQUEST: 'Bad request',
@@ -436,10 +82,10 @@ async function tracing_withSpan(name, fn, attributes = {}) {
436
82
  }
437
83
  });
438
84
  }
439
- class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE_h3__.H3Error {
440
- code;
85
+ class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError {
441
86
  category;
442
87
  meta;
88
+ statusCode;
443
89
  constructor(message, options = {
444
90
  code: error_codes_ERROR_CODES.UNKNOWN_ERROR,
445
91
  status: 500,
@@ -447,22 +93,18 @@ class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE_h3__.H3Error
447
93
  cause: void 0,
448
94
  meta: {}
449
95
  }){
450
- super(message, {
451
- cause: options.cause
96
+ super(options.code ?? error_codes_ERROR_CODES.UNKNOWN_ERROR, {
97
+ message,
98
+ cause: options.cause,
99
+ data: options.meta ?? {}
452
100
  });
453
- this.name = this.constructor.name;
454
- this.code = options.code ?? error_codes_ERROR_CODES.UNKNOWN_ERROR;
455
- this.statusCode = options.status ?? 500;
101
+ this.name = 'DoubleTieError';
456
102
  this.category = options.category ?? ERROR_CATEGORIES.UNEXPECTED;
457
103
  this.meta = options.meta ?? {};
458
- this.data = {
459
- code: this.code,
460
- category: this.category,
461
- meta: this.meta
462
- };
104
+ this.statusCode = options.status ?? 500;
463
105
  tracing_withSpan('create_doubletie_error', async (span)=>{
464
106
  span.setAttributes({
465
- 'error.name': this.name,
107
+ 'error.name': this.constructor.name,
466
108
  'error.message': message,
467
109
  'error.code': this.code,
468
110
  'error.status': this.statusCode,
@@ -482,11 +124,11 @@ class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE_h3__.H3Error
482
124
  const validationErrorMessage = this.meta?.validationErrors ? String(this.meta.validationErrors) : void 0;
483
125
  const stackTrace = this.stack ? this.stack.split('\n').map((line)=>line.trim()).filter((line)=>line && !line.includes('Error: ')) : [];
484
126
  return {
485
- statusCode: this.statusCode,
127
+ code: this.code,
486
128
  message: validationErrorMessage || this.message,
487
- statusMessage: this.statusMessage,
129
+ status: this.statusCode,
130
+ defined: true,
488
131
  data: {
489
- code: this.code,
490
132
  category: this.category,
491
133
  meta: this.meta,
492
134
  ...'production' === process.env.NODE_ENV ? {} : {
@@ -537,7 +179,9 @@ class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE_h3__.H3Error
537
179
  const ErrorSubclass = class extends error_class_DoubleTieError {
538
180
  constructor(message, options){
539
181
  super(message, options);
540
- this.name = name;
182
+ Object.defineProperty(this, 'name', {
183
+ value: name
184
+ });
541
185
  }
542
186
  };
543
187
  Object.defineProperty(ErrorSubclass, 'name', {
@@ -604,94 +248,6 @@ function promiseToResult(promise, errorCode = error_codes_ERROR_CODES.UNKNOWN_ER
604
248
  return result;
605
249
  });
606
250
  }
607
- const validationPipeline = (schema, transformer)=>(data)=>{
608
- const preprocessData = (value)=>{
609
- if ('object' != typeof value || null === value) {
610
- if ('string' == typeof value) try {
611
- if (value.startsWith('[') && value.endsWith(']')) return JSON.parse(value);
612
- if ('true' === value.toLowerCase()) return true;
613
- if ('false' === value.toLowerCase()) return false;
614
- if (value.startsWith('{') && value.endsWith('}')) return JSON.parse(value);
615
- } catch {}
616
- return value;
617
- }
618
- if (Array.isArray(value)) return value.map(preprocessData);
619
- const processed = {};
620
- for (const [key, val] of Object.entries(value))processed[key] = preprocessData(val);
621
- return processed;
622
- };
623
- const preprocessedData = preprocessData(data);
624
- const parseResult = schema.safeParse(preprocessedData);
625
- if (!parseResult.success) return fail('Validation failed', {
626
- code: error_codes_ERROR_CODES.INVALID_REQUEST,
627
- status: 400,
628
- meta: {
629
- validationErrors: parseResult.error.issues
630
- }
631
- });
632
- try {
633
- return (0, __WEBPACK_EXTERNAL_MODULE_neverthrow__.ok)(transformer(parseResult.data));
634
- } catch (error) {
635
- return fail('Error transforming data after validation', {
636
- code: error_codes_ERROR_CODES.BAD_REQUEST,
637
- status: 400,
638
- cause: error instanceof Error ? error : void 0,
639
- meta: {
640
- inputData: parseResult.data
641
- }
642
- });
643
- }
644
- };
645
- function createH3ErrorHandler() {
646
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.eventHandler)((event)=>{
647
- event.context._onError = (error)=>{
648
- event.context.logger.error('Error in H3 error handler', {
649
- error
650
- });
651
- if (error instanceof error_class_DoubleTieError) {
652
- event.context.logger.error('Handling DoubleTieError:', error.statusCode, error.message);
653
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendError)(event, error);
654
- }
655
- event.context.logger.error('Handling generic error', {
656
- error
657
- });
658
- const dtError = new error_class_DoubleTieError(error instanceof Error ? error.message : String(error), {
659
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
660
- status: 500,
661
- cause: error instanceof Error ? error : void 0
662
- });
663
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendError)(event, dtError);
664
- };
665
- event.node.req.on('error', (err)=>{
666
- event.context.logger.error('Request error event triggered:', {
667
- err
668
- });
669
- if (event.context._onError) event.context._onError(err);
670
- });
671
- });
672
- }
673
- function withH3ErrorHandling(handler) {
674
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.eventHandler)(async (event)=>{
675
- try {
676
- return await handler(event);
677
- } catch (error) {
678
- event.context.logger.error('Error caught in withH3ErrorHandling:', {
679
- error
680
- });
681
- if (error instanceof error_class_DoubleTieError) {
682
- event.context.logger.error('Handling DoubleTieError in wrapper:', error.statusCode, error.message);
683
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendError)(event, error);
684
- }
685
- if (event.context._onError && 'function' == typeof event.context._onError) return event.context._onError(error);
686
- const dtError = new error_class_DoubleTieError(error instanceof Error ? error.message : String(error), {
687
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
688
- status: 500,
689
- cause: error instanceof Error ? error : void 0
690
- });
691
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendError)(event, dtError);
692
- }
693
- });
694
- }
695
251
  function createTelemetryOptions(appName = 'c15t', telemetryConfig) {
696
252
  const serviceVersion = process.env.npm_package_version || '1.0.0';
697
253
  const config = {
@@ -705,138 +261,123 @@ function createTelemetryOptions(appName = 'c15t', telemetryConfig) {
705
261
  };
706
262
  return config;
707
263
  }
708
- var ZodError = __webpack_require__("../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/ZodError.js");
709
- const levels = [
710
- 'error',
711
- 'warn',
712
- 'info',
713
- 'success',
714
- 'debug'
715
- ];
716
- function shouldPublishLog(currentLogLevel, logLevel) {
717
- const currentLevelIndex = levels.indexOf(currentLogLevel);
718
- const messageLevelIndex = levels.indexOf(logLevel);
719
- if ('debug' === currentLogLevel) return 'debug' === logLevel;
720
- return messageLevelIndex <= currentLevelIndex;
721
- }
722
- const colors = {
723
- reset: '\x1b[0m',
724
- bright: '\x1b[1m',
725
- dim: '\x1b[2m',
726
- underscore: '\x1b[4m',
727
- blink: '\x1b[5m',
728
- reverse: '\x1b[7m',
729
- hidden: '\x1b[8m',
730
- fg: {
731
- black: '\x1b[30m',
732
- red: '\x1b[31m',
733
- green: '\x1b[32m',
734
- yellow: '\x1b[33m',
735
- blue: '\x1b[34m',
736
- magenta: '\x1b[35m',
737
- cyan: '\x1b[36m',
738
- white: '\x1b[37m'
739
- },
740
- bg: {
741
- black: '\x1b[40m',
742
- red: '\x1b[41m',
743
- green: '\x1b[42m',
744
- yellow: '\x1b[43m',
745
- blue: '\x1b[44m',
746
- magenta: '\x1b[45m',
747
- cyan: '\x1b[46m',
748
- white: '\x1b[47m'
749
- }
750
- };
751
- const levelColors = {
752
- info: colors.fg.blue,
753
- success: colors.fg.green,
754
- warn: colors.fg.yellow,
755
- error: colors.fg.red,
756
- debug: colors.fg.magenta
757
- };
758
- const formatMessage = (level, message, appName = 'c15t')=>{
759
- const timestamp = new Date().toISOString();
760
- return `${colors.dim}${timestamp}${colors.reset} ${levelColors[level]}${level.toUpperCase()}${colors.reset} ${colors.bright}[${appName}]:${colors.reset} ${message}`;
761
- };
762
- const LOGGER_TRACER_NAME = '@doubletie/logger';
763
- const LOG_LEVEL_TO_SPAN_STATUS = {
764
- error: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.ERROR,
765
- warn: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK,
766
- info: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK,
767
- success: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK,
768
- debug: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK
769
- };
770
- const telemetry_getTracer = (options)=>{
771
- if (options?.telemetry?.tracer) return options.telemetry.tracer;
772
- return __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.trace.getTracer(LOGGER_TRACER_NAME);
773
- };
774
- const createLogSpan = (level, message, args = [], options)=>{
775
- if (options?.telemetry?.disabled) return null;
776
- const tracer = telemetry_getTracer(options);
777
- const span = tracer.startSpan('log_entry', {
778
- attributes: {
779
- 'log.level': level,
780
- 'log.message': message,
781
- 'log.has_args': args.length > 0,
782
- ...options?.telemetry?.defaultAttributes || {}
783
- }
784
- });
785
- if (args.length > 0 && 'object' == typeof args[0] && null !== args[0]) {
786
- const data = args[0];
787
- for (const [key, value] of Object.entries(data))if (null != value) span.setAttribute(`log.data.${key}`, String(value));
264
+ var package_namespaceObject = JSON.parse('{"i8":"1.1.0-canary.0"}');
265
+ function utils_applyDefaultValue(inputValue, field, operation) {
266
+ if ('update' === operation) return inputValue;
267
+ if (null == inputValue && field.defaultValue) {
268
+ if ('function' == typeof field.defaultValue) return field.defaultValue();
269
+ return field.defaultValue;
788
270
  }
789
- span.setStatus({
790
- code: LOG_LEVEL_TO_SPAN_STATUS[level],
791
- message: 'error' === level || 'warn' === level ? message : void 0
792
- });
793
- return span;
271
+ return inputValue;
272
+ }
273
+ const COMMON_TIMEZONES = {
274
+ UTC: 'UTC',
275
+ GMT: 'GMT',
276
+ EASTERN: 'America/New_York',
277
+ CENTRAL: 'America/Chicago',
278
+ MOUNTAIN: 'America/Denver',
279
+ PACIFIC: 'America/Los_Angeles',
280
+ LONDON: 'Europe/London',
281
+ PARIS: 'Europe/Paris',
282
+ BERLIN: 'Europe/Berlin',
283
+ TOKYO: 'Asia/Tokyo',
284
+ SHANGHAI: 'Asia/Shanghai',
285
+ SINGAPORE: 'Asia/Singapore',
286
+ SYDNEY: 'Australia/Sydney',
287
+ SAO_PAULO: 'America/Sao_Paulo'
794
288
  };
795
- const withLogSpan = async (level, message, args, operation, options)=>{
796
- const span = createLogSpan(level, message, args, options);
797
- if (!span) return operation();
798
- try {
799
- const result = await operation();
800
- return result;
801
- } catch (error) {
802
- span.setStatus({
803
- code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.ERROR,
804
- message: error instanceof Error ? error.message : String(error)
805
- });
806
- throw error;
807
- } finally{
808
- span.end();
809
- }
810
- };
811
- const createLogger = (options)=>{
812
- if (options && 'object' == typeof options && levels.every((level)=>'function' == typeof options[level])) return options;
813
- const loggerOptions = options;
814
- const enabled = loggerOptions?.disabled !== true;
815
- const logLevel = loggerOptions?.level ?? 'error';
816
- const appName = loggerOptions?.appName ?? 'c15t';
817
- const logFunc = async (level, message, args = [])=>{
818
- if (!enabled || !shouldPublishLog(logLevel, level)) return;
819
- await withLogSpan(level, message, args, async ()=>{
820
- const formattedMessage = formatMessage(level, message, appName);
821
- if (!loggerOptions || 'function' != typeof loggerOptions.log) {
822
- if ('error' === level) console.error(formattedMessage, ...args);
823
- else if ('warn' === level) console.warn(formattedMessage, ...args);
824
- else if ('info' === level) console.log(formattedMessage, ...args);
825
- else if ('debug' === level) console.debug(formattedMessage, ...args);
826
- else if ('success' === level) console.log(formattedMessage, ...args);
827
- return;
828
- }
829
- loggerOptions.log('success' === level ? 'info' : level, message, ...args);
830
- });
831
- };
832
- return Object.fromEntries(levels.map((level)=>[
833
- level,
834
- (...[message, ...args])=>logFunc(level, message, args).catch((error)=>{
835
- console.error('Logger error:', error);
836
- })
837
- ]));
838
- };
839
- const logger_factory_logger = createLogger();
289
+ const b58 = (0, __WEBPACK_EXTERNAL_MODULE_base_x_aeb88370__["default"])('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
290
+ function id_generator_generateId(prefix) {
291
+ const buf = crypto.getRandomValues(new Uint8Array(20));
292
+ const EPOCH_TIMESTAMP = 1700000000000;
293
+ const t = Date.now() - EPOCH_TIMESTAMP;
294
+ const high = Math.floor(t / 0x100000000);
295
+ const low = t >>> 0;
296
+ buf[0] = high >>> 24 & 255;
297
+ buf[1] = high >>> 16 & 255;
298
+ buf[2] = high >>> 8 & 255;
299
+ buf[3] = 255 & high;
300
+ buf[4] = low >>> 24 & 255;
301
+ buf[5] = low >>> 16 & 255;
302
+ buf[6] = low >>> 8 & 255;
303
+ buf[7] = 255 & low;
304
+ return `${prefix}_${b58.encode(buf)}`;
305
+ }
306
+ const fieldConfigSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
307
+ required: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
308
+ returned: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
309
+ input: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
310
+ defaultValue: __WEBPACK_EXTERNAL_MODULE_zod__.z.union([
311
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
312
+ __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
313
+ ]).optional(),
314
+ transform: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
315
+ input: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
316
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
317
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
318
+ ])).optional(),
319
+ output: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
320
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
321
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
322
+ ])).optional()
323
+ }).optional(),
324
+ validator: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
325
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
326
+ __WEBPACK_EXTERNAL_MODULE_zod__.z["null"]()
327
+ ])).optional(),
328
+ unique: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
329
+ indexed: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
330
+ sortable: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
331
+ fieldName: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
332
+ bigint: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
333
+ });
334
+ const stringFieldSchema = fieldConfigSchema.extend({
335
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string'),
336
+ minLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
337
+ maxLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
338
+ pattern: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional()
339
+ });
340
+ const numberFieldSchema = fieldConfigSchema.extend({
341
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number'),
342
+ min: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
343
+ max: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional()
344
+ });
345
+ const booleanFieldSchema = fieldConfigSchema.extend({
346
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('boolean')
347
+ });
348
+ const dateFieldSchema = fieldConfigSchema.extend({
349
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('date'),
350
+ minDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
351
+ maxDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
352
+ dateOnly: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false),
353
+ format: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional()
354
+ });
355
+ const timezoneFieldSchema = fieldConfigSchema.extend({
356
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('timezone'),
357
+ validateTimezone: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
358
+ suggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional(),
359
+ restrictToSuggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
360
+ });
361
+ const jsonFieldSchema = fieldConfigSchema.extend({
362
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('json'),
363
+ validateJson: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true)
364
+ });
365
+ const stringArrayFieldSchema = fieldConfigSchema.extend({
366
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string[]')
367
+ });
368
+ const numberArrayFieldSchema = fieldConfigSchema.extend({
369
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number[]')
370
+ });
371
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.discriminatedUnion('type', [
372
+ stringFieldSchema,
373
+ numberFieldSchema,
374
+ booleanFieldSchema,
375
+ dateFieldSchema,
376
+ timezoneFieldSchema,
377
+ jsonFieldSchema,
378
+ stringArrayFieldSchema,
379
+ numberArrayFieldSchema
380
+ ]);
840
381
  const schema_auditLogSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
841
382
  id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
842
383
  entityType: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
@@ -1442,7 +983,7 @@ function validateEntityOutput(tableName, data, options) {
1442
983
  try {
1443
984
  return table.schema.parse(processedData);
1444
985
  } catch (error) {
1445
- if (error instanceof ZodError.ZodError) logger_factory_logger.error(`[validateEntityOutput] Validation failed for table ${String(tableName)}`, {
986
+ if (error instanceof __WEBPACK_EXTERNAL_MODULE_zod__.ZodError) __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__.logger.error(`[validateEntityOutput] Validation failed for table ${String(tableName)}`, {
1446
987
  table,
1447
988
  issues: error.issues
1448
989
  });
@@ -2567,9 +2108,23 @@ const memoryAdapter = (db)=>(options)=>{
2567
2108
  }
2568
2109
  };
2569
2110
  };
2111
+ let globalLogger;
2112
+ function getLogger(options) {
2113
+ if (!globalLogger) globalLogger = (0, __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__.createLogger)({
2114
+ level: 'info',
2115
+ appName: 'c15t',
2116
+ ...options
2117
+ });
2118
+ return globalLogger;
2119
+ }
2120
+ function initLogger(options) {
2121
+ globalLogger = (0, __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__.createLogger)(options);
2122
+ return globalLogger;
2123
+ }
2570
2124
  async function getAdapter(options) {
2571
- const logger = createLogger({
2572
- appName: 'c15t'
2125
+ const logger = getLogger({
2126
+ appName: options.appName ?? 'c15t',
2127
+ ...options.logger
2573
2128
  });
2574
2129
  if (!options.database) {
2575
2130
  const tables = definition_getConsentTables(options);
@@ -2591,7 +2146,7 @@ async function getAdapter(options) {
2591
2146
  })(options);
2592
2147
  }
2593
2148
  const env = 'undefined' != typeof process ? process.env : {};
2594
- const isProduction = 'undefined' != typeof process && 'production' === process.env.NODE_ENV;
2149
+ 'undefined' != typeof process && process.env.NODE_ENV;
2595
2150
  function toBoolean(val) {
2596
2151
  return val ? 'false' !== val : false;
2597
2152
  }
@@ -2631,7 +2186,6 @@ const createRegistry = (ctx)=>({
2631
2186
  ...policyRegistry(ctx),
2632
2187
  ...subjectRegistry(ctx)
2633
2188
  });
2634
- const DEFAULT_SECRET = 'c15t-default-secret-please-change-in-production';
2635
2189
  let telemetrySdk;
2636
2190
  const init = async (options)=>{
2637
2191
  try {
@@ -2640,7 +2194,7 @@ const init = async (options)=>{
2640
2194
  const basePathStr = options.basePath;
2641
2195
  const databaseHooks = options.databaseHooks || [];
2642
2196
  const appName = options.appName || 'c15t';
2643
- const logger = createLogger({
2197
+ const logger = initLogger({
2644
2198
  ...loggerOptions,
2645
2199
  appName: String(appName)
2646
2200
  });
@@ -2656,7 +2210,7 @@ const init = async (options)=>{
2656
2210
  } else {
2657
2211
  const resource = new __WEBPACK_EXTERNAL_MODULE__opentelemetry_resources_c7ac8648__.Resource({
2658
2212
  'service.name': String(appName),
2659
- 'service.version': String(process.env.npm_package_version || '1.0.0'),
2213
+ 'service.version': String(package_namespaceObject.i8 || '1.0.0'),
2660
2214
  ...telemetryOptions?.defaultAttributes || {}
2661
2215
  });
2662
2216
  logger.debug('Initializing telemetry with resource attributes', {
@@ -2694,11 +2248,8 @@ const init = async (options)=>{
2694
2248
  });
2695
2249
  return adapterResult.andThen((adapter)=>{
2696
2250
  const resolvedBaseURL = getBaseURL(baseUrlStr, basePathStr);
2697
- const secret = options.secret || env.C15T_SECRET || env.CONSENT_SECRET || DEFAULT_SECRET;
2698
- if (secret === DEFAULT_SECRET && isProduction) logger.error('Using default secret in production. Set C15T_SECRET or pass secret in config.');
2699
2251
  const finalOptions = {
2700
2252
  ...options,
2701
- secret,
2702
2253
  baseURL: resolvedBaseURL ? new URL(resolvedBaseURL).origin : '',
2703
2254
  basePath: basePathStr || '/api/c15t',
2704
2255
  plugins: [
@@ -2723,7 +2274,6 @@ const init = async (options)=>{
2723
2274
  options: finalOptions,
2724
2275
  trustedOrigins: options.trustedOrigins || [],
2725
2276
  baseURL: resolvedBaseURL || '',
2726
- secret,
2727
2277
  logger,
2728
2278
  generateId: generateIdFunc,
2729
2279
  adapter,
@@ -2733,7 +2283,7 @@ const init = async (options)=>{
2733
2283
  return runPluginInit(ctx);
2734
2284
  });
2735
2285
  } catch (error) {
2736
- const errorLogger = createLogger(options.logger);
2286
+ const errorLogger = getLogger(options.logger);
2737
2287
  errorLogger.error('Initialization failed', {
2738
2288
  error: error instanceof Error ? error.message : String(error),
2739
2289
  stack: error instanceof Error ? error.stack : void 0
@@ -2779,167 +2329,116 @@ function getInternalPlugins(_options) {
2779
2329
  const plugins = [];
2780
2330
  return plugins;
2781
2331
  }
2782
- function defineRoute(pathOrConfig, handlerOrUndefined, options) {
2783
- if ('string' == typeof pathOrConfig && handlerOrUndefined) return {
2784
- path: pathOrConfig,
2785
- handler: handlerOrUndefined,
2786
- options
2787
- };
2788
- const config = pathOrConfig;
2789
- const handler = (0, __WEBPACK_EXTERNAL_MODULE_h3__.defineEventHandler)(async (event)=>{
2790
- const logger = event.context.logger || createLogger();
2791
- logger.debug(`Handling request for ${config.method} ${config.path}`);
2792
- if (!event.context.logger) event.context.logger = logger;
2793
- const validated = {
2794
- body: void 0,
2795
- query: void 0,
2796
- params: void 0
2797
- };
2798
- try {
2799
- if (config.validations?.body) {
2800
- const contentType = event.headers.get('content-type');
2801
- const body = contentType?.includes('multipart/form-data') ? Object.fromEntries(await (0, __WEBPACK_EXTERNAL_MODULE_h3__.readFormData)(event)) : await (0, __WEBPACK_EXTERNAL_MODULE_h3__.readBody)(event);
2802
- logger.debug('Validating request body', {
2803
- body
2804
- });
2805
- const validateBody = validationPipeline(config.validations.body, (data)=>data);
2806
- const result = await validateBody(body);
2807
- result.match((data)=>{
2808
- validated.body = data;
2809
- }, (error)=>{
2810
- logger.error('Validation error (body)', {
2811
- error
2812
- });
2813
- throw new error_class_DoubleTieError('Body validation failed', {
2814
- code: error_codes_ERROR_CODES.BAD_REQUEST,
2815
- status: 422,
2816
- cause: error instanceof Error ? error : void 0,
2817
- meta: {
2818
- validationErrors: error,
2819
- requestPath: config.path,
2820
- requestMethod: config.method
2821
- }
2822
- });
2823
- });
2824
- }
2825
- if (config.validations?.query) {
2826
- const query = getQuery(event);
2827
- logger.debug('Validating query parameters', {
2828
- query
2829
- });
2830
- const validateQuery = validationPipeline(config.validations.query, (data)=>data);
2831
- const result = await validateQuery(query);
2832
- result.match((data)=>{
2833
- validated.query = data;
2834
- }, (error)=>{
2835
- logger.error('Query validation failed', {
2836
- error
2837
- });
2838
- throw new error_class_DoubleTieError('Query validation failed', {
2839
- code: error_codes_ERROR_CODES.BAD_REQUEST,
2840
- status: 422,
2841
- cause: error instanceof Error ? error : void 0,
2842
- meta: {
2843
- validationErrors: error,
2844
- requestPath: config.path,
2845
- requestMethod: config.method
2846
- }
2847
- });
2848
- });
2849
- }
2850
- if (config.validations?.params) {
2851
- const params = getRouterParams(event);
2852
- logger.debug('Validating route parameters', {
2853
- params
2854
- });
2855
- const validateParams = validationPipeline(config.validations.params, (data)=>data);
2856
- const result = await validateParams(params);
2857
- result.match((data)=>{
2858
- validated.params = data;
2859
- }, (error)=>{
2860
- logger.error('Path parameters validation failed', {
2861
- error
2862
- });
2863
- throw new error_class_DoubleTieError('Path parameters validation failed', {
2864
- code: error_codes_ERROR_CODES.BAD_REQUEST,
2865
- status: 422,
2866
- cause: error instanceof Error ? error : void 0,
2867
- meta: {
2868
- validationErrors: error,
2869
- requestPath: config.path,
2870
- requestMethod: config.method
2871
- }
2872
- });
2873
- });
2874
- }
2875
- const eventWithContext = event;
2876
- eventWithContext.context = {
2877
- ...event.context,
2878
- validated
2879
- };
2880
- logger.debug(`Executing handler for ${config.method} ${config.path}`);
2881
- const response = await config.handler(eventWithContext);
2882
- logger.debug(`Handler execution complete for ${config.method} ${config.path}, response type: ${typeof response}`);
2883
- if (null == response) {
2884
- logger.warn(`Handler for ${config.method} ${config.path} returned ${null === response ? 'null' : 'undefined'}`);
2885
- return {};
2886
- }
2887
- if ('boolean' == typeof response || 'number' == typeof response || 'string' == typeof response) {
2888
- logger.warn(`Handler for ${config.method} ${config.path} returned primitive ${typeof response}, wrapping in object`);
2889
- return {
2890
- value: response
2891
- };
2892
- }
2893
- return response;
2894
- } catch (error) {
2895
- if (error instanceof error_class_DoubleTieError) throw error;
2896
- logger.error('Validation failed', {
2897
- error
2898
- });
2899
- let validationErrors = 'Unknown validation error';
2900
- let statusCode = 422;
2901
- if (error instanceof Error) {
2902
- validationErrors = error.message;
2903
- if ('ZodError' === error.name && 'format' in error && 'function' == typeof error.format) try {
2904
- validationErrors = error.format();
2905
- statusCode = 422;
2906
- } catch {
2907
- validationErrors = `Validation error: ${error.message}`;
2908
- }
2909
- }
2910
- logger.error('Validation failed', {
2911
- error,
2912
- validationErrors
2913
- });
2914
- throw new error_class_DoubleTieError('Validation failed', {
2915
- code: error_codes_ERROR_CODES.BAD_REQUEST,
2916
- status: statusCode,
2917
- cause: error instanceof Error ? error : void 0,
2918
- meta: {
2919
- validationErrors,
2920
- requestPath: config.path,
2921
- requestMethod: config.method
2922
- }
2923
- });
2332
+ const API_ROUTER_TRACER_NAME = '@doubletie/api-router';
2333
+ const getTracer = (options)=>{
2334
+ if (options?.telemetry?.tracer) return options.telemetry.tracer;
2335
+ return __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.trace.getTracer(API_ROUTER_TRACER_NAME);
2336
+ };
2337
+ const createRequestSpan = (method, path, options)=>{
2338
+ if (options?.telemetry?.disabled) return null;
2339
+ const tracer = getTracer(options);
2340
+ const span = tracer.startSpan(`${method} ${path}`, {
2341
+ attributes: {
2342
+ 'http.method': method,
2343
+ 'http.path': path,
2344
+ ...options?.telemetry?.defaultAttributes || {}
2924
2345
  }
2925
2346
  });
2926
- return {
2927
- path: config.path,
2928
- method: config.method,
2929
- handler,
2930
- responseType: {}
2931
- };
2932
- }
2933
- function getQuery(event) {
2934
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.getQuery)(event);
2347
+ return span;
2348
+ };
2349
+ const withRequestSpan = async (method, path, operation, options)=>{
2350
+ const span = createRequestSpan(method, path, options);
2351
+ if (!span) return operation();
2352
+ try {
2353
+ const result = await operation();
2354
+ span.setStatus({
2355
+ code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK
2356
+ });
2357
+ return result;
2358
+ } catch (error) {
2359
+ handleSpanError(span, error);
2360
+ throw error;
2361
+ } finally{
2362
+ span.end();
2363
+ }
2364
+ };
2365
+ const handleSpanError = (span, error)=>{
2366
+ span.setStatus({
2367
+ code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.ERROR,
2368
+ message: error instanceof Error ? error.message : String(error)
2369
+ });
2370
+ if (error instanceof Error) {
2371
+ span.setAttribute('error.type', error.name);
2372
+ span.setAttribute('error.message', error.message);
2373
+ if (error.stack) span.setAttribute('error.stack', error.stack);
2374
+ }
2375
+ };
2376
+ const STRIP_REGEX = /^(https?:\/\/)|(wss?:\/\/)|(\/+$)|:\d+/g;
2377
+ function isOriginTrusted(origin, trustedDomains, logger) {
2378
+ try {
2379
+ if (0 === trustedDomains.length) throw new Error('No trusted domains');
2380
+ logger?.debug(`Checking if origin ${origin} is trusted in ${trustedDomains}`);
2381
+ if (trustedDomains.includes('*')) {
2382
+ logger?.debug('Allowing all origins');
2383
+ return true;
2384
+ }
2385
+ const url = new URL(origin);
2386
+ const originHostname = url.hostname.toLowerCase();
2387
+ logger?.debug(`Parsed origin hostname: ${originHostname}`);
2388
+ return trustedDomains.some((domain)=>{
2389
+ if (!domain || '' === domain.trim()) {
2390
+ logger?.debug('Skipping empty domain');
2391
+ return false;
2392
+ }
2393
+ const strippedDomain = domain.replace(STRIP_REGEX, '').toLowerCase();
2394
+ logger?.debug(`Checking against stripped domain: ${strippedDomain}`);
2395
+ if (strippedDomain.startsWith('*.')) {
2396
+ const wildcardDomain = strippedDomain.slice(2);
2397
+ const parts = originHostname.split('.');
2398
+ const isValid = parts.length > 2 && originHostname.endsWith(wildcardDomain);
2399
+ logger?.debug(`Wildcard match result: ${isValid} ${originHostname} ends with ${wildcardDomain} ${parts.length > 2} ${originHostname.endsWith(wildcardDomain)}`);
2400
+ return isValid;
2401
+ }
2402
+ const isMatch = originHostname === strippedDomain;
2403
+ logger?.debug(`Exact match result: ${isMatch} ${originHostname} === ${strippedDomain}`);
2404
+ return isMatch;
2405
+ });
2406
+ } catch (error) {
2407
+ logger?.error('Error validating origin:', error);
2408
+ return false;
2409
+ }
2935
2410
  }
2936
- function getRouterParams(event) {
2937
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.getRouterParams)(event) || {};
2411
+ const DEFAULT_IP_HEADERS = [
2412
+ 'x-client-ip',
2413
+ 'x-forwarded-for',
2414
+ 'cf-connecting-ip',
2415
+ 'fastly-client-ip',
2416
+ 'x-real-ip',
2417
+ 'x-cluster-client-ip',
2418
+ 'x-forwarded',
2419
+ 'forwarded-for',
2420
+ 'forwarded'
2421
+ ];
2422
+ function getIp(req, options) {
2423
+ const advanced = options.advanced || {};
2424
+ if (advanced?.ipAddress?.disableIpTracking) return null;
2425
+ const testIP = '127.0.0.1';
2426
+ if (isTest) return testIP;
2427
+ const ipHeaders = advanced?.ipAddress?.ipAddressHeaders || DEFAULT_IP_HEADERS;
2428
+ const headers = req instanceof Request ? req.headers : req;
2429
+ for (const key of ipHeaders){
2430
+ const value = headers.get(key);
2431
+ if (value) {
2432
+ const ip = value.split(',')[0]?.trim();
2433
+ if (ip) return ip;
2434
+ }
2435
+ }
2436
+ return null;
2938
2437
  }
2939
2438
  const baseConsentSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2940
2439
  subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2941
2440
  externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2942
- domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2441
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i, 'invalid domain'),
2943
2442
  type: PolicyTypeSchema,
2944
2443
  metadata: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional()
2945
2444
  });
@@ -2964,210 +2463,513 @@ const otherConsentSchema = baseConsentSchema.extend({
2964
2463
  ]),
2965
2464
  preferences: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.boolean()).optional()
2966
2465
  });
2967
- const SetConsentRequestBody = __WEBPACK_EXTERNAL_MODULE_zod__.z.discriminatedUnion('type', [
2968
- cookieBannerSchema,
2969
- policyBasedSchema,
2970
- otherConsentSchema
2971
- ]);
2972
- const setConsent = defineRoute({
2466
+ const postConsentContract = __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__.oc.route({
2467
+ method: 'POST',
2973
2468
  path: '/consent/set',
2974
- method: 'post',
2975
- validations: {
2976
- body: SetConsentRequestBody
2469
+ description: `Records a user's consent preferences and creates necessary consent records.
2470
+ This endpoint handles various types of consent submissions:
2471
+
2472
+ 1. Cookie Banner Consent:
2473
+ - Records granular cookie preferences
2474
+ - Supports multiple consent purposes
2475
+ - Creates audit trail for compliance
2476
+
2477
+ 2. Policy-Based Consent:
2478
+ - Privacy Policy acceptance
2479
+ - Data Processing Agreement (DPA) consent
2480
+ - Terms and Conditions acceptance
2481
+ - Links consent to specific policy versions
2482
+
2483
+ 3. Other Consent Types:
2484
+ - Marketing communications preferences
2485
+ - Age verification consent
2486
+ - Custom consent types
2487
+
2488
+ The endpoint performs the following operations:
2489
+ - Creates or retrieves subject records
2490
+ - Validates domain and policy information
2491
+ - Creates consent records with audit trails
2492
+ - Records consent purposes and preferences
2493
+ - Generates audit logs for compliance
2494
+
2495
+ Use this endpoint to record user consent and maintain a compliant consent management system.`,
2496
+ tags: [
2497
+ 'consent',
2498
+ 'cookie-banner'
2499
+ ]
2500
+ }).errors({
2501
+ INPUT_VALIDATION_FAILED: {
2502
+ status: 422,
2503
+ message: 'Invalid input parameters',
2504
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2505
+ formErrors: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()),
2506
+ fieldErrors: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.string(), __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()))
2507
+ })
2977
2508
  },
2978
- handler: async (event)=>{
2979
- const logger = event.context.logger || createLogger();
2980
- logger.info('Handling set-consent request');
2981
- const { body } = event.context.validated;
2982
- const { registry, adapter } = event.context;
2983
- const { type, subjectId, externalSubjectId, domain, metadata } = body;
2984
- logger.debug('Request parameters', {
2985
- type,
2986
- subjectId,
2987
- externalSubjectId,
2988
- domain
2989
- });
2990
- try {
2991
- const subject = await registry.findOrCreateSubject({
2992
- subjectId,
2993
- externalSubjectId,
2994
- ipAddress: event.context.ipAddress || 'unknown'
2995
- });
2996
- if (!subject) {
2997
- const errMsg = 'Subject not found or could not be created';
2998
- logger.error(errMsg, {
2999
- subjectId,
3000
- externalSubjectId
3001
- });
3002
- throw new error_class_DoubleTieError(errMsg, {
3003
- code: error_codes_ERROR_CODES.BAD_REQUEST,
3004
- status: 400,
3005
- meta: {
3006
- subjectId,
3007
- externalSubjectId
3008
- }
3009
- });
2509
+ SUBJECT_CREATION_FAILED: {
2510
+ status: 400,
2511
+ message: 'Failed to create or find subject',
2512
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2513
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2514
+ externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional()
2515
+ })
2516
+ },
2517
+ DOMAIN_CREATION_FAILED: {
2518
+ status: 500,
2519
+ message: 'Failed to create or find domain',
2520
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2521
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2522
+ })
2523
+ },
2524
+ POLICY_NOT_FOUND: {
2525
+ status: 404,
2526
+ message: 'Policy not found',
2527
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2528
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2529
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2530
+ })
2531
+ },
2532
+ POLICY_INACTIVE: {
2533
+ status: 409,
2534
+ message: 'Policy is not active',
2535
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2536
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2537
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2538
+ })
2539
+ },
2540
+ POLICY_CREATION_FAILED: {
2541
+ status: 500,
2542
+ message: 'Failed to create or find policy',
2543
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2544
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2545
+ })
2546
+ },
2547
+ PURPOSE_CREATION_FAILED: {
2548
+ status: 500,
2549
+ message: 'Failed to create consent purpose',
2550
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2551
+ purposeCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2552
+ })
2553
+ },
2554
+ CONSENT_CREATION_FAILED: {
2555
+ status: 500,
2556
+ message: 'Failed to create consent record',
2557
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2558
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2559
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2560
+ })
2561
+ }
2562
+ }).input(__WEBPACK_EXTERNAL_MODULE_zod__.z.discriminatedUnion('type', [
2563
+ cookieBannerSchema,
2564
+ policyBasedSchema,
2565
+ otherConsentSchema
2566
+ ])).output(__WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2567
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2568
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2569
+ externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2570
+ domainId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2571
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2572
+ type: PolicyTypeSchema,
2573
+ status: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2574
+ recordId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2575
+ metadata: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional(),
2576
+ givenAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date()
2577
+ }));
2578
+ const JurisdictionMessages = {
2579
+ GDPR: 'GDPR or equivalent regulations require a cookie banner.',
2580
+ CH: 'Switzerland requires similar data protection measures.',
2581
+ BR: "Brazil's LGPD requires consent for cookies.",
2582
+ PIPEDA: 'PIPEDA requires consent for data collection.',
2583
+ AU: "Australia's Privacy Act mandates transparency about data collection.",
2584
+ APPI: "Japan's APPI requires consent for data collection.",
2585
+ PIPA: "South Korea's PIPA requires consent for data collection.",
2586
+ NONE: 'No specific requirements'
2587
+ };
2588
+ const JurisdictionCodeSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z["enum"]([
2589
+ 'GDPR',
2590
+ 'CH',
2591
+ 'BR',
2592
+ 'PIPEDA',
2593
+ 'AU',
2594
+ 'APPI',
2595
+ 'PIPA',
2596
+ 'NONE'
2597
+ ]);
2598
+ const JurisdictionInfoSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2599
+ code: JurisdictionCodeSchema,
2600
+ message: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2601
+ });
2602
+ const showConsentBannerContract = __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__.oc.route({
2603
+ method: 'GET',
2604
+ path: '/show-consent-banner',
2605
+ description: `Determines if a user should see a consent banner based on their location and applicable privacy regulations.
2606
+ This endpoint performs the following checks:
2607
+
2608
+ 1. Detects the user's location using various header information:
2609
+ - Cloudflare country headers
2610
+ - Vercel IP country headers
2611
+ - AWS CloudFront headers
2612
+ - Custom country code headers
2613
+
2614
+ 2. Determines the applicable jurisdiction based on the location:
2615
+ - GDPR (EU/EEA/UK)
2616
+ - Swiss Data Protection Act
2617
+ - LGPD (Brazil)
2618
+ - PIPEDA (Canada)
2619
+ - Australian Privacy Principles
2620
+ - APPI (Japan)
2621
+ - PIPA (South Korea)
2622
+
2623
+ 3. Returns detailed information about:
2624
+ - Whether to show the consent banner
2625
+ - The applicable jurisdiction and its requirements
2626
+ - The user's detected location (country and region)
2627
+
2628
+ Use this endpoint to implement geo-targeted consent banners and ensure compliance with regional privacy regulations.`,
2629
+ tags: [
2630
+ 'cookie-banner'
2631
+ ]
2632
+ }).output(__WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2633
+ showConsentBanner: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean(),
2634
+ jurisdiction: JurisdictionInfoSchema,
2635
+ location: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2636
+ countryCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable(),
2637
+ regionCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable()
2638
+ })
2639
+ }));
2640
+ const verifyConsentInputSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2641
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2642
+ externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2643
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2644
+ type: PolicyTypeSchema,
2645
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2646
+ preferences: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional()
2647
+ }).strict();
2648
+ const verify_contract_consentSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2649
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2650
+ purposeIds: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string())
2651
+ }).passthrough();
2652
+ const verifyConsentContract = __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__.oc.route({
2653
+ method: 'POST',
2654
+ path: '/consent/verify',
2655
+ description: `Verifies if a user has given valid consent for a specific policy and domain.
2656
+ This endpoint performs comprehensive consent verification by:
2657
+
2658
+ 1. Validating the subject's identity (using subjectId or externalSubjectId)
2659
+ 2. Verifying the domain's existence and validity
2660
+ 3. Checking if the specified policy exists and is active
2661
+ 4. Validating that all required purposes have been consented to
2662
+ 5. Ensuring the consent record is current and valid
2663
+
2664
+ The endpoint supports different types of consent verification:
2665
+ - Cookie banner consent verification
2666
+ - Privacy policy consent verification
2667
+ - Terms and conditions verification
2668
+ - Marketing communications consent verification
2669
+ - Age verification
2670
+ - Custom consent types
2671
+
2672
+ Use this endpoint to ensure compliance with privacy regulations and to verify user consent before processing personal data.`,
2673
+ tags: [
2674
+ 'consent'
2675
+ ]
2676
+ }).errors({
2677
+ INPUT_VALIDATION_FAILED: {
2678
+ status: 422,
2679
+ message: 'Invalid input parameters',
2680
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2681
+ formErrors: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()),
2682
+ fieldErrors: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.string(), __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional())
2683
+ })
2684
+ },
2685
+ SUBJECT_NOT_FOUND: {
2686
+ status: 404,
2687
+ message: 'Subject not found',
2688
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2689
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2690
+ externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional()
2691
+ })
2692
+ },
2693
+ DOMAIN_NOT_FOUND: {
2694
+ status: 404,
2695
+ message: 'Domain not found',
2696
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2697
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2698
+ })
2699
+ },
2700
+ POLICY_NOT_FOUND: {
2701
+ status: 404,
2702
+ message: 'Policy not found or invalid',
2703
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2704
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2705
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2706
+ })
2707
+ },
2708
+ PURPOSES_NOT_FOUND: {
2709
+ status: 404,
2710
+ message: 'Could not find all specified purposes',
2711
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2712
+ preferences: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()),
2713
+ foundPurposes: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string())
2714
+ })
2715
+ },
2716
+ COOKIE_BANNER_PREFERENCES_REQUIRED: {
2717
+ status: 400,
2718
+ message: 'Preferences are required for cookie banner consent',
2719
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2720
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('cookie_banner')
2721
+ })
2722
+ },
2723
+ NO_CONSENT_FOUND: {
2724
+ status: 404,
2725
+ message: 'No consent found for the given policy',
2726
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2727
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2728
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2729
+ domainId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2730
+ })
2731
+ }
2732
+ }).input(verifyConsentInputSchema).output(__WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2733
+ isValid: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean(),
2734
+ reasons: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional(),
2735
+ consent: verify_contract_consentSchema.optional()
2736
+ }));
2737
+ const consentContracts = {
2738
+ post: postConsentContract,
2739
+ showBanner: showConsentBannerContract,
2740
+ verify: verifyConsentContract
2741
+ };
2742
+ const statusContract = __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__.oc.route({
2743
+ method: 'GET',
2744
+ path: '/status',
2745
+ description: `Returns the current operational status and health metrics of the service.
2746
+ This endpoint provides real-time information about:
2747
+ - Overall service status (ok/error)
2748
+ - Current API version
2749
+ - Server timestamp
2750
+ - Storage system status and availability
2751
+ - Client information (IP, User Agent, Region)
2752
+
2753
+ Use this endpoint for health checks, monitoring, and service status verification.`,
2754
+ tags: [
2755
+ 'meta'
2756
+ ]
2757
+ }).output(__WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2758
+ status: __WEBPACK_EXTERNAL_MODULE_zod__.z["enum"]([
2759
+ 'ok',
2760
+ 'error'
2761
+ ]),
2762
+ version: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2763
+ timestamp: __WEBPACK_EXTERNAL_MODULE_zod__.z.date(),
2764
+ storage: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2765
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2766
+ available: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean()
2767
+ }),
2768
+ client: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2769
+ ip: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable(),
2770
+ userAgent: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable(),
2771
+ region: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2772
+ countryCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable(),
2773
+ regionCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable()
2774
+ })
2775
+ })
2776
+ }));
2777
+ const metaContracts = {
2778
+ status: statusContract
2779
+ };
2780
+ const contracts_config = {
2781
+ consent: consentContracts,
2782
+ meta: metaContracts
2783
+ };
2784
+ const os = (0, __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.implement)(contracts_config);
2785
+ const postConsent = os.consent.post.handler(async ({ input, context })=>{
2786
+ const typedContext = context;
2787
+ const logger = typedContext.logger;
2788
+ logger.info('Handling post-consent request');
2789
+ const { type, subjectId, externalSubjectId, domain, metadata, preferences } = input;
2790
+ logger.debug('Request parameters', {
2791
+ type,
2792
+ subjectId,
2793
+ externalSubjectId,
2794
+ domain
2795
+ });
2796
+ try {
2797
+ const subject = await typedContext.registry.findOrCreateSubject({
2798
+ subjectId,
2799
+ externalSubjectId,
2800
+ ipAddress: typedContext.ipAddress || 'unknown'
2801
+ });
2802
+ if (!subject) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('SUBJECT_CREATION_FAILED', {
2803
+ data: {
2804
+ subjectId,
2805
+ externalSubjectId
3010
2806
  }
3011
- logger.debug('Subject found/created', {
3012
- subjectId: subject.id
3013
- });
3014
- const domainRecord = await registry.findOrCreateDomain(domain);
3015
- const now = new Date();
3016
- let policyId;
3017
- let purposeIds = [];
3018
- if ('policyId' in body) {
3019
- const { policyId: pid } = body;
3020
- policyId = pid;
3021
- if (!policyId) throw new error_class_DoubleTieError('Policy ID is required', {
3022
- code: error_codes_ERROR_CODES.BAD_REQUEST,
3023
- status: 400,
3024
- meta: {
3025
- type
3026
- }
3027
- });
3028
- const policy = await registry.findConsentPolicyById(policyId);
3029
- if (!policy) throw new error_class_DoubleTieError('Policy not found', {
3030
- code: error_codes_ERROR_CODES.NOT_FOUND,
3031
- status: 404,
3032
- meta: {
3033
- policyId
3034
- }
3035
- });
3036
- if (!policy.isActive) throw new error_class_DoubleTieError('Policy is not active', {
3037
- code: error_codes_ERROR_CODES.CONFLICT,
3038
- status: 409,
3039
- meta: {
3040
- policyId
3041
- }
3042
- });
3043
- } else {
3044
- const policy = await registry.findOrCreatePolicy(type);
3045
- if (!policy) throw new error_class_DoubleTieError('Failed to create or find policy', {
3046
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
3047
- status: 500,
3048
- meta: {
3049
- type
3050
- }
3051
- });
3052
- policyId = policy.id;
2807
+ });
2808
+ logger.debug('Subject found/created', {
2809
+ subjectId: subject.id
2810
+ });
2811
+ const domainRecord = await typedContext.registry.findOrCreateDomain(domain);
2812
+ if (!domainRecord) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('DOMAIN_CREATION_FAILED', {
2813
+ data: {
2814
+ domain
3053
2815
  }
3054
- if ('preferences' in body && body.preferences) purposeIds = await Promise.all(Object.entries(body.preferences).filter(([_, isConsented])=>isConsented).map(async ([purposeCode])=>{
3055
- let existingPurpose = await registry.findConsentPurposeByCode(purposeCode);
3056
- if (!existingPurpose) existingPurpose = await registry.createConsentPurpose({
2816
+ });
2817
+ const now = new Date();
2818
+ let policyId;
2819
+ let purposeIds = [];
2820
+ if ('policyId' in input && input.policyId) {
2821
+ policyId = input.policyId;
2822
+ const policy = await typedContext.registry.findConsentPolicyById(policyId);
2823
+ if (!policy) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_NOT_FOUND', {
2824
+ data: {
2825
+ policyId,
2826
+ type
2827
+ }
2828
+ });
2829
+ if (!policy.isActive) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_INACTIVE', {
2830
+ data: {
2831
+ policyId,
2832
+ type
2833
+ }
2834
+ });
2835
+ } else {
2836
+ const policy = await typedContext.registry.findOrCreatePolicy(type);
2837
+ if (!policy) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_CREATION_FAILED', {
2838
+ data: {
2839
+ type
2840
+ }
2841
+ });
2842
+ policyId = policy.id;
2843
+ }
2844
+ if (preferences) {
2845
+ const consentedPurposes = Object.entries(preferences).filter(([_, isConsented])=>isConsented).map(([purposeCode])=>purposeCode);
2846
+ const existingPurposes = await Promise.all(consentedPurposes.map((purposeCode)=>typedContext.registry.findConsentPurposeByCode(purposeCode)));
2847
+ const purposesToCreate = consentedPurposes.filter((_purposeCode, index)=>!existingPurposes[index]);
2848
+ const createdPurposes = await Promise.all(purposesToCreate.map((purposeCode)=>typedContext.registry.createConsentPurpose({
3057
2849
  code: purposeCode,
3058
2850
  name: purposeCode,
3059
2851
  description: `Auto-created consentPurpose for ${purposeCode}`,
3060
2852
  isActive: true,
3061
2853
  isEssential: false,
3062
- dataCategory: 'functional',
3063
2854
  legalBasis: 'consent',
3064
2855
  createdAt: now,
3065
2856
  updatedAt: now
3066
- });
3067
- return existingPurpose.id;
3068
- }));
3069
- const result = await adapter.transaction({
3070
- callback: async (tx)=>{
3071
- const consentRecord = await tx.create({
3072
- model: 'consent',
3073
- data: {
3074
- subjectId: subject.id,
3075
- domainId: domainRecord.id,
3076
- policyId,
3077
- purposeIds,
3078
- status: 'active',
3079
- isActive: true,
3080
- givenAt: now,
3081
- ipAddress: event.context.ipAddress || 'unknown',
3082
- agent: event.context.userAgent || 'unknown',
3083
- history: []
3084
- }
3085
- });
3086
- const record = await tx.create({
3087
- model: 'consentRecord',
3088
- data: {
3089
- subjectId: subject.id,
3090
- consentId: consentRecord.id,
3091
- actionType: 'consent_given',
3092
- details: metadata,
3093
- createdAt: now
3094
- }
3095
- });
3096
- await tx.create({
3097
- model: 'auditLog',
3098
- data: {
3099
- subjectId: subject.id,
3100
- entityType: 'consent',
3101
- entityId: consentRecord.id,
3102
- actionType: 'consent_given',
3103
- details: {
3104
- consentId: consentRecord.id,
3105
- type
3106
- },
3107
- timestamp: now,
3108
- ipAddress: event.context.ipAddress || 'unknown',
3109
- agent: event.context.userAgent || 'unknown'
3110
- }
3111
- });
3112
- return {
3113
- consent: consentRecord,
3114
- record
3115
- };
3116
- }
3117
- });
3118
- if (!result || !result.consent || !result.record) throw new error_class_DoubleTieError('Failed to create consent record', {
3119
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
3120
- status: 500,
3121
- meta: {
3122
- subjectId: subject.id,
3123
- domain
2857
+ })));
2858
+ purposeIds = [
2859
+ ...existingPurposes.filter((p)=>null !== p).map((p)=>p.id),
2860
+ ...createdPurposes.filter((p)=>null !== p).map((p)=>p.id)
2861
+ ];
2862
+ if (purposeIds.length !== consentedPurposes.length) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('PURPOSE_CREATION_FAILED', {
2863
+ data: {
2864
+ purposeCode: purposesToCreate[purposeIds.length - consentedPurposes.length]
3124
2865
  }
3125
2866
  });
3126
- const response = {
3127
- id: result.consent.id,
3128
- subjectId: subject.id,
3129
- externalSubjectId: subject.externalId ?? void 0,
3130
- domainId: domainRecord.id,
3131
- domain: domainRecord.name,
3132
- type,
3133
- status: result.consent.status,
3134
- recordId: result.record.id,
3135
- metadata,
3136
- givenAt: result.consent.givenAt.toISOString()
3137
- };
3138
- logger.info('Set-consent successful', {
3139
- consentId: response.id
3140
- });
3141
- return response;
3142
- } catch (error) {
3143
- logger.error('Error in set-consent handler', {
3144
- error: error instanceof Error ? error.message : String(error),
3145
- errorType: error instanceof Error ? error.constructor.name : typeof error
3146
- });
3147
- throw error;
3148
2867
  }
3149
- }
3150
- });
3151
- const show_consent_banner_showConsentBanner = defineRoute({
3152
- path: '/show-consent-banner',
3153
- method: 'get',
3154
- handler: async (event)=>{
3155
- const countryCode = event.headers.get('cf-ipcountry') || event.headers.get('x-vercel-ip-country') || event.headers.get('x-amz-cf-ipcountry') || event.headers.get('x-country-code');
3156
- const regionCode = event.headers.get('x-vercel-ip-country-region') || event.headers.get('x-region-code');
3157
- const { showConsentBanner, jurisdictionCode, message } = checkJurisdiction(countryCode ?? null);
3158
- return {
3159
- showConsentBanner,
3160
- jurisdiction: {
3161
- code: jurisdictionCode,
3162
- message
3163
- },
3164
- location: {
3165
- countryCode,
3166
- regionCode
2868
+ const result = await typedContext.adapter.transaction({
2869
+ callback: async (tx)=>{
2870
+ const consentRecord = await tx.create({
2871
+ model: 'consent',
2872
+ data: {
2873
+ subjectId: subject.id,
2874
+ domainId: domainRecord.id,
2875
+ policyId,
2876
+ purposeIds,
2877
+ status: 'active',
2878
+ isActive: true,
2879
+ givenAt: now,
2880
+ ipAddress: typedContext.ipAddress || 'unknown',
2881
+ agent: typedContext.userAgent || 'unknown',
2882
+ history: []
2883
+ }
2884
+ });
2885
+ const record = await tx.create({
2886
+ model: 'consentRecord',
2887
+ data: {
2888
+ subjectId: subject.id,
2889
+ consentId: consentRecord.id,
2890
+ actionType: 'consent_given',
2891
+ details: metadata,
2892
+ createdAt: now
2893
+ }
2894
+ });
2895
+ await tx.create({
2896
+ model: 'auditLog',
2897
+ data: {
2898
+ subjectId: subject.id,
2899
+ entityType: 'consent',
2900
+ entityId: consentRecord.id,
2901
+ actionType: 'consent_given',
2902
+ details: {
2903
+ consentId: consentRecord.id,
2904
+ type
2905
+ },
2906
+ timestamp: now,
2907
+ ipAddress: typedContext.ipAddress || 'unknown',
2908
+ agent: typedContext.userAgent || 'unknown'
2909
+ }
2910
+ });
2911
+ return {
2912
+ consent: consentRecord,
2913
+ record
2914
+ };
3167
2915
  }
2916
+ });
2917
+ if (!result || !result.consent || !result.record) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('CONSENT_CREATION_FAILED', {
2918
+ data: {
2919
+ subjectId: subject.id,
2920
+ domain
2921
+ }
2922
+ });
2923
+ return {
2924
+ id: result.consent.id,
2925
+ subjectId: subject.id,
2926
+ externalSubjectId: subject.externalId ?? void 0,
2927
+ domainId: domainRecord.id,
2928
+ domain: domainRecord.name,
2929
+ type,
2930
+ status: result.consent.status,
2931
+ recordId: result.record.id,
2932
+ metadata,
2933
+ givenAt: result.consent.givenAt
3168
2934
  };
2935
+ } catch (error) {
2936
+ logger.error('Error in post-consent handler', {
2937
+ error: error instanceof Error ? error.message : String(error),
2938
+ errorType: error instanceof Error ? error.constructor.name : typeof error
2939
+ });
2940
+ if (error instanceof __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError) throw error;
2941
+ throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('INTERNAL_SERVER_ERROR', {
2942
+ message: error instanceof Error ? error.message : String(error)
2943
+ });
3169
2944
  }
3170
2945
  });
2946
+ const show_banner_handler_showConsentBanner = os.consent.showBanner.handler(({ context })=>{
2947
+ const typedContext = context;
2948
+ const headers = typedContext.headers;
2949
+ if (!headers) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('LOCATION_DETECTION_FAILED', {
2950
+ data: {
2951
+ reason: 'No headers found in request context'
2952
+ }
2953
+ });
2954
+ const normalizeHeader = (value)=>{
2955
+ if (!value) return null;
2956
+ return Array.isArray(value) ? value[0] ?? null : value;
2957
+ };
2958
+ const countryCode = normalizeHeader(headers.get('cf-ipcountry')) ?? normalizeHeader(headers.get('x-vercel-ip-country')) ?? normalizeHeader(headers.get('x-amz-cf-ipcountry')) ?? normalizeHeader(headers.get('x-country-code'));
2959
+ const regionCode = normalizeHeader(headers.get('x-vercel-ip-country-region')) ?? normalizeHeader(headers.get('x-region-code'));
2960
+ const { showConsentBanner, jurisdictionCode, message } = checkJurisdiction(countryCode);
2961
+ return {
2962
+ showConsentBanner,
2963
+ jurisdiction: {
2964
+ code: jurisdictionCode,
2965
+ message
2966
+ },
2967
+ location: {
2968
+ countryCode,
2969
+ regionCode
2970
+ }
2971
+ };
2972
+ });
3171
2973
  function checkJurisdiction(countryCode) {
3172
2974
  const jurisdictions = {
3173
2975
  EU: new Set([
@@ -3228,150 +3030,156 @@ function checkJurisdiction(countryCode) {
3228
3030
  };
3229
3031
  let showConsentBanner = false;
3230
3032
  let jurisdictionCode = 'NONE';
3231
- let message = 'No specific requirements';
3232
3033
  if (countryCode) {
3233
- if (jurisdictions.EU.has(countryCode) || jurisdictions.EEA.has(countryCode) || jurisdictions.UK.has(countryCode)) {
3234
- showConsentBanner = true;
3235
- jurisdictionCode = 'GDPR';
3236
- message = 'GDPR or equivalent regulations require a cookie banner.';
3237
- } else if (jurisdictions.CH.has(countryCode)) {
3238
- showConsentBanner = true;
3239
- jurisdictionCode = 'CH';
3240
- message = 'Switzerland requires similar data protection measures.';
3241
- } else if (jurisdictions.BR.has(countryCode)) {
3242
- showConsentBanner = true;
3243
- jurisdictionCode = 'BR';
3244
- message = "Brazil's LGPD requires consent for cookies.";
3245
- } else if (jurisdictions.CA.has(countryCode)) {
3246
- showConsentBanner = true;
3247
- jurisdictionCode = 'PIPEDA';
3248
- message = 'PIPEDA requires consent for data collection.';
3249
- } else if (jurisdictions.AU.has(countryCode)) {
3250
- showConsentBanner = true;
3251
- jurisdictionCode = 'AU';
3252
- message = "Australia's Privacy Act mandates transparency about data collection.";
3253
- } else if (jurisdictions.JP.has(countryCode)) {
3254
- showConsentBanner = true;
3255
- jurisdictionCode = 'APPI';
3256
- message = "Japan's APPI requires consent for data collection.";
3257
- } else if (jurisdictions.KR.has(countryCode)) {
3034
+ const jurisdictionMap = [
3035
+ {
3036
+ sets: [
3037
+ jurisdictions.EU,
3038
+ jurisdictions.EEA,
3039
+ jurisdictions.UK
3040
+ ],
3041
+ code: 'GDPR'
3042
+ },
3043
+ {
3044
+ sets: [
3045
+ jurisdictions.CH
3046
+ ],
3047
+ code: 'CH'
3048
+ },
3049
+ {
3050
+ sets: [
3051
+ jurisdictions.BR
3052
+ ],
3053
+ code: 'BR'
3054
+ },
3055
+ {
3056
+ sets: [
3057
+ jurisdictions.CA
3058
+ ],
3059
+ code: 'PIPEDA'
3060
+ },
3061
+ {
3062
+ sets: [
3063
+ jurisdictions.AU
3064
+ ],
3065
+ code: 'AU'
3066
+ },
3067
+ {
3068
+ sets: [
3069
+ jurisdictions.JP
3070
+ ],
3071
+ code: 'APPI'
3072
+ },
3073
+ {
3074
+ sets: [
3075
+ jurisdictions.KR
3076
+ ],
3077
+ code: 'PIPA'
3078
+ }
3079
+ ];
3080
+ for (const { sets, code } of jurisdictionMap)if (sets.some((set)=>set.has(countryCode))) {
3258
3081
  showConsentBanner = true;
3259
- jurisdictionCode = 'PIPA';
3260
- message = "South Korea's PIPA requires consent for data collection.";
3082
+ jurisdictionCode = code;
3083
+ break;
3261
3084
  }
3262
3085
  }
3086
+ const message = JurisdictionMessages[jurisdictionCode];
3263
3087
  return {
3264
3088
  showConsentBanner,
3265
3089
  jurisdictionCode,
3266
3090
  message
3267
3091
  };
3268
3092
  }
3269
- var package_namespaceObject = {
3270
- i8: "1.0.0"
3271
- };
3272
- const status_status = defineRoute({
3273
- path: '/status',
3274
- method: 'get',
3275
- handler: async (event)=>{
3276
- const response = {
3277
- status: 'ok',
3278
- version: package_namespaceObject.i8,
3279
- timestamp: new Date().toISOString(),
3280
- storage: {
3281
- type: event.context.adapter?.id ?? 'Unavailable',
3282
- available: !!event.context.adapter
3283
- }
3284
- };
3285
- return response;
3286
- }
3287
- });
3288
- const VerifyConsentRequestBody = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
3289
- subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
3290
- externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
3291
- domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
3292
- type: PolicyTypeSchema,
3293
- policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
3294
- preferences: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional()
3295
- });
3296
- const verifyConsent = defineRoute({
3297
- path: '/consent/verify',
3298
- method: 'post',
3299
- validations: {
3300
- body: VerifyConsentRequestBody
3301
- },
3302
- handler: async (event)=>{
3303
- const { body } = event.context.validated;
3304
- const { type, subjectId, externalSubjectId, domain, policyId, preferences } = body;
3305
- const { registry } = event.context;
3306
- const subject = await registry.findOrCreateSubject({
3093
+ const verifyConsent = os.consent.verify.handler(async ({ input, context })=>{
3094
+ const typedContext = context;
3095
+ const logger = typedContext.logger;
3096
+ logger.info('Handling verify-consent request');
3097
+ const { type, subjectId, externalSubjectId, domain, policyId, preferences } = input;
3098
+ logger.debug('Request parameters', {
3099
+ type,
3100
+ subjectId,
3101
+ externalSubjectId,
3102
+ domain,
3103
+ policyId,
3104
+ preferences
3105
+ });
3106
+ try {
3107
+ const subject = await typedContext.registry.findOrCreateSubject({
3307
3108
  subjectId,
3308
3109
  externalSubjectId,
3309
- ipAddress: event.context.ipAddress || 'unknown'
3110
+ ipAddress: typedContext.ipAddress || 'unknown'
3310
3111
  });
3311
- if (!subject) return {
3312
- isValid: false,
3313
- reasons: [
3314
- 'Subject not found'
3315
- ]
3316
- };
3317
- const domainRecord = await registry.findDomain(domain);
3318
- if (!domainRecord) return {
3319
- isValid: false,
3320
- reasons: [
3321
- 'Domain not found'
3322
- ]
3323
- };
3324
- if ('cookie_banner' === type && preferences?.length === 0) return {
3325
- isValid: false,
3326
- reasons: [
3327
- 'Preferences are required'
3328
- ]
3329
- };
3330
- const purposePromises = preferences?.map((purpose)=>registry.findConsentPurposeByCode(purpose));
3112
+ if (!subject) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('SUBJECT_NOT_FOUND', {
3113
+ data: {
3114
+ subjectId,
3115
+ externalSubjectId
3116
+ }
3117
+ });
3118
+ const domainRecord = await typedContext.registry.findDomain(domain);
3119
+ if (!domainRecord) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('DOMAIN_NOT_FOUND', {
3120
+ data: {
3121
+ domain
3122
+ }
3123
+ });
3124
+ if ('cookie_banner' === type && (!preferences || 0 === preferences.length)) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('COOKIE_BANNER_PREFERENCES_REQUIRED', {
3125
+ data: {
3126
+ type: 'cookie_banner'
3127
+ }
3128
+ });
3129
+ const purposePromises = preferences?.map((purpose)=>typedContext.registry.findConsentPurposeByCode(purpose));
3331
3130
  const rawPurposes = await Promise.all(purposePromises ?? []);
3332
3131
  const purposeIds = rawPurposes.filter((purpose)=>null !== purpose).map((purpose)=>purpose.id);
3333
- if (purposeIds.length !== (preferences?.length ?? 0)) return {
3334
- isValid: false,
3335
- reasons: [
3336
- 'Could not find all purposes'
3337
- ]
3338
- };
3132
+ if (purposeIds.length !== (preferences?.length ?? 0)) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('PURPOSES_NOT_FOUND', {
3133
+ data: {
3134
+ preferences: preferences ?? [],
3135
+ foundPurposes: rawPurposes.filter((p)=>null !== p).map((p)=>p.code)
3136
+ }
3137
+ });
3339
3138
  if (policyId) {
3340
- const policy = await registry.findConsentPolicyById(policyId);
3341
- if (!policy || policy.type !== type) return {
3342
- isValid: false,
3343
- reasons: [
3344
- 'Policy not found'
3345
- ]
3346
- };
3347
- return await policyConsentGiven({
3139
+ const policy = await typedContext.registry.findConsentPolicyById(policyId);
3140
+ if (!policy || policy.type !== type) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_NOT_FOUND', {
3141
+ data: {
3142
+ policyId,
3143
+ type
3144
+ }
3145
+ });
3146
+ return await checkPolicyConsent({
3348
3147
  policyId: policy.id,
3349
3148
  subjectId: subject.id,
3350
3149
  domainId: domainRecord.id,
3351
3150
  purposeIds,
3352
3151
  type,
3353
- event
3152
+ context: typedContext
3354
3153
  });
3355
3154
  }
3356
- const latestPolicy = await registry.findOrCreatePolicy(type);
3357
- if (!latestPolicy) return {
3358
- isValid: false,
3359
- reasons: [
3360
- 'Failed to find or create latest policy'
3361
- ]
3362
- };
3363
- return await policyConsentGiven({
3155
+ const latestPolicy = await typedContext.registry.findOrCreatePolicy(type);
3156
+ if (!latestPolicy) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_NOT_FOUND', {
3157
+ data: {
3158
+ policyId: 'latest',
3159
+ type
3160
+ }
3161
+ });
3162
+ return await checkPolicyConsent({
3364
3163
  policyId: latestPolicy.id,
3365
3164
  subjectId: subject.id,
3366
3165
  domainId: domainRecord.id,
3367
3166
  purposeIds,
3368
3167
  type,
3369
- event
3168
+ context: typedContext
3169
+ });
3170
+ } catch (error) {
3171
+ logger.error('Error in verify-consent handler', {
3172
+ error: error instanceof Error ? error.message : String(error),
3173
+ errorType: error instanceof Error ? error.constructor.name : typeof error
3174
+ });
3175
+ if (error instanceof __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError) throw error;
3176
+ throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('INTERNAL_SERVER_ERROR', {
3177
+ message: error instanceof Error ? error.message : String(error)
3370
3178
  });
3371
3179
  }
3372
3180
  });
3373
- async function policyConsentGiven({ policyId, subjectId, domainId, purposeIds, type, event }) {
3374
- const { registry, adapter } = event.context;
3181
+ async function checkPolicyConsent({ policyId, subjectId, domainId, purposeIds, type, context }) {
3182
+ const { registry, adapter } = context;
3375
3183
  const rawConsents = await adapter.findMany({
3376
3184
  model: 'consent',
3377
3185
  where: [
@@ -3393,13 +3201,12 @@ async function policyConsentGiven({ policyId, subjectId, domainId, purposeIds, t
3393
3201
  direction: 'desc'
3394
3202
  }
3395
3203
  });
3396
- const consents = rawConsents.map((consent)=>validateEntityOutput('consent', consent, {}));
3397
- const filteredConsents = consents.filter((consent)=>{
3204
+ const filteredConsents = rawConsents.filter((consent)=>{
3398
3205
  if (!purposeIds) return true;
3399
3206
  return purposeIds.every((id)=>consent.purposeIds.some((purposeId)=>purposeId === id));
3400
3207
  });
3401
3208
  await registry.createAuditLog({
3402
- subjectId: subjectId,
3209
+ subjectId,
3403
3210
  entityType: 'consent_policy',
3404
3211
  entityId: policyId,
3405
3212
  actionType: 'verify_consent',
@@ -3408,260 +3215,325 @@ async function policyConsentGiven({ policyId, subjectId, domainId, purposeIds, t
3408
3215
  policyId,
3409
3216
  purposeIds,
3410
3217
  success: 0 !== filteredConsents.length,
3411
- consentId: filteredConsents[0]?.id
3218
+ ...filteredConsents.length > 0 ? {
3219
+ consentId: filteredConsents[0]?.id
3220
+ } : {}
3221
+ }
3222
+ });
3223
+ if (0 === rawConsents.length) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('NO_CONSENT_FOUND', {
3224
+ data: {
3225
+ policyId,
3226
+ subjectId,
3227
+ domainId
3228
+ }
3229
+ });
3230
+ if (0 === filteredConsents.length) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('NO_CONSENT_FOUND', {
3231
+ data: {
3232
+ policyId,
3233
+ subjectId,
3234
+ domainId
3412
3235
  }
3413
3236
  });
3414
- if (0 === consents.length) return {
3415
- isValid: false,
3416
- reasons: [
3417
- 'No consent found for the given policy'
3418
- ]
3419
- };
3420
3237
  return {
3421
3238
  isValid: true,
3422
3239
  consent: filteredConsents[0]
3423
3240
  };
3424
3241
  }
3425
- const routes = [
3426
- status_status,
3427
- show_consent_banner_showConsentBanner,
3428
- setConsent,
3429
- verifyConsent
3430
- ];
3431
- const API_ROUTER_TRACER_NAME = '@doubletie/api-router';
3432
- const api_router_telemetry_getTracer = (options)=>{
3433
- if (options?.telemetry?.tracer) return options.telemetry.tracer;
3434
- return __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.trace.getTracer(API_ROUTER_TRACER_NAME);
3242
+ const consentHandlers = {
3243
+ post: postConsent,
3244
+ showBanner: show_banner_handler_showConsentBanner,
3245
+ verify: verifyConsent
3435
3246
  };
3436
- const createRequestSpan = (method, path, options)=>{
3437
- if (options?.telemetry?.disabled) return null;
3438
- const tracer = api_router_telemetry_getTracer(options);
3439
- const span = tracer.startSpan(`${method} ${path}`, {
3440
- attributes: {
3441
- 'http.method': method,
3442
- 'http.path': path,
3443
- ...options?.telemetry?.defaultAttributes || {}
3247
+ const statusHandler = os.meta.status.handler(({ context })=>{
3248
+ const typedContext = context;
3249
+ const headers = typedContext.headers;
3250
+ const normalizeHeader = (value)=>{
3251
+ if (!value) return null;
3252
+ return Array.isArray(value) ? value[0] ?? null : value;
3253
+ };
3254
+ const countryCode = normalizeHeader(headers?.get('cf-ipcountry')) ?? normalizeHeader(headers?.get('x-vercel-ip-country')) ?? normalizeHeader(headers?.get('x-amz-cf-ipcountry')) ?? normalizeHeader(headers?.get('x-country-code'));
3255
+ const regionCode = normalizeHeader(headers?.get('x-vercel-ip-country-region')) ?? normalizeHeader(headers?.get('x-region-code'));
3256
+ return {
3257
+ status: 'ok',
3258
+ version: package_namespaceObject.i8,
3259
+ timestamp: new Date(),
3260
+ storage: {
3261
+ type: typedContext.adapter?.id ?? 'MemoryAdapter',
3262
+ available: !!typedContext.adapter
3263
+ },
3264
+ client: {
3265
+ ip: typedContext.ipAddress ?? null,
3266
+ userAgent: typedContext.userAgent ?? null,
3267
+ region: {
3268
+ countryCode,
3269
+ regionCode
3270
+ }
3444
3271
  }
3445
- });
3446
- return span;
3447
- };
3448
- const withRequestSpan = async (method, path, operation, options)=>{
3449
- const span = createRequestSpan(method, path, options);
3450
- if (!span) return operation();
3451
- try {
3452
- const result = await operation();
3453
- span.setStatus({
3454
- code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK
3455
- });
3456
- return result;
3457
- } catch (error) {
3458
- handleSpanError(span, error);
3459
- throw error;
3460
- } finally{
3461
- span.end();
3462
- }
3272
+ };
3273
+ });
3274
+ const metaHandlers = {
3275
+ status: statusHandler
3463
3276
  };
3464
- const handleSpanError = (span, error)=>{
3465
- span.setStatus({
3466
- code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.ERROR,
3467
- message: error instanceof Error ? error.message : String(error)
3277
+ const router = os.router({
3278
+ consent: consentHandlers,
3279
+ meta: metaHandlers
3280
+ });
3281
+ const c15tInstance = (options)=>{
3282
+ const contextPromise = init(options);
3283
+ const corsOptions = options.trustedOrigins ? {
3284
+ origin: options.trustedOrigins.includes('*') ? '*' : options.trustedOrigins,
3285
+ credentials: true,
3286
+ methods: [
3287
+ 'GET',
3288
+ 'POST',
3289
+ 'PUT',
3290
+ 'DELETE',
3291
+ 'OPTIONS',
3292
+ 'PATCH'
3293
+ ],
3294
+ allowedHeaders: [
3295
+ 'Content-Type',
3296
+ 'Authorization',
3297
+ 'X-Request-ID'
3298
+ ],
3299
+ maxAge: 86400
3300
+ } : {
3301
+ origin: '*',
3302
+ credentials: false,
3303
+ methods: [
3304
+ 'GET',
3305
+ 'POST',
3306
+ 'PUT',
3307
+ 'DELETE',
3308
+ 'OPTIONS',
3309
+ 'PATCH'
3310
+ ],
3311
+ allowedHeaders: [
3312
+ 'Content-Type',
3313
+ 'Authorization',
3314
+ 'X-Request-ID'
3315
+ ],
3316
+ maxAge: 86400
3317
+ };
3318
+ const rpcHandler = new __WEBPACK_EXTERNAL_MODULE__orpc_openapi_fetch_89b49e61__.OpenAPIHandler(router, {
3319
+ plugins: [
3320
+ new __WEBPACK_EXTERNAL_MODULE__orpc_server_plugins_e445fd4f__.CORSPlugin(corsOptions)
3321
+ ]
3468
3322
  });
3469
- if (error instanceof Error) {
3470
- span.setAttribute('error.type', error.name);
3471
- span.setAttribute('error.message', error.message);
3472
- if (error.stack) span.setAttribute('error.stack', error.stack);
3473
- }
3474
- };
3475
- const STRIP_REGEX = /^(https?:\/\/)|(wss?:\/\/)|(\/+$)|:\d+/g;
3476
- function isOriginTrusted(origin, trustedDomains, logger) {
3477
- try {
3478
- if (0 === trustedDomains.length) throw new Error('No trusted domains');
3479
- logger?.debug(`Checking if origin ${origin} is trusted in ${trustedDomains}`);
3480
- if (trustedDomains.includes('*')) {
3481
- logger?.debug('Allowing all origins');
3482
- return true;
3483
- }
3484
- const url = new URL(origin);
3485
- const originHostname = url.hostname.toLowerCase();
3486
- logger?.debug(`Parsed origin hostname: ${originHostname}`);
3487
- return trustedDomains.some((domain)=>{
3488
- if (!domain || '' === domain.trim()) {
3489
- logger?.debug('Skipping empty domain');
3490
- return false;
3323
+ const openAPIGenerator = new __WEBPACK_EXTERNAL_MODULE__orpc_openapi_a95cc8e7__.OpenAPIGenerator({
3324
+ schemaConverters: [
3325
+ new __WEBPACK_EXTERNAL_MODULE__orpc_zod_716a28d4__.ZodToJsonSchemaConverter()
3326
+ ]
3327
+ });
3328
+ const openApiConfig = {
3329
+ enabled: true,
3330
+ specPath: '/spec.json',
3331
+ docsPath: '/docs',
3332
+ ...options.openapi || {}
3333
+ };
3334
+ const defaultOpenApiOptions = {
3335
+ info: {
3336
+ title: options.appName || 'c15t API',
3337
+ version: package_namespaceObject.i8,
3338
+ description: 'API for consent management'
3339
+ },
3340
+ servers: [
3341
+ {
3342
+ url: '/'
3491
3343
  }
3492
- const strippedDomain = domain.replace(STRIP_REGEX, '').toLowerCase();
3493
- logger?.debug(`Checking against stripped domain: ${strippedDomain}`);
3494
- if (strippedDomain.startsWith('*.')) {
3495
- const wildcardDomain = strippedDomain.slice(2);
3496
- const parts = originHostname.split('.');
3497
- const isValid = parts.length > 2 && originHostname.endsWith(wildcardDomain);
3498
- logger?.debug(`Wildcard match result: ${isValid} ${originHostname} ends with ${wildcardDomain} ${parts.length > 2} ${originHostname.endsWith(wildcardDomain)}`);
3499
- return isValid;
3344
+ ],
3345
+ security: [
3346
+ {
3347
+ bearerAuth: []
3500
3348
  }
3501
- const isMatch = originHostname === strippedDomain;
3502
- logger?.debug(`Exact match result: ${isMatch} ${originHostname} === ${strippedDomain}`);
3503
- return isMatch;
3504
- });
3505
- } catch (error) {
3506
- logger?.error('Error validating origin:', error);
3507
- return false;
3508
- }
3509
- }
3510
- const DEFAULT_IP_HEADERS = [
3511
- 'x-client-ip',
3512
- 'x-forwarded-for',
3513
- 'cf-connecting-ip',
3514
- 'fastly-client-ip',
3515
- 'x-real-ip',
3516
- 'x-cluster-client-ip',
3517
- 'x-forwarded',
3518
- 'forwarded-for',
3519
- 'forwarded'
3520
- ];
3521
- function getIp(req, options) {
3522
- const advanced = options.advanced || {};
3523
- if (advanced?.ipAddress?.disableIpTracking) return null;
3524
- const testIP = '127.0.0.1';
3525
- if (isTest) return testIP;
3526
- const ipHeaders = advanced?.ipAddress?.ipAddressHeaders || DEFAULT_IP_HEADERS;
3527
- const headers = req instanceof Request ? req.headers : req;
3528
- for (const key of ipHeaders){
3529
- const value = headers.get(key);
3530
- if (value) {
3531
- const ip = value.split(',')[0]?.trim();
3532
- if (ip) return ip;
3349
+ ]
3350
+ };
3351
+ const processIp = (request, context)=>{
3352
+ const ip = getIp(request, options);
3353
+ if (ip) context.ipAddress = ip;
3354
+ return context;
3355
+ };
3356
+ const processCors = (request, context)=>{
3357
+ const origin = request.headers.get('origin');
3358
+ if (origin && options.trustedOrigins) {
3359
+ const trusted = isOriginTrusted(origin, options.trustedOrigins, context.logger);
3360
+ context.origin = origin;
3361
+ context.trustedOrigin = trusted;
3533
3362
  }
3534
- }
3535
- return null;
3536
- }
3537
- function createApiHandler({ options, context }) {
3538
- const { logger } = context;
3539
- logger.info('Creating API Handler');
3540
- const app = (0, __WEBPACK_EXTERNAL_MODULE_h3__.createApp)({
3541
- onRequest (event) {
3542
- event.context.ipAddress = getIp(event.headers, options);
3543
- event.context.userAgent = event.node.req.headers['user-agent'] || null;
3544
- event.context.registry = context.registry;
3545
- event.context.adapter = context.adapter;
3546
- event.context.trustedOrigins = context.trustedOrigins;
3547
- event.context.logger = logger;
3548
- logger.debug(`Request received: ${event.method} ${event.path}`);
3549
- },
3550
- onError (error, event) {
3551
- if (event.context._onError && 'function' == typeof event.context._onError) return event.context._onError(error);
3552
- logger.error(`Unhandled API error in ${event.method} ${event.path}`, {
3553
- error: error instanceof Error ? error.message : String(error),
3554
- errorType: error instanceof Error ? error.constructor.name : typeof error
3555
- });
3363
+ return context;
3364
+ };
3365
+ const processTelemetry = (request, context)=>{
3366
+ const url = new URL(request.url);
3367
+ const path = url.pathname;
3368
+ const method = request.method;
3369
+ withRequestSpan(method, path, async ()=>{}, options);
3370
+ context.path = path;
3371
+ context.method = method;
3372
+ context.headers = request.headers;
3373
+ context.userAgent = request.headers.get('user-agent') || void 0;
3374
+ return context;
3375
+ };
3376
+ const getOpenAPISpec = async ()=>{
3377
+ if (getOpenAPISpec.cached) return getOpenAPISpec.cached;
3378
+ const mergedOptions = {
3379
+ ...defaultOpenApiOptions
3380
+ };
3381
+ if (openApiConfig.options) {
3382
+ const userOptions = openApiConfig.options;
3383
+ if (userOptions.info) mergedOptions.info = {
3384
+ ...defaultOpenApiOptions.info,
3385
+ ...userOptions.info
3386
+ };
3387
+ for (const [key, value] of Object.entries(userOptions))if ('info' !== key) mergedOptions[key] = value;
3556
3388
  }
3557
- });
3558
- app.use(createH3ErrorHandler());
3559
- logger.debug('Added error handler middleware');
3560
- app.use((0, __WEBPACK_EXTERNAL_MODULE_h3__.eventHandler)((event)=>{
3561
- if ((0, __WEBPACK_EXTERNAL_MODULE_h3__.handleCors)(event, {
3562
- origin: (originStr)=>isOriginTrusted(originStr, event.context.trustedOrigins, logger),
3563
- methods: [
3564
- 'GET',
3565
- 'POST',
3566
- 'PUT',
3567
- 'DELETE',
3568
- 'PATCH',
3569
- 'OPTIONS'
3570
- ],
3571
- allowHeaders: [
3572
- 'Content-Type',
3573
- 'Authorization'
3574
- ],
3575
- credentials: true,
3576
- maxAge: '600'
3577
- })) return void logger.debug('CORS preflight response sent');
3578
- }));
3579
- const router = (0, __WEBPACK_EXTERNAL_MODULE_h3__.createRouter)();
3580
- app.use(router);
3581
- logger.debug('Router initialized and registered with app');
3582
- for (const route of routes){
3583
- logger.debug(`Registering route: ${route.method} ${route.path}`);
3584
- router[route.method](route.path, withH3ErrorHandling((0, __WEBPACK_EXTERNAL_MODULE_h3__.eventHandler)(async (event)=>{
3585
- logger.debug(`Handling request: ${route.method} ${route.path}`);
3586
- try {
3587
- logger.debug(`Executing handler for ${route.path}`);
3588
- const result = await withRequestSpan(event.method.toUpperCase(), route.path, ()=>route.handler(event), options);
3589
- logger.debug(`Handler completed for ${route.path}`);
3590
- if ('object' == typeof result && null !== result && 'pipe' in result && 'function' == typeof result.pipe) {
3591
- logger.debug(`Sending stream response for ${route.path}`);
3592
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendStream)(event, result);
3389
+ const spec = await openAPIGenerator.generate(router, mergedOptions);
3390
+ getOpenAPISpec.cached = spec;
3391
+ return spec;
3392
+ };
3393
+ const getDocsUI = ()=>{
3394
+ if (openApiConfig.customUiTemplate) return openApiConfig.customUiTemplate;
3395
+ return `
3396
+ <!doctype html>
3397
+ <html>
3398
+ <head>
3399
+ <title>${options.appName || 'c15t API'} Documentation</title>
3400
+ <meta charset="utf-8" />
3401
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
3402
+ <link rel="icon" type="image/svg+xml" href="https://orpc.unnoq.com/icon.svg" />
3403
+ </head>
3404
+ <body>
3405
+ <script
3406
+ id="api-reference"
3407
+ data-url="${encodeURI(openApiConfig.specPath)}">
3408
+ </script>
3409
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
3410
+ </body>
3411
+ </html>
3412
+ `;
3413
+ };
3414
+ const handleOpenApiSpecRequest = async (url)=>{
3415
+ if (openApiConfig.enabled && url.pathname === openApiConfig.specPath) {
3416
+ const spec = await getOpenAPISpec();
3417
+ return new Response(JSON.stringify(spec), {
3418
+ status: 200,
3419
+ headers: {
3420
+ 'Content-Type': 'application/json'
3593
3421
  }
3594
- event.node.res.setHeader('Content-Type', 'application/json');
3595
- return result;
3596
- } catch (error) {
3597
- logger.error(`Error in route handler for ${route.path}`, {
3598
- error: error instanceof Error ? error.message : String(error),
3599
- errorType: error instanceof Error ? error.constructor.name : typeof error
3600
- });
3601
- throw error;
3602
- }
3603
- })));
3604
- }
3605
- const handler = (0, __WEBPACK_EXTERNAL_MODULE_h3__.toWebHandler)(app);
3606
- logger.info('API handler created successfully');
3607
- return {
3608
- handler
3422
+ });
3423
+ }
3424
+ return null;
3609
3425
  };
3610
- }
3611
- const c15tInstance = (options)=>{
3612
- const contextPromise = init(options);
3613
- let webHandler = null;
3614
- const getHandler = async (ctx)=>{
3615
- if (!webHandler) {
3616
- const { handler } = createApiHandler({
3617
- options: ctx.options,
3618
- context: {
3619
- adapter: ctx.adapter,
3620
- registry: ctx.registry,
3621
- trustedOrigins: ctx.trustedOrigins,
3622
- logger: ctx.logger
3426
+ const handleDocsUiRequest = (url)=>{
3427
+ if (openApiConfig.enabled && url.pathname === openApiConfig.docsPath) {
3428
+ const html = getDocsUI();
3429
+ return new Response(html, {
3430
+ status: 200,
3431
+ headers: {
3432
+ 'Content-Type': 'text/html',
3433
+ 'Content-Security-Policy': "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;"
3623
3434
  }
3624
3435
  });
3625
- webHandler = handler;
3626
3436
  }
3627
- return webHandler;
3437
+ return null;
3438
+ };
3439
+ const createDoubleTieErrorResponse = (error)=>{
3440
+ const sanitizedMessage = error.message.replace(/[^\w\s.,;:!?()[\]{}'"+-]/g, '');
3441
+ return new Response(JSON.stringify({
3442
+ code: error.code,
3443
+ message: sanitizedMessage,
3444
+ data: error.meta,
3445
+ status: error.statusCode,
3446
+ defined: true
3447
+ }), {
3448
+ status: error.statusCode,
3449
+ headers: {
3450
+ 'Content-Type': 'application/json'
3451
+ }
3452
+ });
3453
+ };
3454
+ const createUnknownErrorResponse = (error)=>{
3455
+ const message = error instanceof Error ? error.message : String(error);
3456
+ let status = 500;
3457
+ if (error instanceof Error && 'status' in error) {
3458
+ const statusValue = error.status;
3459
+ if ('number' == typeof statusValue && statusValue >= 100 && statusValue < 600) status = statusValue;
3460
+ }
3461
+ return new Response(JSON.stringify({
3462
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
3463
+ message,
3464
+ status,
3465
+ defined: true,
3466
+ data: {}
3467
+ }), {
3468
+ status,
3469
+ headers: {
3470
+ 'Content-Type': 'application/json'
3471
+ }
3472
+ });
3473
+ };
3474
+ const handleApiRequest = async (request, ctx)=>{
3475
+ const orpcContext = {
3476
+ adapter: ctx.adapter,
3477
+ registry: ctx.registry,
3478
+ logger: ctx.logger,
3479
+ generateId: ctx.generateId,
3480
+ headers: request.headers,
3481
+ userAgent: request.headers.get('user-agent') || void 0
3482
+ };
3483
+ processIp(request, orpcContext);
3484
+ processCors(request, orpcContext);
3485
+ processTelemetry(request, orpcContext);
3486
+ const handlerContext = orpcContext;
3487
+ const { matched, response } = await rpcHandler.handle(request, {
3488
+ prefix: '/',
3489
+ context: handlerContext
3490
+ });
3491
+ if (matched && response) return response;
3492
+ return new Response('Not Found', {
3493
+ status: 404
3494
+ });
3628
3495
  };
3629
3496
  const handler = async (request)=>{
3630
3497
  try {
3631
- const contextResult = await contextPromise;
3632
- return contextResult.match(async (ctx)=>{
3633
- try {
3634
- const handler = await getHandler(ctx);
3635
- const response = await handler(request);
3636
- return (0, __WEBPACK_EXTERNAL_MODULE_neverthrow__.okAsync)(response);
3637
- } catch (error) {
3638
- return failAsync('Request handling failed', {
3639
- code: error_codes_ERROR_CODES.REQUEST_HANDLER_ERROR,
3640
- cause: error instanceof Error ? error : void 0
3641
- });
3642
- }
3643
- }, (error)=>failAsync(`Context initialization failed: ${error.message}`, {
3644
- code: error_codes_ERROR_CODES.INITIALIZATION_FAILED,
3645
- cause: error
3646
- }));
3498
+ const url = new URL(request.url);
3499
+ const openApiResponse = await handleOpenApiSpecRequest(url);
3500
+ if (openApiResponse) return openApiResponse;
3501
+ const docsResponse = handleDocsUiRequest(url);
3502
+ if (docsResponse) return docsResponse;
3503
+ const ctxResult = await contextPromise;
3504
+ if (!ctxResult.isOk()) throw ctxResult.error;
3505
+ const ctx = ctxResult.value;
3506
+ return await handleApiRequest(request, ctx);
3647
3507
  } catch (error) {
3648
- return failAsync(`Unexpected error: ${error instanceof Error ? error.message : String(error)}`, {
3649
- code: error_codes_ERROR_CODES.UNKNOWN_ERROR,
3650
- cause: error instanceof Error ? error : void 0
3651
- });
3508
+ const logger = options.logger ? (0, __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__.createLogger)(options.logger) : console;
3509
+ logger.error('Request handling error:', error);
3510
+ if (error instanceof error_class_DoubleTieError) return createDoubleTieErrorResponse(error);
3511
+ return createUnknownErrorResponse(error);
3652
3512
  }
3653
3513
  };
3514
+ const createNextHandlers = ()=>{
3515
+ const nextHandler = async (request)=>await handler(request);
3516
+ return {
3517
+ GET: nextHandler,
3518
+ POST: nextHandler,
3519
+ PUT: nextHandler,
3520
+ PATCH: nextHandler,
3521
+ DELETE: nextHandler,
3522
+ OPTIONS: nextHandler,
3523
+ HEAD: nextHandler
3524
+ };
3525
+ };
3654
3526
  return {
3655
- handler,
3656
- getApi: async ()=>{
3657
- const contextResult = await contextPromise;
3658
- return contextResult.match(()=>(0, __WEBPACK_EXTERNAL_MODULE_neverthrow__.okAsync)(routes), (error)=>failAsync(`API retrieval failed: ${error.message}`, {
3659
- code: error_codes_ERROR_CODES.API_RETRIEVAL_ERROR,
3660
- cause: error
3661
- }));
3662
- },
3663
3527
  options,
3664
- $context: contextPromise
3528
+ $context: contextPromise.then((result)=>{
3529
+ if (!result.isOk()) throw result.error;
3530
+ return result.value;
3531
+ }),
3532
+ router: router,
3533
+ handler,
3534
+ ...createNextHandlers(),
3535
+ getOpenAPISpec,
3536
+ getDocsUI
3665
3537
  };
3666
3538
  };
3667
- export { pkgs_types_namespaceObject as Types, c15tInstance };
3539
+ export { c15tInstance };