@donotdev/functions 0.0.19 → 0.1.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 (292) hide show
  1. package/LICENSE.md +3 -3
  2. package/lib/firebase/auth/getCustomClaims.d.ts +25 -0
  3. package/lib/firebase/auth/getUserAuthStatus.d.ts +29 -0
  4. package/lib/firebase/auth/index.d.ts +12 -0
  5. package/lib/firebase/auth/removeCustomClaims.d.ts +28 -0
  6. package/lib/firebase/auth/setCustomClaims.d.ts +34 -0
  7. package/lib/firebase/baseFunction.d.ts +26 -0
  8. package/lib/firebase/billing/cancelSubscription.d.ts +10 -0
  9. package/lib/firebase/billing/changePlan.d.ts +13 -0
  10. package/lib/firebase/billing/createCheckoutSession.d.ts +21 -0
  11. package/lib/firebase/billing/createCustomerPortal.d.ts +19 -0
  12. package/lib/firebase/billing/healthCheck.d.ts +5 -0
  13. package/lib/firebase/billing/index.d.ts +18 -0
  14. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +19 -0
  15. package/lib/firebase/billing/webhookHandler.d.ts +6 -0
  16. package/lib/firebase/config/constants.d.ts +89 -0
  17. package/lib/firebase/config/index.d.ts +9 -0
  18. package/lib/firebase/config/secrets.d.ts +15 -0
  19. package/lib/firebase/crud/aggregate.d.ts +98 -0
  20. package/lib/firebase/crud/create.d.ts +16 -0
  21. package/lib/firebase/crud/delete.d.ts +20 -0
  22. package/lib/firebase/crud/get.d.ts +24 -0
  23. package/lib/firebase/crud/index.d.ts +14 -0
  24. package/lib/firebase/crud/list.d.ts +25 -0
  25. package/lib/firebase/crud/update.d.ts +25 -0
  26. package/lib/firebase/helpers/githubAccessHelper.d.ts +30 -0
  27. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +36 -0
  28. package/lib/firebase/helpers/index.d.ts +10 -0
  29. package/lib/firebase/index.d.ts +17 -0
  30. package/lib/firebase/index.js +25 -9110
  31. package/lib/firebase/index.js.map +4 -4
  32. package/lib/firebase/oauth/disconnect.d.ts +12 -0
  33. package/lib/firebase/oauth/exchangeToken.d.ts +9 -0
  34. package/lib/firebase/oauth/getConnections.d.ts +11 -0
  35. package/lib/firebase/oauth/githubAccess.d.ts +83 -0
  36. package/lib/firebase/oauth/index.d.ts +13 -0
  37. package/lib/firebase/oauth/refreshToken.d.ts +9 -0
  38. package/lib/firebase/registerCrudFunctions.d.ts +32 -0
  39. package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +14 -0
  40. package/lib/firebase/scheduled/index.d.ts +9 -0
  41. package/lib/shared/billing/createCheckout.d.ts +50 -0
  42. package/lib/shared/billing/helpers/index.d.ts +10 -0
  43. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +34 -0
  44. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +45 -0
  45. package/lib/shared/billing/idempotency.d.ts +22 -0
  46. package/lib/shared/billing/index.d.ts +11 -0
  47. package/lib/shared/billing/webhookHandler.d.ts +37 -0
  48. package/lib/shared/errorHandling.d.ts +14 -0
  49. package/lib/shared/firebase.d.ts +73 -0
  50. package/lib/shared/github.d.ts +128 -0
  51. package/lib/shared/index.d.ts +16 -0
  52. package/lib/shared/index.js +25 -6927
  53. package/lib/shared/index.js.map +4 -4
  54. package/lib/shared/logger.d.ts +133 -0
  55. package/lib/shared/metadata.d.ts +36 -0
  56. package/lib/shared/oauth/exchangeToken.d.ts +24 -0
  57. package/lib/shared/oauth/grantAccess.d.ts +30 -0
  58. package/lib/shared/oauth/index.d.ts +10 -0
  59. package/lib/shared/schema.d.ts +56 -0
  60. package/lib/shared/utils/detectFirestore.d.ts +31 -0
  61. package/lib/shared/utils/external/date.d.ts +36 -0
  62. package/lib/shared/utils/external/index.d.ts +11 -0
  63. package/lib/shared/utils/external/references.d.ts +12 -0
  64. package/lib/shared/utils/external/subscription.d.ts +41 -0
  65. package/lib/shared/utils/firebaseHelpers.d.ts +23 -0
  66. package/lib/shared/utils/functionWrapper.d.ts +36 -0
  67. package/lib/shared/utils/index.d.ts +14 -0
  68. package/lib/shared/utils/internal/auth.d.ts +57 -0
  69. package/lib/shared/utils/internal/firebase.d.ts +5 -0
  70. package/lib/shared/utils/internal/idempotency.d.ts +21 -0
  71. package/lib/shared/utils/internal/index.d.ts +14 -0
  72. package/lib/shared/utils/internal/monitoring.d.ts +80 -0
  73. package/lib/shared/utils/internal/rateLimiter.d.ts +82 -0
  74. package/lib/shared/utils/internal/validation.d.ts +43 -0
  75. package/lib/shared/utils/schemaValidation.d.ts +60 -0
  76. package/lib/shared/utils/validation.d.ts +98 -0
  77. package/lib/shared/utils/vercelHelpers.d.ts +18 -0
  78. package/lib/shared/utils.d.ts +234 -0
  79. package/lib/shared/validation.d.ts +16 -0
  80. package/lib/supabase/auth/deleteAccount.d.ts +16 -0
  81. package/lib/supabase/auth/getCustomClaims.d.ts +16 -0
  82. package/lib/supabase/auth/getUserAuthStatus.d.ts +18 -0
  83. package/lib/supabase/auth/removeCustomClaims.d.ts +16 -0
  84. package/lib/supabase/auth/setCustomClaims.d.ts +18 -0
  85. package/lib/supabase/baseFunction.d.ts +43 -0
  86. package/lib/supabase/billing/cancelSubscription.d.ts +9 -0
  87. package/lib/supabase/billing/changePlan.d.ts +11 -0
  88. package/lib/supabase/billing/createCheckoutSession.d.ts +11 -0
  89. package/lib/supabase/billing/createCustomerPortal.d.ts +9 -0
  90. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +9 -0
  91. package/lib/supabase/crud/aggregate.d.ts +27 -0
  92. package/lib/supabase/crud/create.d.ts +23 -0
  93. package/lib/supabase/crud/delete.d.ts +30 -0
  94. package/lib/supabase/crud/get.d.ts +23 -0
  95. package/lib/supabase/crud/index.d.ts +20 -0
  96. package/lib/supabase/crud/list.d.ts +33 -0
  97. package/lib/supabase/crud/update.d.ts +24 -0
  98. package/lib/supabase/helpers/authProvider.d.ts +22 -0
  99. package/lib/supabase/index.d.ts +30 -0
  100. package/lib/supabase/index.js +23 -0
  101. package/lib/supabase/index.js.map +7 -0
  102. package/lib/supabase/oauth/disconnect.d.ts +13 -0
  103. package/lib/supabase/oauth/exchangeToken.d.ts +13 -0
  104. package/lib/supabase/oauth/getConnections.d.ts +13 -0
  105. package/lib/supabase/oauth/index.d.ts +12 -0
  106. package/lib/supabase/oauth/refreshToken.d.ts +13 -0
  107. package/lib/supabase/registerCrudFunctions.d.ts +24 -0
  108. package/lib/supabase/utils/idempotency.d.ts +36 -0
  109. package/lib/supabase/utils/monitoring.d.ts +59 -0
  110. package/lib/supabase/utils/rateLimiter.d.ts +56 -0
  111. package/lib/vercel/api/auth/get-custom-claims.d.ts +2 -0
  112. package/lib/vercel/api/auth/get-user-auth-status.d.ts +2 -0
  113. package/lib/vercel/api/auth/index.d.ts +12 -0
  114. package/lib/vercel/api/auth/remove-custom-claims.d.ts +2 -0
  115. package/lib/vercel/api/auth/set-custom-claims.d.ts +10 -0
  116. package/lib/vercel/api/billing/cancel.d.ts +10 -0
  117. package/lib/vercel/api/billing/change-plan.d.ts +11 -0
  118. package/lib/vercel/api/billing/create-checkout-session.d.ts +13 -0
  119. package/lib/vercel/api/billing/customer-portal.d.ts +3 -0
  120. package/lib/vercel/api/billing/index.d.ts +14 -0
  121. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +31 -0
  122. package/lib/vercel/api/billing/webhook-handler.d.ts +22 -0
  123. package/lib/vercel/api/config/constants.d.ts +103 -0
  124. package/lib/vercel/api/config/firebase-admin.d.ts +19 -0
  125. package/lib/vercel/api/config/index.d.ts +10 -0
  126. package/lib/vercel/api/crud/create.d.ts +2 -0
  127. package/lib/vercel/api/crud/delete.d.ts +2 -0
  128. package/lib/vercel/api/crud/get.d.ts +2 -0
  129. package/lib/vercel/api/crud/index.d.ts +13 -0
  130. package/lib/vercel/api/crud/list.d.ts +2 -0
  131. package/lib/vercel/api/crud/update.d.ts +2 -0
  132. package/lib/vercel/api/index.d.ts +13 -0
  133. package/lib/vercel/api/index.js +22 -4790
  134. package/lib/vercel/api/index.js.map +4 -4
  135. package/lib/vercel/api/oauth/check-github-access.d.ts +12 -0
  136. package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
  137. package/lib/vercel/api/oauth/grant-github-access.d.ts +12 -0
  138. package/lib/vercel/api/oauth/index.d.ts +12 -0
  139. package/lib/vercel/api/oauth/revoke-github-access.d.ts +11 -0
  140. package/lib/vercel/api/utils/cors.d.ts +49 -0
  141. package/lib/vercel/baseFunction.d.ts +25 -0
  142. package/package.json +4 -4
  143. package/src/firebase/auth/getCustomClaims.ts +3 -3
  144. package/src/firebase/auth/getUserAuthStatus.ts +3 -3
  145. package/src/firebase/auth/index.ts +1 -1
  146. package/src/firebase/auth/removeCustomClaims.ts +3 -3
  147. package/src/firebase/auth/setCustomClaims.ts +130 -84
  148. package/src/firebase/baseFunction.ts +2 -2
  149. package/src/firebase/billing/cancelSubscription.ts +3 -3
  150. package/src/firebase/billing/changePlan.ts +3 -3
  151. package/src/firebase/billing/createCheckoutSession.ts +1 -1
  152. package/src/firebase/billing/createCustomerPortal.ts +1 -1
  153. package/src/firebase/billing/healthCheck.ts +8 -24
  154. package/src/firebase/billing/index.d.ts +11 -11
  155. package/src/firebase/billing/index.ts +1 -1
  156. package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -3
  157. package/src/firebase/billing/webhookHandler.ts +1 -2
  158. package/src/firebase/config/constants.ts +4 -4
  159. package/src/firebase/config/index.ts +1 -1
  160. package/src/firebase/config/secrets.ts +1 -1
  161. package/src/firebase/crud/aggregate.ts +2 -2
  162. package/src/firebase/crud/create.ts +19 -4
  163. package/src/firebase/crud/delete.ts +3 -3
  164. package/src/firebase/crud/get.ts +1 -1
  165. package/src/firebase/crud/index.ts +1 -1
  166. package/src/firebase/crud/list.ts +1 -1
  167. package/src/firebase/crud/update.ts +2 -2
  168. package/src/firebase/helpers/githubAccessHelper.ts +4 -4
  169. package/src/firebase/helpers/githubTeamAccessHelper.ts +3 -3
  170. package/src/firebase/helpers/index.ts +1 -1
  171. package/src/firebase/index.d.ts +9 -9
  172. package/src/firebase/index.ts +1 -1
  173. package/src/firebase/oauth/disconnect.ts +2 -2
  174. package/src/firebase/oauth/exchangeToken.ts +7 -7
  175. package/src/firebase/oauth/getConnections.ts +2 -2
  176. package/src/firebase/oauth/githubAccess.ts +10 -10
  177. package/src/firebase/oauth/index.ts +1 -1
  178. package/src/firebase/oauth/refreshToken.ts +2 -2
  179. package/src/firebase/registerCrudFunctions.ts +1 -1
  180. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +1 -1
  181. package/src/firebase/scheduled/index.ts +1 -1
  182. package/src/shared/__tests__/auth.test.ts +46 -0
  183. package/src/shared/__tests__/errorHandling.test.ts +66 -1
  184. package/src/shared/__tests__/firebase.test.ts +293 -0
  185. package/src/shared/__tests__/internalValidation.test.ts +190 -0
  186. package/src/shared/__tests__/metadata.test.ts +66 -0
  187. package/src/shared/__tests__/schema.test.ts +219 -0
  188. package/src/shared/__tests__/schemaValidation.test.ts +72 -0
  189. package/src/shared/__tests__/subscription.test.ts +45 -0
  190. package/src/shared/__tests__/utils.test.ts +281 -0
  191. package/src/shared/__tests__/validation-env.test.ts +73 -0
  192. package/src/shared/billing/__tests__/createCheckout.test.ts +1 -1
  193. package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -1
  194. package/src/shared/billing/createCheckout.ts +10 -5
  195. package/src/shared/billing/helpers/index.ts +1 -1
  196. package/src/shared/billing/helpers/subscriptionManagement.ts +4 -4
  197. package/src/shared/billing/helpers/updateUserSubscription.ts +4 -4
  198. package/src/shared/billing/idempotency.ts +4 -4
  199. package/src/shared/billing/index.ts +1 -1
  200. package/src/shared/billing/webhookHandler.ts +7 -7
  201. package/src/shared/errorHandling.ts +2 -2
  202. package/src/shared/firebase.ts +7 -7
  203. package/src/shared/github.ts +11 -11
  204. package/src/shared/index.d.ts +9 -9
  205. package/src/shared/index.ts +1 -1
  206. package/src/shared/logger.ts +8 -8
  207. package/src/shared/metadata.ts +3 -3
  208. package/src/shared/oauth/__tests__/exchangeToken.test.ts +1 -1
  209. package/src/shared/oauth/exchangeToken.ts +2 -2
  210. package/src/shared/oauth/grantAccess.ts +2 -2
  211. package/src/shared/oauth/index.ts +1 -1
  212. package/src/shared/schema.ts +4 -4
  213. package/src/shared/utils/__tests__/functionWrapper.test.ts +1 -1
  214. package/src/shared/utils/detectFirestore.ts +3 -3
  215. package/src/shared/utils/external/date.ts +5 -5
  216. package/src/shared/utils/external/index.ts +1 -1
  217. package/src/shared/utils/external/references.ts +2 -2
  218. package/src/shared/utils/external/subscription.ts +5 -5
  219. package/src/shared/utils/firebaseHelpers.ts +3 -3
  220. package/src/shared/utils/functionWrapper.ts +4 -4
  221. package/src/shared/utils/index.ts +1 -1
  222. package/src/shared/utils/internal/auth.ts +7 -7
  223. package/src/shared/utils/internal/firebase.ts +1 -1
  224. package/src/shared/utils/internal/idempotency.ts +3 -3
  225. package/src/shared/utils/internal/index.ts +1 -1
  226. package/src/shared/utils/internal/monitoring.ts +8 -8
  227. package/src/shared/utils/internal/rateLimiter.ts +6 -6
  228. package/src/shared/utils/internal/validation.ts +6 -6
  229. package/src/shared/utils/schemaValidation.ts +6 -6
  230. package/src/shared/utils/validation.ts +10 -10
  231. package/src/shared/utils/vercelHelpers.ts +3 -3
  232. package/src/shared/utils.ts +19 -19
  233. package/src/shared/validation.ts +2 -2
  234. package/src/supabase/auth/deleteAccount.ts +2 -2
  235. package/src/supabase/auth/getCustomClaims.ts +2 -2
  236. package/src/supabase/auth/getUserAuthStatus.ts +2 -2
  237. package/src/supabase/auth/removeCustomClaims.ts +2 -2
  238. package/src/supabase/auth/setCustomClaims.ts +2 -2
  239. package/src/supabase/baseFunction.ts +3 -3
  240. package/src/supabase/billing/cancelSubscription.ts +2 -2
  241. package/src/supabase/billing/changePlan.ts +2 -2
  242. package/src/supabase/billing/createCheckoutSession.ts +2 -2
  243. package/src/supabase/billing/createCustomerPortal.ts +2 -2
  244. package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -2
  245. package/src/supabase/crud/aggregate.ts +11 -8
  246. package/src/supabase/crud/create.ts +2 -2
  247. package/src/supabase/crud/delete.ts +1 -1
  248. package/src/supabase/crud/get.ts +2 -2
  249. package/src/supabase/crud/index.ts +1 -1
  250. package/src/supabase/crud/list.ts +2 -2
  251. package/src/supabase/crud/update.ts +2 -2
  252. package/src/supabase/helpers/authProvider.ts +2 -2
  253. package/src/supabase/index.ts +10 -2
  254. package/src/supabase/oauth/disconnect.ts +104 -0
  255. package/src/supabase/oauth/exchangeToken.ts +152 -0
  256. package/src/supabase/oauth/getConnections.ts +85 -0
  257. package/src/supabase/oauth/index.ts +15 -0
  258. package/src/supabase/oauth/refreshToken.ts +131 -0
  259. package/src/supabase/registerCrudFunctions.ts +1 -1
  260. package/src/supabase/utils/idempotency.ts +1 -1
  261. package/src/supabase/utils/monitoring.ts +1 -1
  262. package/src/supabase/utils/rateLimiter.ts +1 -1
  263. package/src/vercel/api/auth/get-custom-claims.ts +1 -1
  264. package/src/vercel/api/auth/get-user-auth-status.ts +1 -1
  265. package/src/vercel/api/auth/index.ts +1 -1
  266. package/src/vercel/api/auth/remove-custom-claims.ts +1 -1
  267. package/src/vercel/api/auth/set-custom-claims.ts +69 -24
  268. package/src/vercel/api/billing/cancel.ts +3 -3
  269. package/src/vercel/api/billing/change-plan.ts +3 -3
  270. package/src/vercel/api/billing/create-checkout-session.ts +3 -3
  271. package/src/vercel/api/billing/customer-portal.ts +1 -1
  272. package/src/vercel/api/billing/index.ts +1 -1
  273. package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
  274. package/src/vercel/api/billing/webhook-handler.ts +3 -3
  275. package/src/vercel/api/config/constants.ts +9 -9
  276. package/src/vercel/api/config/firebase-admin.ts +3 -3
  277. package/src/vercel/api/config/index.ts +1 -1
  278. package/src/vercel/api/crud/create.ts +1 -1
  279. package/src/vercel/api/crud/delete.ts +1 -1
  280. package/src/vercel/api/crud/get.ts +1 -1
  281. package/src/vercel/api/crud/index.ts +1 -1
  282. package/src/vercel/api/crud/list.ts +1 -1
  283. package/src/vercel/api/crud/update.ts +1 -1
  284. package/src/vercel/api/index.d.ts +1 -1
  285. package/src/vercel/api/index.ts +1 -1
  286. package/src/vercel/api/oauth/check-github-access.ts +3 -3
  287. package/src/vercel/api/oauth/exchange-token.ts +1 -1
  288. package/src/vercel/api/oauth/grant-github-access.ts +3 -3
  289. package/src/vercel/api/oauth/index.ts +1 -1
  290. package/src/vercel/api/oauth/revoke-github-access.ts +1 -1
  291. package/src/vercel/api/utils/cors.ts +4 -4
  292. package/src/vercel/baseFunction.ts +2 -2
@@ -1,4791 +1,23 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __name = (target, value) =>
4
- __defProp(target, 'name', { value, configurable: true });
5
- var __esm = (fn, res) =>
6
- function __init() {
7
- return (fn && (res = (0, fn[__getOwnPropNames(fn)[0]])((fn = 0))), res);
8
- };
9
-
10
- // ../core/utils/src/common/arrayTranslations.ts
11
- var init_arrayTranslations = __esm({
12
- '../core/utils/src/common/arrayTranslations.ts'() {
13
- 'use strict';
14
- },
15
- });
16
-
17
- // ../core/utils/src/common/createMetadata.ts
18
- var init_createMetadata = __esm({
19
- '../core/utils/src/common/createMetadata.ts'() {
20
- 'use strict';
21
- },
22
- });
23
-
24
- // ../core/utils/src/common/dateUtils.ts
25
- var init_dateUtils = __esm({
26
- '../core/utils/src/common/dateUtils.ts'() {
27
- 'use strict';
28
- },
29
- });
30
-
31
- // ../core/types/src/auth/constants.ts
32
- var USER_ROLES, SUBSCRIPTION_TIERS, FEATURES, PERMISSIONS;
33
- var init_constants = __esm({
34
- '../core/types/src/auth/constants.ts'() {
35
- 'use strict';
36
- USER_ROLES = {
37
- GUEST: 'guest',
38
- USER: 'user',
39
- ADMIN: 'admin',
40
- SUPER: 'super',
41
- };
42
- SUBSCRIPTION_TIERS = {
43
- FREE: 'free',
44
- PRO: 'pro',
45
- PREMIUM: 'premium',
46
- };
47
- FEATURES = {
48
- BASIC_ACCESS: 'basic_access',
49
- ADVANCED_FEATURES: 'advanced_features',
50
- API_ACCESS: 'api_access',
51
- PRIORITY_SUPPORT: 'priority_support',
52
- };
53
- PERMISSIONS = {
54
- READ_PUBLIC: 'read_public',
55
- READ_OWN_DATA: 'read_own_data',
56
- WRITE_OWN_DATA: 'write_own_data',
57
- READ_ALL_DATA: 'read_all_data',
58
- MANAGE_USERS: 'manage_users',
59
- };
60
- },
61
- });
62
-
63
- // ../../node_modules/.bun/valibot@1.2.0+1fb4c65d43e298b9/node_modules/valibot/dist/index.mjs
64
- // @__NO_SIDE_EFFECTS__
65
- function getGlobalConfig(config$1) {
66
- return {
67
- lang: config$1?.lang ?? store$4?.lang,
68
- message: config$1?.message,
69
- abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
70
- abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly,
71
- };
72
- }
73
- // @__NO_SIDE_EFFECTS__
74
- function getGlobalMessage(lang) {
75
- return store$3?.get(lang);
76
- }
77
- // @__NO_SIDE_EFFECTS__
78
- function getSchemaMessage(lang) {
79
- return store$2?.get(lang);
80
- }
81
- // @__NO_SIDE_EFFECTS__
82
- function getSpecificMessage(reference, lang) {
83
- return store$1?.get(reference)?.get(lang);
84
- }
85
- // @__NO_SIDE_EFFECTS__
86
- function _stringify(input) {
87
- const type = typeof input;
88
- if (type === 'string') return `"${input}"`;
89
- if (type === 'number' || type === 'bigint' || type === 'boolean')
90
- return `${input}`;
91
- if (type === 'object' || type === 'function')
92
- return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? 'null';
93
- return type;
94
- }
95
- function _addIssue(context, label, dataset, config$1, other) {
96
- const input = other && 'input' in other ? other.input : dataset.value;
97
- const expected = other?.expected ?? context.expects ?? null;
98
- const received = other?.received ?? /* @__PURE__ */ _stringify(input);
99
- const issue = {
100
- kind: context.kind,
101
- type: context.type,
102
- input,
103
- expected,
104
- received,
105
- message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : 'R'}eceived ${received}`,
106
- requirement: context.requirement,
107
- path: other?.path,
108
- issues: other?.issues,
109
- lang: config$1.lang,
110
- abortEarly: config$1.abortEarly,
111
- abortPipeEarly: config$1.abortPipeEarly,
112
- };
113
- const isSchema = context.kind === 'schema';
114
- const message$1 =
115
- other?.message ??
116
- context.message ??
117
- /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ??
118
- (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ??
119
- config$1.message ??
120
- /* @__PURE__ */ getGlobalMessage(issue.lang);
121
- if (message$1 !== void 0)
122
- issue.message =
123
- typeof message$1 === 'function' ? message$1(issue) : message$1;
124
- if (isSchema) dataset.typed = false;
125
- if (dataset.issues) dataset.issues.push(issue);
126
- else dataset.issues = [issue];
127
- }
128
- // @__NO_SIDE_EFFECTS__
129
- function _getStandardProps(context) {
130
- return {
131
- version: 1,
132
- vendor: 'valibot',
133
- validate(value$1) {
134
- return context['~run'](
135
- { value: value$1 },
136
- /* @__PURE__ */ getGlobalConfig()
137
- );
138
- },
139
- };
140
- }
141
- // @__NO_SIDE_EFFECTS__
142
- function _isValidObjectKey(object$1, key) {
143
- return (
144
- Object.hasOwn(object$1, key) &&
145
- key !== '__proto__' &&
146
- key !== 'prototype' &&
147
- key !== 'constructor'
148
- );
149
- }
150
- // @__NO_SIDE_EFFECTS__
151
- function _joinExpects(values$1, separator) {
152
- const list = [...new Set(values$1)];
153
- if (list.length > 1) return `(${list.join(` ${separator} `)})`;
154
- return list[0] ?? 'never';
155
- }
156
- // @__NO_SIDE_EFFECTS__
157
- function email(message$1) {
158
- return {
159
- kind: 'validation',
160
- type: 'email',
161
- reference: email,
162
- expects: null,
163
- async: false,
164
- requirement: EMAIL_REGEX,
165
- message: message$1,
166
- '~run'(dataset, config$1) {
167
- if (dataset.typed && !this.requirement.test(dataset.value))
168
- _addIssue(this, 'email', dataset, config$1);
169
- return dataset;
170
- },
171
- };
172
- }
173
- // @__NO_SIDE_EFFECTS__
174
- function isoTimestamp(message$1) {
175
- return {
176
- kind: 'validation',
177
- type: 'iso_timestamp',
178
- reference: isoTimestamp,
179
- async: false,
180
- expects: null,
181
- requirement: ISO_TIMESTAMP_REGEX,
182
- message: message$1,
183
- '~run'(dataset, config$1) {
184
- if (dataset.typed && !this.requirement.test(dataset.value))
185
- _addIssue(this, 'timestamp', dataset, config$1);
186
- return dataset;
187
- },
188
- };
189
- }
190
- // @__NO_SIDE_EFFECTS__
191
- function length(requirement, message$1) {
192
- return {
193
- kind: 'validation',
194
- type: 'length',
195
- reference: length,
196
- async: false,
197
- expects: `${requirement}`,
198
- requirement,
199
- message: message$1,
200
- '~run'(dataset, config$1) {
201
- if (dataset.typed && dataset.value.length !== this.requirement)
202
- _addIssue(this, 'length', dataset, config$1, {
203
- received: `${dataset.value.length}`,
204
- });
205
- return dataset;
206
- },
207
- };
208
- }
209
- // @__NO_SIDE_EFFECTS__
210
- function maxLength(requirement, message$1) {
211
- return {
212
- kind: 'validation',
213
- type: 'max_length',
214
- reference: maxLength,
215
- async: false,
216
- expects: `<=${requirement}`,
217
- requirement,
218
- message: message$1,
219
- '~run'(dataset, config$1) {
220
- if (dataset.typed && dataset.value.length > this.requirement)
221
- _addIssue(this, 'length', dataset, config$1, {
222
- received: `${dataset.value.length}`,
223
- });
224
- return dataset;
225
- },
226
- };
227
- }
228
- // @__NO_SIDE_EFFECTS__
229
- function maxValue(requirement, message$1) {
230
- return {
231
- kind: 'validation',
232
- type: 'max_value',
233
- reference: maxValue,
234
- async: false,
235
- expects: `<=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,
236
- requirement,
237
- message: message$1,
238
- '~run'(dataset, config$1) {
239
- if (dataset.typed && !(dataset.value <= this.requirement))
240
- _addIssue(this, 'value', dataset, config$1, {
241
- received:
242
- dataset.value instanceof Date
243
- ? dataset.value.toJSON()
244
- : /* @__PURE__ */ _stringify(dataset.value),
245
- });
246
- return dataset;
247
- },
248
- };
249
- }
250
- // @__NO_SIDE_EFFECTS__
251
- function minLength(requirement, message$1) {
252
- return {
253
- kind: 'validation',
254
- type: 'min_length',
255
- reference: minLength,
256
- async: false,
257
- expects: `>=${requirement}`,
258
- requirement,
259
- message: message$1,
260
- '~run'(dataset, config$1) {
261
- if (dataset.typed && dataset.value.length < this.requirement)
262
- _addIssue(this, 'length', dataset, config$1, {
263
- received: `${dataset.value.length}`,
264
- });
265
- return dataset;
266
- },
267
- };
268
- }
269
- // @__NO_SIDE_EFFECTS__
270
- function minValue(requirement, message$1) {
271
- return {
272
- kind: 'validation',
273
- type: 'min_value',
274
- reference: minValue,
275
- async: false,
276
- expects: `>=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,
277
- requirement,
278
- message: message$1,
279
- '~run'(dataset, config$1) {
280
- if (dataset.typed && !(dataset.value >= this.requirement))
281
- _addIssue(this, 'value', dataset, config$1, {
282
- received:
283
- dataset.value instanceof Date
284
- ? dataset.value.toJSON()
285
- : /* @__PURE__ */ _stringify(dataset.value),
286
- });
287
- return dataset;
288
- },
289
- };
290
- }
291
- // @__NO_SIDE_EFFECTS__
292
- function regex(requirement, message$1) {
293
- return {
294
- kind: 'validation',
295
- type: 'regex',
296
- reference: regex,
297
- async: false,
298
- expects: `${requirement}`,
299
- requirement,
300
- message: message$1,
301
- '~run'(dataset, config$1) {
302
- if (dataset.typed && !this.requirement.test(dataset.value))
303
- _addIssue(this, 'format', dataset, config$1);
304
- return dataset;
305
- },
306
- };
307
- }
308
- // @__NO_SIDE_EFFECTS__
309
- function url(message$1) {
310
- return {
311
- kind: 'validation',
312
- type: 'url',
313
- reference: url,
314
- async: false,
315
- expects: null,
316
- requirement(input) {
317
- try {
318
- new URL(input);
319
- return true;
320
- } catch {
321
- return false;
322
- }
323
- },
324
- message: message$1,
325
- '~run'(dataset, config$1) {
326
- if (dataset.typed && !this.requirement(dataset.value))
327
- _addIssue(this, 'URL', dataset, config$1);
328
- return dataset;
329
- },
330
- };
331
- }
332
- // @__NO_SIDE_EFFECTS__
333
- function getFallback(schema, dataset, config$1) {
334
- return typeof schema.fallback === 'function'
335
- ? schema.fallback(dataset, config$1)
336
- : schema.fallback;
337
- }
338
- // @__NO_SIDE_EFFECTS__
339
- function getDefault(schema, dataset, config$1) {
340
- return typeof schema.default === 'function'
341
- ? schema.default(dataset, config$1)
342
- : schema.default;
343
- }
344
- // @__NO_SIDE_EFFECTS__
345
- function any() {
346
- return {
347
- kind: 'schema',
348
- type: 'any',
349
- reference: any,
350
- expects: 'any',
351
- async: false,
352
- get '~standard'() {
353
- return /* @__PURE__ */ _getStandardProps(this);
354
- },
355
- '~run'(dataset) {
356
- dataset.typed = true;
357
- return dataset;
358
- },
359
- };
360
- }
361
- // @__NO_SIDE_EFFECTS__
362
- function array(item, message$1) {
363
- return {
364
- kind: 'schema',
365
- type: 'array',
366
- reference: array,
367
- expects: 'Array',
368
- async: false,
369
- item,
370
- message: message$1,
371
- get '~standard'() {
372
- return /* @__PURE__ */ _getStandardProps(this);
373
- },
374
- '~run'(dataset, config$1) {
375
- const input = dataset.value;
376
- if (Array.isArray(input)) {
377
- dataset.typed = true;
378
- dataset.value = [];
379
- for (let key = 0; key < input.length; key++) {
380
- const value$1 = input[key];
381
- const itemDataset = this.item['~run']({ value: value$1 }, config$1);
382
- if (itemDataset.issues) {
383
- const pathItem = {
384
- type: 'array',
385
- origin: 'value',
386
- input,
387
- key,
388
- value: value$1,
389
- };
390
- for (const issue of itemDataset.issues) {
391
- if (issue.path) issue.path.unshift(pathItem);
392
- else issue.path = [pathItem];
393
- dataset.issues?.push(issue);
394
- }
395
- if (!dataset.issues) dataset.issues = itemDataset.issues;
396
- if (config$1.abortEarly) {
397
- dataset.typed = false;
398
- break;
399
- }
400
- }
401
- if (!itemDataset.typed) dataset.typed = false;
402
- dataset.value.push(itemDataset.value);
403
- }
404
- } else _addIssue(this, 'type', dataset, config$1);
405
- return dataset;
406
- },
407
- };
408
- }
409
- // @__NO_SIDE_EFFECTS__
410
- function boolean(message$1) {
411
- return {
412
- kind: 'schema',
413
- type: 'boolean',
414
- reference: boolean,
415
- expects: 'boolean',
416
- async: false,
417
- message: message$1,
418
- get '~standard'() {
419
- return /* @__PURE__ */ _getStandardProps(this);
420
- },
421
- '~run'(dataset, config$1) {
422
- if (typeof dataset.value === 'boolean') dataset.typed = true;
423
- else _addIssue(this, 'type', dataset, config$1);
424
- return dataset;
425
- },
426
- };
427
- }
428
- // @__NO_SIDE_EFFECTS__
429
- function literal(literal_, message$1) {
430
- return {
431
- kind: 'schema',
432
- type: 'literal',
433
- reference: literal,
434
- expects: /* @__PURE__ */ _stringify(literal_),
435
- async: false,
436
- literal: literal_,
437
- message: message$1,
438
- get '~standard'() {
439
- return /* @__PURE__ */ _getStandardProps(this);
440
- },
441
- '~run'(dataset, config$1) {
442
- if (dataset.value === this.literal) dataset.typed = true;
443
- else _addIssue(this, 'type', dataset, config$1);
444
- return dataset;
445
- },
446
- };
447
- }
448
- // @__NO_SIDE_EFFECTS__
449
- function looseObject(entries$1, message$1) {
450
- return {
451
- kind: 'schema',
452
- type: 'loose_object',
453
- reference: looseObject,
454
- expects: 'Object',
455
- async: false,
456
- entries: entries$1,
457
- message: message$1,
458
- get '~standard'() {
459
- return /* @__PURE__ */ _getStandardProps(this);
460
- },
461
- '~run'(dataset, config$1) {
462
- const input = dataset.value;
463
- if (input && typeof input === 'object') {
464
- dataset.typed = true;
465
- dataset.value = {};
466
- for (const key in this.entries) {
467
- const valueSchema = this.entries[key];
468
- if (
469
- key in input ||
470
- ((valueSchema.type === 'exact_optional' ||
471
- valueSchema.type === 'optional' ||
472
- valueSchema.type === 'nullish') &&
473
- valueSchema.default !== void 0)
474
- ) {
475
- const value$1 =
476
- key in input
477
- ? input[key]
478
- : /* @__PURE__ */ getDefault(valueSchema);
479
- const valueDataset = valueSchema['~run'](
480
- { value: value$1 },
481
- config$1
482
- );
483
- if (valueDataset.issues) {
484
- const pathItem = {
485
- type: 'object',
486
- origin: 'value',
487
- input,
488
- key,
489
- value: value$1,
490
- };
491
- for (const issue of valueDataset.issues) {
492
- if (issue.path) issue.path.unshift(pathItem);
493
- else issue.path = [pathItem];
494
- dataset.issues?.push(issue);
495
- }
496
- if (!dataset.issues) dataset.issues = valueDataset.issues;
497
- if (config$1.abortEarly) {
498
- dataset.typed = false;
499
- break;
500
- }
501
- }
502
- if (!valueDataset.typed) dataset.typed = false;
503
- dataset.value[key] = valueDataset.value;
504
- } else if (valueSchema.fallback !== void 0)
505
- dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
506
- else if (
507
- valueSchema.type !== 'exact_optional' &&
508
- valueSchema.type !== 'optional' &&
509
- valueSchema.type !== 'nullish'
510
- ) {
511
- _addIssue(this, 'key', dataset, config$1, {
512
- input: void 0,
513
- expected: `"${key}"`,
514
- path: [
515
- {
516
- type: 'object',
517
- origin: 'key',
518
- input,
519
- key,
520
- value: input[key],
521
- },
522
- ],
523
- });
524
- if (config$1.abortEarly) break;
525
- }
526
- }
527
- if (!dataset.issues || !config$1.abortEarly) {
528
- for (const key in input)
529
- if (
530
- /* @__PURE__ */ _isValidObjectKey(input, key) &&
531
- !(key in this.entries)
532
- )
533
- dataset.value[key] = input[key];
534
- }
535
- } else _addIssue(this, 'type', dataset, config$1);
536
- return dataset;
537
- },
538
- };
539
- }
540
- // @__NO_SIDE_EFFECTS__
541
- function never(message$1) {
542
- return {
543
- kind: 'schema',
544
- type: 'never',
545
- reference: never,
546
- expects: 'never',
547
- async: false,
548
- message: message$1,
549
- get '~standard'() {
550
- return /* @__PURE__ */ _getStandardProps(this);
551
- },
552
- '~run'(dataset, config$1) {
553
- _addIssue(this, 'type', dataset, config$1);
554
- return dataset;
555
- },
556
- };
557
- }
558
- // @__NO_SIDE_EFFECTS__
559
- function nullable(wrapped, default_) {
560
- return {
561
- kind: 'schema',
562
- type: 'nullable',
563
- reference: nullable,
564
- expects: `(${wrapped.expects} | null)`,
565
- async: false,
566
- wrapped,
567
- default: default_,
568
- get '~standard'() {
569
- return /* @__PURE__ */ _getStandardProps(this);
570
- },
571
- '~run'(dataset, config$1) {
572
- if (dataset.value === null) {
573
- if (this.default !== void 0)
574
- dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
575
- if (dataset.value === null) {
576
- dataset.typed = true;
577
- return dataset;
578
- }
579
- }
580
- return this.wrapped['~run'](dataset, config$1);
581
- },
582
- };
583
- }
584
- // @__NO_SIDE_EFFECTS__
585
- function number(message$1) {
586
- return {
587
- kind: 'schema',
588
- type: 'number',
589
- reference: number,
590
- expects: 'number',
591
- async: false,
592
- message: message$1,
593
- get '~standard'() {
594
- return /* @__PURE__ */ _getStandardProps(this);
595
- },
596
- '~run'(dataset, config$1) {
597
- if (typeof dataset.value === 'number' && !isNaN(dataset.value))
598
- dataset.typed = true;
599
- else _addIssue(this, 'type', dataset, config$1);
600
- return dataset;
601
- },
602
- };
603
- }
604
- // @__NO_SIDE_EFFECTS__
605
- function object(entries$1, message$1) {
606
- return {
607
- kind: 'schema',
608
- type: 'object',
609
- reference: object,
610
- expects: 'Object',
611
- async: false,
612
- entries: entries$1,
613
- message: message$1,
614
- get '~standard'() {
615
- return /* @__PURE__ */ _getStandardProps(this);
616
- },
617
- '~run'(dataset, config$1) {
618
- const input = dataset.value;
619
- if (input && typeof input === 'object') {
620
- dataset.typed = true;
621
- dataset.value = {};
622
- for (const key in this.entries) {
623
- const valueSchema = this.entries[key];
624
- if (
625
- key in input ||
626
- ((valueSchema.type === 'exact_optional' ||
627
- valueSchema.type === 'optional' ||
628
- valueSchema.type === 'nullish') &&
629
- valueSchema.default !== void 0)
630
- ) {
631
- const value$1 =
632
- key in input
633
- ? input[key]
634
- : /* @__PURE__ */ getDefault(valueSchema);
635
- const valueDataset = valueSchema['~run'](
636
- { value: value$1 },
637
- config$1
638
- );
639
- if (valueDataset.issues) {
640
- const pathItem = {
641
- type: 'object',
642
- origin: 'value',
643
- input,
644
- key,
645
- value: value$1,
646
- };
647
- for (const issue of valueDataset.issues) {
648
- if (issue.path) issue.path.unshift(pathItem);
649
- else issue.path = [pathItem];
650
- dataset.issues?.push(issue);
651
- }
652
- if (!dataset.issues) dataset.issues = valueDataset.issues;
653
- if (config$1.abortEarly) {
654
- dataset.typed = false;
655
- break;
656
- }
657
- }
658
- if (!valueDataset.typed) dataset.typed = false;
659
- dataset.value[key] = valueDataset.value;
660
- } else if (valueSchema.fallback !== void 0)
661
- dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
662
- else if (
663
- valueSchema.type !== 'exact_optional' &&
664
- valueSchema.type !== 'optional' &&
665
- valueSchema.type !== 'nullish'
666
- ) {
667
- _addIssue(this, 'key', dataset, config$1, {
668
- input: void 0,
669
- expected: `"${key}"`,
670
- path: [
671
- {
672
- type: 'object',
673
- origin: 'key',
674
- input,
675
- key,
676
- value: input[key],
677
- },
678
- ],
679
- });
680
- if (config$1.abortEarly) break;
681
- }
682
- }
683
- } else _addIssue(this, 'type', dataset, config$1);
684
- return dataset;
685
- },
686
- };
687
- }
688
- // @__NO_SIDE_EFFECTS__
689
- function optional(wrapped, default_) {
690
- return {
691
- kind: 'schema',
692
- type: 'optional',
693
- reference: optional,
694
- expects: `(${wrapped.expects} | undefined)`,
695
- async: false,
696
- wrapped,
697
- default: default_,
698
- get '~standard'() {
699
- return /* @__PURE__ */ _getStandardProps(this);
700
- },
701
- '~run'(dataset, config$1) {
702
- if (dataset.value === void 0) {
703
- if (this.default !== void 0)
704
- dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
705
- if (dataset.value === void 0) {
706
- dataset.typed = true;
707
- return dataset;
708
- }
709
- }
710
- return this.wrapped['~run'](dataset, config$1);
711
- },
712
- };
713
- }
714
- // @__NO_SIDE_EFFECTS__
715
- function picklist(options, message$1) {
716
- return {
717
- kind: 'schema',
718
- type: 'picklist',
719
- reference: picklist,
720
- expects: /* @__PURE__ */ _joinExpects(options.map(_stringify), '|'),
721
- async: false,
722
- options,
723
- message: message$1,
724
- get '~standard'() {
725
- return /* @__PURE__ */ _getStandardProps(this);
726
- },
727
- '~run'(dataset, config$1) {
728
- if (this.options.includes(dataset.value)) dataset.typed = true;
729
- else _addIssue(this, 'type', dataset, config$1);
730
- return dataset;
731
- },
732
- };
733
- }
734
- // @__NO_SIDE_EFFECTS__
735
- function record(key, value$1, message$1) {
736
- return {
737
- kind: 'schema',
738
- type: 'record',
739
- reference: record,
740
- expects: 'Object',
741
- async: false,
742
- key,
743
- value: value$1,
744
- message: message$1,
745
- get '~standard'() {
746
- return /* @__PURE__ */ _getStandardProps(this);
747
- },
748
- '~run'(dataset, config$1) {
749
- const input = dataset.value;
750
- if (input && typeof input === 'object') {
751
- dataset.typed = true;
752
- dataset.value = {};
753
- for (const entryKey in input)
754
- if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {
755
- const entryValue = input[entryKey];
756
- const keyDataset = this.key['~run']({ value: entryKey }, config$1);
757
- if (keyDataset.issues) {
758
- const pathItem = {
759
- type: 'object',
760
- origin: 'key',
761
- input,
762
- key: entryKey,
763
- value: entryValue,
764
- };
765
- for (const issue of keyDataset.issues) {
766
- issue.path = [pathItem];
767
- dataset.issues?.push(issue);
768
- }
769
- if (!dataset.issues) dataset.issues = keyDataset.issues;
770
- if (config$1.abortEarly) {
771
- dataset.typed = false;
772
- break;
773
- }
774
- }
775
- const valueDataset = this.value['~run'](
776
- { value: entryValue },
777
- config$1
778
- );
779
- if (valueDataset.issues) {
780
- const pathItem = {
781
- type: 'object',
782
- origin: 'value',
783
- input,
784
- key: entryKey,
785
- value: entryValue,
786
- };
787
- for (const issue of valueDataset.issues) {
788
- if (issue.path) issue.path.unshift(pathItem);
789
- else issue.path = [pathItem];
790
- dataset.issues?.push(issue);
791
- }
792
- if (!dataset.issues) dataset.issues = valueDataset.issues;
793
- if (config$1.abortEarly) {
794
- dataset.typed = false;
795
- break;
796
- }
797
- }
798
- if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;
799
- if (keyDataset.typed)
800
- dataset.value[keyDataset.value] = valueDataset.value;
801
- }
802
- } else _addIssue(this, 'type', dataset, config$1);
803
- return dataset;
804
- },
805
- };
806
- }
807
- // @__NO_SIDE_EFFECTS__
808
- function string(message$1) {
809
- return {
810
- kind: 'schema',
811
- type: 'string',
812
- reference: string,
813
- expects: 'string',
814
- async: false,
815
- message: message$1,
816
- get '~standard'() {
817
- return /* @__PURE__ */ _getStandardProps(this);
818
- },
819
- '~run'(dataset, config$1) {
820
- if (typeof dataset.value === 'string') dataset.typed = true;
821
- else _addIssue(this, 'type', dataset, config$1);
822
- return dataset;
823
- },
824
- };
825
- }
826
- // @__NO_SIDE_EFFECTS__
827
- function _subIssues(datasets) {
828
- let issues;
829
- if (datasets)
830
- for (const dataset of datasets)
831
- if (issues) issues.push(...dataset.issues);
832
- else issues = dataset.issues;
833
- return issues;
834
- }
835
- // @__NO_SIDE_EFFECTS__
836
- function union(options, message$1) {
837
- return {
838
- kind: 'schema',
839
- type: 'union',
840
- reference: union,
841
- expects: /* @__PURE__ */ _joinExpects(
842
- options.map((option) => option.expects),
843
- '|'
844
- ),
845
- async: false,
846
- options,
847
- message: message$1,
848
- get '~standard'() {
849
- return /* @__PURE__ */ _getStandardProps(this);
850
- },
851
- '~run'(dataset, config$1) {
852
- let validDataset;
853
- let typedDatasets;
854
- let untypedDatasets;
855
- for (const schema of this.options) {
856
- const optionDataset = schema['~run'](
857
- { value: dataset.value },
858
- config$1
859
- );
860
- if (optionDataset.typed)
861
- if (optionDataset.issues)
862
- if (typedDatasets) typedDatasets.push(optionDataset);
863
- else typedDatasets = [optionDataset];
864
- else {
865
- validDataset = optionDataset;
866
- break;
867
- }
868
- else if (untypedDatasets) untypedDatasets.push(optionDataset);
869
- else untypedDatasets = [optionDataset];
870
- }
871
- if (validDataset) return validDataset;
872
- if (typedDatasets) {
873
- if (typedDatasets.length === 1) return typedDatasets[0];
874
- _addIssue(this, 'type', dataset, config$1, {
875
- issues: /* @__PURE__ */ _subIssues(typedDatasets),
876
- });
877
- dataset.typed = true;
878
- } else if (untypedDatasets?.length === 1) return untypedDatasets[0];
879
- else
880
- _addIssue(this, 'type', dataset, config$1, {
881
- issues: /* @__PURE__ */ _subIssues(untypedDatasets),
882
- });
883
- return dataset;
884
- },
885
- };
886
- }
887
- // @__NO_SIDE_EFFECTS__
888
- function unknown() {
889
- return {
890
- kind: 'schema',
891
- type: 'unknown',
892
- reference: unknown,
893
- expects: 'unknown',
894
- async: false,
895
- get '~standard'() {
896
- return /* @__PURE__ */ _getStandardProps(this);
897
- },
898
- '~run'(dataset) {
899
- dataset.typed = true;
900
- return dataset;
901
- },
902
- };
903
- }
904
- // @__NO_SIDE_EFFECTS__
905
- function variant(key, options, message$1) {
906
- return {
907
- kind: 'schema',
908
- type: 'variant',
909
- reference: variant,
910
- expects: 'Object',
911
- async: false,
912
- key,
913
- options,
914
- message: message$1,
915
- get '~standard'() {
916
- return /* @__PURE__ */ _getStandardProps(this);
917
- },
918
- '~run'(dataset, config$1) {
919
- const input = dataset.value;
920
- if (input && typeof input === 'object') {
921
- let outputDataset;
922
- let maxDiscriminatorPriority = 0;
923
- let invalidDiscriminatorKey = this.key;
924
- let expectedDiscriminators = [];
925
- const parseOptions = /* @__PURE__ */ __name((variant$1, allKeys) => {
926
- for (const schema of variant$1.options) {
927
- if (schema.type === 'variant')
928
- parseOptions(schema, new Set(allKeys).add(schema.key));
929
- else {
930
- let keysAreValid = true;
931
- let currentPriority = 0;
932
- for (const currentKey of allKeys) {
933
- const discriminatorSchema = schema.entries[currentKey];
934
- if (
935
- currentKey in input
936
- ? discriminatorSchema['~run'](
937
- {
938
- typed: false,
939
- value: input[currentKey],
940
- },
941
- { abortEarly: true }
942
- ).issues
943
- : discriminatorSchema.type !== 'exact_optional' &&
944
- discriminatorSchema.type !== 'optional' &&
945
- discriminatorSchema.type !== 'nullish'
946
- ) {
947
- keysAreValid = false;
948
- if (
949
- invalidDiscriminatorKey !== currentKey &&
950
- (maxDiscriminatorPriority < currentPriority ||
951
- (maxDiscriminatorPriority === currentPriority &&
952
- currentKey in input &&
953
- !(invalidDiscriminatorKey in input)))
954
- ) {
955
- maxDiscriminatorPriority = currentPriority;
956
- invalidDiscriminatorKey = currentKey;
957
- expectedDiscriminators = [];
958
- }
959
- if (invalidDiscriminatorKey === currentKey)
960
- expectedDiscriminators.push(
961
- schema.entries[currentKey].expects
962
- );
963
- break;
964
- }
965
- currentPriority++;
966
- }
967
- if (keysAreValid) {
968
- const optionDataset = schema['~run'](
969
- { value: input },
970
- config$1
971
- );
972
- if (
973
- !outputDataset ||
974
- (!outputDataset.typed && optionDataset.typed)
975
- )
976
- outputDataset = optionDataset;
977
- }
978
- }
979
- if (outputDataset && !outputDataset.issues) break;
980
- }
981
- }, 'parseOptions');
982
- parseOptions(this, /* @__PURE__ */ new Set([this.key]));
983
- if (outputDataset) return outputDataset;
984
- _addIssue(this, 'type', dataset, config$1, {
985
- input: input[invalidDiscriminatorKey],
986
- expected: /* @__PURE__ */ _joinExpects(expectedDiscriminators, '|'),
987
- path: [
988
- {
989
- type: 'object',
990
- origin: 'value',
991
- input,
992
- key: invalidDiscriminatorKey,
993
- value: input[invalidDiscriminatorKey],
994
- },
995
- ],
996
- });
997
- } else _addIssue(this, 'type', dataset, config$1);
998
- return dataset;
999
- },
1000
- };
1001
- }
1002
- function parse(schema, input, config$1) {
1003
- const dataset = schema['~run'](
1004
- { value: input },
1005
- /* @__PURE__ */ getGlobalConfig(config$1)
1006
- );
1007
- if (dataset.issues) throw new ValiError(dataset.issues);
1008
- return dataset.value;
1009
- }
1010
- // @__NO_SIDE_EFFECTS__
1011
- function pipe(...pipe$1) {
1012
- return {
1013
- ...pipe$1[0],
1014
- pipe: pipe$1,
1015
- get '~standard'() {
1016
- return /* @__PURE__ */ _getStandardProps(this);
1017
- },
1018
- '~run'(dataset, config$1) {
1019
- for (const item of pipe$1)
1020
- if (item.kind !== 'metadata') {
1021
- if (
1022
- dataset.issues &&
1023
- (item.kind === 'schema' || item.kind === 'transformation')
1024
- ) {
1025
- dataset.typed = false;
1026
- break;
1027
- }
1028
- if (
1029
- !dataset.issues ||
1030
- (!config$1.abortEarly && !config$1.abortPipeEarly)
1031
- )
1032
- dataset = item['~run'](dataset, config$1);
1033
- }
1034
- return dataset;
1035
- },
1036
- };
1037
- }
1038
- // @__NO_SIDE_EFFECTS__
1039
- function safeParse(schema, input, config$1) {
1040
- const dataset = schema['~run'](
1041
- { value: input },
1042
- /* @__PURE__ */ getGlobalConfig(config$1)
1043
- );
1044
- return {
1045
- typed: dataset.typed,
1046
- success: !dataset.issues,
1047
- output: dataset.value,
1048
- issues: dataset.issues,
1049
- };
1050
- }
1051
- var store$4,
1052
- store$3,
1053
- store$2,
1054
- store$1,
1055
- ValiError,
1056
- EMAIL_REGEX,
1057
- EMOJI_REGEX,
1058
- ISO_TIMESTAMP_REGEX;
1059
- var init_dist = __esm({
1060
- '../../node_modules/.bun/valibot@1.2.0+1fb4c65d43e298b9/node_modules/valibot/dist/index.mjs'() {
1061
- __name(getGlobalConfig, 'getGlobalConfig');
1062
- __name(getGlobalMessage, 'getGlobalMessage');
1063
- __name(getSchemaMessage, 'getSchemaMessage');
1064
- __name(getSpecificMessage, 'getSpecificMessage');
1065
- __name(_stringify, '_stringify');
1066
- __name(_addIssue, '_addIssue');
1067
- __name(_getStandardProps, '_getStandardProps');
1068
- __name(_isValidObjectKey, '_isValidObjectKey');
1069
- __name(_joinExpects, '_joinExpects');
1070
- ValiError = class extends Error {
1071
- static {
1072
- __name(this, 'ValiError');
1073
- }
1074
- /**
1075
- * Creates a Valibot error with useful information.
1076
- *
1077
- * @param issues The error issues.
1078
- */
1079
- constructor(issues) {
1080
- super(issues[0].message);
1081
- this.name = 'ValiError';
1082
- this.issues = issues;
1083
- }
1084
- };
1085
- EMAIL_REGEX =
1086
- /^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu;
1087
- EMOJI_REGEX = new RegExp(
1088
- '^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$',
1089
- 'u'
1090
- );
1091
- ISO_TIMESTAMP_REGEX =
1092
- /^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z|[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;
1093
- __name(email, 'email');
1094
- __name(isoTimestamp, 'isoTimestamp');
1095
- __name(length, 'length');
1096
- __name(maxLength, 'maxLength');
1097
- __name(maxValue, 'maxValue');
1098
- __name(minLength, 'minLength');
1099
- __name(minValue, 'minValue');
1100
- __name(regex, 'regex');
1101
- __name(url, 'url');
1102
- __name(getFallback, 'getFallback');
1103
- __name(getDefault, 'getDefault');
1104
- __name(any, 'any');
1105
- __name(array, 'array');
1106
- __name(boolean, 'boolean');
1107
- __name(literal, 'literal');
1108
- __name(looseObject, 'looseObject');
1109
- __name(never, 'never');
1110
- __name(nullable, 'nullable');
1111
- __name(number, 'number');
1112
- __name(object, 'object');
1113
- __name(optional, 'optional');
1114
- __name(picklist, 'picklist');
1115
- __name(record, 'record');
1116
- __name(string, 'string');
1117
- __name(_subIssues, '_subIssues');
1118
- __name(union, 'union');
1119
- __name(unknown, 'unknown');
1120
- __name(variant, 'variant');
1121
- __name(parse, 'parse');
1122
- __name(pipe, 'pipe');
1123
- __name(safeParse, 'safeParse');
1124
- },
1125
- });
1126
-
1127
- // ../core/types/src/billing/constants.ts
1128
- var SUBSCRIPTION_STATUS, STRIPE_MODES, DEFAULT_SUBSCRIPTION;
1129
- var init_constants2 = __esm({
1130
- '../core/types/src/billing/constants.ts'() {
1131
- 'use strict';
1132
- SUBSCRIPTION_STATUS = {
1133
- ACTIVE: 'active',
1134
- CANCELED: 'canceled',
1135
- INCOMPLETE: 'incomplete',
1136
- INCOMPLETE_EXPIRED: 'incomplete_expired',
1137
- PAST_DUE: 'past_due',
1138
- TRIALING: 'trialing',
1139
- UNPAID: 'unpaid',
1140
- };
1141
- STRIPE_MODES = {
1142
- PAYMENT: 'payment',
1143
- SUBSCRIPTION: 'subscription',
1144
- };
1145
- DEFAULT_SUBSCRIPTION = {
1146
- tier: 'free',
1147
- subscriptionId: null,
1148
- customerId: '',
1149
- // Will be set to user ID
1150
- status: 'active',
1151
- subscriptionEnd: null,
1152
- cancelAtPeriodEnd: false,
1153
- updatedAt: /* @__PURE__ */ new Date().toISOString(),
1154
- isDefault: true,
1155
- };
1156
- },
1157
- });
1158
-
1159
- // ../core/types/src/billing/schemas.ts
1160
- var CreateCheckoutSessionRequestSchema,
1161
- CreateCheckoutSessionResponseSchema,
1162
- SubscriptionDataSchema,
1163
- SubscriptionClaimsSchema,
1164
- WebhookEventSchema,
1165
- CheckoutSessionMetadataSchema,
1166
- StripePaymentSchema,
1167
- StripeSubscriptionSchema,
1168
- ProductDeclarationSchema,
1169
- ProductDeclarationsSchema,
1170
- StripeFrontConfigSchema,
1171
- StripeBackConfigSchema;
1172
- var init_schemas = __esm({
1173
- '../core/types/src/billing/schemas.ts'() {
1174
- 'use strict';
1175
- init_dist();
1176
- init_constants2();
1177
- CreateCheckoutSessionRequestSchema = object({
1178
- userId: string(),
1179
- productId: optional(string()),
1180
- priceId: string(),
1181
- successUrl: pipe(string(), url()),
1182
- cancelUrl: pipe(string(), url()),
1183
- customerEmail: optional(pipe(string(), email())),
1184
- userEmail: optional(pipe(string(), email())),
1185
- metadata: optional(record(string(), string())),
1186
- allowPromotionCodes: optional(boolean()),
1187
- mode: optional(
1188
- picklist([STRIPE_MODES.PAYMENT, STRIPE_MODES.SUBSCRIPTION])
1189
- ),
1190
- });
1191
- CreateCheckoutSessionResponseSchema = object({
1192
- sessionId: string(),
1193
- sessionUrl: nullable(pipe(string(), url())),
1194
- });
1195
- SubscriptionDataSchema = object({
1196
- userId: string(),
1197
- tier: string(),
1198
- status: picklist(Object.values(SUBSCRIPTION_STATUS)),
1199
- subscriptionId: nullable(string()),
1200
- customerId: string(),
1201
- subscriptionEnd: nullable(pipe(string(), isoTimestamp())),
1202
- cancelAtPeriodEnd: boolean(),
1203
- updatedAt: pipe(string(), isoTimestamp()),
1204
- });
1205
- SubscriptionClaimsSchema = object({
1206
- tier: string(),
1207
- subscriptionId: nullable(string()),
1208
- customerId: string(),
1209
- status: picklist(Object.values(SUBSCRIPTION_STATUS)),
1210
- subscriptionEnd: nullable(pipe(string(), isoTimestamp())),
1211
- cancelAtPeriodEnd: boolean(),
1212
- updatedAt: pipe(string(), isoTimestamp()),
1213
- isDefault: optional(boolean()),
1214
- });
1215
- WebhookEventSchema = object({
1216
- id: string(),
1217
- type: string(),
1218
- data: object({
1219
- object: any(),
1220
- }),
1221
- created: pipe(string(), isoTimestamp()),
1222
- });
1223
- CheckoutSessionMetadataSchema = looseObject({
1224
- userId: optional(string()),
1225
- firebaseUid: optional(string()),
1226
- productType: optional(string()),
1227
- });
1228
- StripePaymentSchema = object({
1229
- type: literal('StripePayment'),
1230
- name: pipe(string(), minLength(1, 'Product name is required')),
1231
- description: optional(string()),
1232
- price: string(),
1233
- // Display price (e.g., "2,000€") - not used for Stripe, only for display
1234
- currency: optional(
1235
- pipe(string(), length(3, 'Currency must be 3-letter ISO code')),
1236
- 'EUR'
1237
- ),
1238
- priceId: pipe(string(), minLength(1, 'Stripe price ID is required')),
1239
- tier: pipe(string(), minLength(1, 'Tier is required')),
1240
- duration: pipe(string(), minLength(1, 'Duration is required')),
1241
- // 'lifetime', '6months', etc.
1242
- allowPromotionCodes: optional(boolean()),
1243
- // Optional: Custom metadata
1244
- metadata: optional(record(string(), string())),
1245
- // Extension hooks - users define custom logic (TypeScript only)
1246
- // onPurchaseSuccess?: (userId: string, metadata: any) => Promise<void>;
1247
- // onPurchaseFailure?: (userId: string, metadata: any) => Promise<void>;
1248
- });
1249
- StripeSubscriptionSchema = object({
1250
- type: literal('StripeSubscription'),
1251
- name: pipe(string(), minLength(1, 'Product name is required')),
1252
- description: optional(string()),
1253
- price: string(),
1254
- // Display price (e.g., "2,000€") - not used for Stripe, only for display
1255
- currency: optional(
1256
- pipe(string(), length(3, 'Currency must be 3-letter ISO code')),
1257
- 'EUR'
1258
- ),
1259
- priceId: pipe(string(), minLength(1, 'Stripe price ID is required')),
1260
- tier: pipe(string(), minLength(1, 'Tier is required')),
1261
- duration: picklist([
1262
- '1month',
1263
- '3months',
1264
- '6months',
1265
- '1year',
1266
- '2years',
1267
- 'lifetime',
1268
- ]),
1269
- allowPromotionCodes: optional(boolean()),
1270
- // Optional: Custom metadata
1271
- metadata: optional(record(string(), string())),
1272
- // Extension hooks - users define custom logic (TypeScript only)
1273
- // onSubscriptionCreated?: (userId: string, metadata: any) => Promise<void>;
1274
- // onSubscriptionRenewed?: (userId: string, metadata: any) => Promise<void>;
1275
- // onSubscriptionCancelled?: (userId: string, metadata: any) => Promise<void>;
1276
- // onPaymentFailed?: (userId: string, metadata: any) => Promise<void>;
1277
- });
1278
- ProductDeclarationSchema = variant('type', [
1279
- StripePaymentSchema,
1280
- StripeSubscriptionSchema,
1281
- ]);
1282
- ProductDeclarationsSchema = record(
1283
- string(),
1284
- // Product key
1285
- ProductDeclarationSchema
1286
- );
1287
- StripeFrontConfigSchema = record(
1288
- string(),
1289
- // Product key
1290
- object({
1291
- name: string(),
1292
- price: string(),
1293
- // Display price (e.g., "2,000€")
1294
- currency: string(),
1295
- description: optional(string()),
1296
- features: optional(array(string())),
1297
- priceId: string(),
1298
- allowPromotionCodes: optional(boolean()),
1299
- })
1300
- );
1301
- StripeBackConfigSchema = record(
1302
- string(),
1303
- // Product key
1304
- object({
1305
- type: picklist(['StripePayment', 'StripeSubscription']),
1306
- name: string(),
1307
- price: number(),
1308
- currency: string(),
1309
- priceId: string(),
1310
- tier: string(),
1311
- duration: string(),
1312
- description: optional(string()),
1313
- metadata: optional(record(string(), string())),
1314
- allowPromotionCodes: optional(boolean()),
1315
- // Hooks are TypeScript-only, not validated by Valibot
1316
- })
1317
- );
1318
- },
1319
- });
1320
-
1321
- // ../core/types/src/billing/types.ts
1322
- var init_types = __esm({
1323
- '../core/types/src/billing/types.ts'() {
1324
- 'use strict';
1325
- },
1326
- });
1327
-
1328
- // ../core/types/src/billing/index.ts
1329
- var init_billing = __esm({
1330
- '../core/types/src/billing/index.ts'() {
1331
- 'use strict';
1332
- init_constants2();
1333
- init_schemas();
1334
- init_types();
1335
- },
1336
- });
1337
-
1338
- // ../core/types/src/auth/schemas.ts
1339
- var AuthUserSchema, UserSubscriptionSchema, CustomClaimsSchema;
1340
- var init_schemas2 = __esm({
1341
- '../core/types/src/auth/schemas.ts'() {
1342
- 'use strict';
1343
- init_dist();
1344
- init_constants();
1345
- init_billing();
1346
- AuthUserSchema = object({
1347
- id: string(),
1348
- // Nullable to match runtime mapping from Firebase (can be null)
1349
- email: optional(nullable(pipe(string(), email()))),
1350
- displayName: optional(nullable(string())),
1351
- photoURL: optional(nullable(pipe(string(), url()))),
1352
- // Additional runtime properties used across the app
1353
- emailVerified: optional(boolean()),
1354
- lastLoginAt: optional(string()),
1355
- // Provider data mapped from Firebase providers
1356
- providerData: optional(
1357
- array(
1358
- object({
1359
- providerId: string(),
1360
- uid: string(),
1361
- email: optional(nullable(pipe(string(), email()))),
1362
- displayName: optional(nullable(string())),
1363
- photoURL: optional(nullable(pipe(string(), url()))),
1364
- phoneNumber: optional(nullable(string())),
1365
- })
1366
- )
1367
- ),
1368
- role: optional(picklist(Object.values(USER_ROLES))),
1369
- customClaims: optional(record(string(), any())),
1370
- });
1371
- UserSubscriptionSchema = object({
1372
- userId: string(),
1373
- tier: picklist(Object.values(SUBSCRIPTION_TIERS)),
1374
- status: picklist(Object.values(SUBSCRIPTION_STATUS)),
1375
- isActive: optional(boolean()),
1376
- features: optional(array(string())),
1377
- subscriptionId: nullable(string()),
1378
- customerId: string(),
1379
- subscriptionEnd: nullable(pipe(string(), isoTimestamp())),
1380
- cancelAtPeriodEnd: boolean(),
1381
- updatedAt: pipe(string(), isoTimestamp()),
1382
- });
1383
- CustomClaimsSchema = object({
1384
- role: optional(picklist(Object.values(USER_ROLES))),
1385
- subscription: optional(UserSubscriptionSchema),
1386
- features: optional(array(picklist(Object.values(FEATURES)))),
1387
- permissions: optional(array(picklist(Object.values(PERMISSIONS)))),
1388
- githubAccess: optional(
1389
- object({
1390
- username: optional(string()),
1391
- teamAccess: optional(array(string())),
1392
- repoAccess: optional(array(string())),
1393
- })
1394
- ),
1395
- });
1396
- },
1397
- });
1398
-
1399
- // ../core/types/src/auth/types.ts
1400
- var init_types2 = __esm({
1401
- '../core/types/src/auth/types.ts'() {
1402
- 'use strict';
1403
- },
1404
- });
1405
-
1406
- // ../core/types/src/auth/index.ts
1407
- var init_auth = __esm({
1408
- '../core/types/src/auth/index.ts'() {
1409
- 'use strict';
1410
- init_constants();
1411
- init_schemas2();
1412
- init_types2();
1413
- },
1414
- });
1415
-
1416
- // ../core/types/src/common/index.ts
1417
- var init_common = __esm({
1418
- '../core/types/src/common/index.ts'() {
1419
- 'use strict';
1420
- },
1421
- });
1422
-
1423
- // ../core/types/src/crud/aggregate.ts
1424
- var init_aggregate = __esm({
1425
- '../core/types/src/crud/aggregate.ts'() {
1426
- 'use strict';
1427
- },
1428
- });
1429
-
1430
- // ../core/types/src/crud/constants.ts
1431
- var init_constants3 = __esm({
1432
- '../core/types/src/crud/constants.ts'() {
1433
- 'use strict';
1434
- },
1435
- });
1436
-
1437
- // ../core/types/src/crud/schemas.ts
1438
- var FIRESTORE_ID_PATTERN,
1439
- createEntitySchema,
1440
- getEntitySchema,
1441
- updateEntitySchema,
1442
- deleteEntitySchema,
1443
- listEntitiesSchema;
1444
- var init_schemas3 = __esm({
1445
- '../core/types/src/crud/schemas.ts'() {
1446
- 'use strict';
1447
- init_dist();
1448
- init_constants3();
1449
- FIRESTORE_ID_PATTERN = /^[0-9a-zA-Z]+$/;
1450
- createEntitySchema = object({
1451
- collection: pipe(string(), minLength(1, 'Collection name is required')),
1452
- data: record(string(), unknown()),
1453
- idempotencyKey: optional(string()),
1454
- });
1455
- getEntitySchema = object({
1456
- collection: pipe(string(), minLength(1, 'Collection name is required')),
1457
- id: pipe(string(), minLength(1, 'Entity ID is required')),
1458
- });
1459
- updateEntitySchema = object({
1460
- collection: pipe(string(), minLength(1, 'Collection name is required')),
1461
- id: pipe(string(), minLength(1, 'Entity ID is required')),
1462
- data: record(string(), unknown()),
1463
- merge: optional(boolean(), false),
1464
- });
1465
- deleteEntitySchema = object({
1466
- collection: pipe(string(), minLength(1, 'Collection name is required')),
1467
- id: pipe(string(), minLength(1, 'Entity ID is required')),
1468
- });
1469
- listEntitiesSchema = object({
1470
- collection: pipe(string(), minLength(1, 'Collection name is required')),
1471
- limit: optional(pipe(number(), minValue(1), maxValue(1e3)), 50),
1472
- offset: optional(pipe(number(), minValue(0)), 0),
1473
- orderBy: optional(string()),
1474
- orderDirection: optional(picklist(['asc', 'desc']), 'desc'),
1475
- where: optional(
1476
- array(
1477
- object({
1478
- field: string(),
1479
- operator: picklist([
1480
- '==',
1481
- '!=',
1482
- '<',
1483
- '<=',
1484
- '>',
1485
- '>=',
1486
- 'array-contains',
1487
- 'in',
1488
- 'not-in',
1489
- ]),
1490
- value: any(),
1491
- })
1492
- )
1493
- ),
1494
- });
1495
- },
1496
- });
1497
-
1498
- // ../core/types/src/crud/types.ts
1499
- var init_types3 = __esm({
1500
- '../core/types/src/crud/types.ts'() {
1501
- 'use strict';
1502
- },
1503
- });
1504
-
1505
- // ../core/types/src/crud/index.ts
1506
- var init_crud = __esm({
1507
- '../core/types/src/crud/index.ts'() {
1508
- 'use strict';
1509
- init_aggregate();
1510
- init_schemas3();
1511
- init_types3();
1512
- },
1513
- });
1514
-
1515
- // ../core/types/src/errors/errorClasses.ts
1516
- var FIREBASE_ERROR_MAP, DoNotDevError;
1517
- var init_errorClasses = __esm({
1518
- '../core/types/src/errors/errorClasses.ts'() {
1519
- 'use strict';
1520
- FIREBASE_ERROR_MAP = {
1521
- 'permission-denied': {
1522
- type: 'PERMISSION_DENIED',
1523
- message: 'You do not have permission to perform this action',
1524
- },
1525
- 'not-found': {
1526
- type: 'NOT_FOUND',
1527
- message: 'The requested resource was not found',
1528
- },
1529
- 'already-exists': {
1530
- type: 'ALREADY_EXISTS',
1531
- message: 'The resource already exists',
1532
- },
1533
- 'invalid-argument': {
1534
- type: 'VALIDATION_ERROR',
1535
- message: 'Invalid argument provided',
1536
- },
1537
- };
1538
- DoNotDevError = class _DoNotDevError extends Error {
1539
- static {
1540
- __name(this, 'DoNotDevError');
1541
- }
1542
- /** The error code categorizing this error */
1543
- code;
1544
- /** Optional additional details or context about the error */
1545
- details;
1546
- /** The source system where the error originated */
1547
- source;
1548
- /** Original error if this is wrapping another error */
1549
- originalError;
1550
- /** Additional context for the error */
1551
- context;
1552
- /** Whether this error should be displayed to the user */
1553
- displayable;
1554
- /** Flag to track if a user message has been provided */
1555
- userMessageProvided;
1556
- constructor(message, code = 'internal', options) {
1557
- super(message);
1558
- Object.setPrototypeOf(this, _DoNotDevError.prototype);
1559
- this.code = code;
1560
- this.details = options?.details;
1561
- this.source = options?.source;
1562
- this.originalError = options?.originalError;
1563
- this.context = options?.context;
1564
- this.displayable = options?.displayable ?? true;
1565
- this.userMessageProvided = options?.userMessageProvided;
1566
- this.name = this.constructor.name;
1567
- if (Error.captureStackTrace) {
1568
- Error.captureStackTrace(this, this.constructor);
1569
- }
1570
- }
1571
- toString() {
1572
- return `${this.name} [${this.code}]: ${this.message}`;
1573
- }
1574
- toJSON() {
1575
- return {
1576
- name: this.name,
1577
- code: this.code,
1578
- message: this.message,
1579
- details: this.details,
1580
- source: this.source,
1581
- originalError: this.originalError,
1582
- context: this.context,
1583
- displayable: this.displayable,
1584
- userMessageProvided: this.userMessageProvided,
1585
- };
1586
- }
1587
- };
1588
- },
1589
- });
1590
-
1591
- // ../core/types/src/errors/index.ts
1592
- var init_errors = __esm({
1593
- '../core/types/src/errors/index.ts'() {
1594
- 'use strict';
1595
- init_errorClasses();
1596
- },
1597
- });
1598
-
1599
- // ../core/types/src/events/AuthEvents.ts
1600
- var init_AuthEvents = __esm({
1601
- '../core/types/src/events/AuthEvents.ts'() {
1602
- 'use strict';
1603
- },
1604
- });
1605
-
1606
- // ../core/types/src/events/BillingEvents.ts
1607
- var init_BillingEvents = __esm({
1608
- '../core/types/src/events/BillingEvents.ts'() {
1609
- 'use strict';
1610
- },
1611
- });
1612
-
1613
- // ../core/types/src/events/OAuthEvents.ts
1614
- var init_OAuthEvents = __esm({
1615
- '../core/types/src/events/OAuthEvents.ts'() {
1616
- 'use strict';
1617
- },
1618
- });
1619
-
1620
- // ../core/types/src/events/PayloadEvents.ts
1621
- var init_PayloadEvents = __esm({
1622
- '../core/types/src/events/PayloadEvents.ts'() {
1623
- 'use strict';
1624
- },
1625
- });
1626
-
1627
- // ../core/types/src/events/StripeEvents.ts
1628
- var init_StripeEvents = __esm({
1629
- '../core/types/src/events/StripeEvents.ts'() {
1630
- 'use strict';
1631
- },
1632
- });
1633
-
1634
- // ../core/types/src/events/index.ts
1635
- var init_events = __esm({
1636
- '../core/types/src/events/index.ts'() {
1637
- 'use strict';
1638
- init_AuthEvents();
1639
- init_BillingEvents();
1640
- init_OAuthEvents();
1641
- init_PayloadEvents();
1642
- init_StripeEvents();
1643
- },
1644
- });
1645
-
1646
- // ../core/types/src/firebase/firebaseTypes.ts
1647
- var init_firebaseTypes = __esm({
1648
- '../core/types/src/firebase/firebaseTypes.ts'() {
1649
- 'use strict';
1650
- },
1651
- });
1652
-
1653
- // ../core/types/src/firebase/index.ts
1654
- var init_firebase = __esm({
1655
- '../core/types/src/firebase/index.ts'() {
1656
- 'use strict';
1657
- init_firebaseTypes();
1658
- },
1659
- });
1660
-
1661
- // ../core/types/src/functions/functionTypes.ts
1662
- var init_functionTypes = __esm({
1663
- '../core/types/src/functions/functionTypes.ts'() {
1664
- 'use strict';
1665
- },
1666
- });
1667
-
1668
- // ../core/types/src/functions/index.ts
1669
- var init_functions = __esm({
1670
- '../core/types/src/functions/index.ts'() {
1671
- 'use strict';
1672
- init_functionTypes();
1673
- },
1674
- });
1675
-
1676
- // ../core/types/src/hooks/hookTypes.ts
1677
- var init_hookTypes = __esm({
1678
- '../core/types/src/hooks/hookTypes.ts'() {
1679
- 'use strict';
1680
- },
1681
- });
1682
-
1683
- // ../core/types/src/hooks/index.ts
1684
- var init_hooks = __esm({
1685
- '../core/types/src/hooks/index.ts'() {
1686
- 'use strict';
1687
- init_hookTypes();
1688
- },
1689
- });
1690
-
1691
- // ../core/types/src/i18n/i18nTypes.ts
1692
- var init_i18nTypes = __esm({
1693
- '../core/types/src/i18n/i18nTypes.ts'() {
1694
- 'use strict';
1695
- },
1696
- });
1697
-
1698
- // ../core/types/src/i18n/index.ts
1699
- var init_i18n = __esm({
1700
- '../core/types/src/i18n/index.ts'() {
1701
- 'use strict';
1702
- init_i18nTypes();
1703
- },
1704
- });
1705
-
1706
- // ../core/types/src/layout/breakpoint.ts
1707
- var init_breakpoint = __esm({
1708
- '../core/types/src/layout/breakpoint.ts'() {
1709
- 'use strict';
1710
- },
1711
- });
1712
-
1713
- // ../core/types/src/layout/layoutTypes.ts
1714
- var init_layoutTypes = __esm({
1715
- '../core/types/src/layout/layoutTypes.ts'() {
1716
- 'use strict';
1717
- },
1718
- });
1719
-
1720
- // ../core/types/src/layout/presetConfig.ts
1721
- var init_presetConfig = __esm({
1722
- '../core/types/src/layout/presetConfig.ts'() {
1723
- 'use strict';
1724
- },
1725
- });
1726
-
1727
- // ../core/types/src/layout/index.ts
1728
- var init_layout = __esm({
1729
- '../core/types/src/layout/index.ts'() {
1730
- 'use strict';
1731
- init_breakpoint();
1732
- init_layoutTypes();
1733
- init_presetConfig();
1734
- },
1735
- });
1736
-
1737
- // ../core/types/src/legal/types.ts
1738
- var init_types4 = __esm({
1739
- '../core/types/src/legal/types.ts'() {
1740
- 'use strict';
1741
- },
1742
- });
1743
-
1744
- // ../core/types/src/legal/index.ts
1745
- var init_legal = __esm({
1746
- '../core/types/src/legal/index.ts'() {
1747
- 'use strict';
1748
- init_types4();
1749
- },
1750
- });
1751
-
1752
- // ../core/types/src/oauth/constants.ts
1753
- var GITHUB_PERMISSION_LEVELS;
1754
- var init_constants4 = __esm({
1755
- '../core/types/src/oauth/constants.ts'() {
1756
- 'use strict';
1757
- GITHUB_PERMISSION_LEVELS = ['pull', 'push', 'admin', 'maintain', 'triage'];
1758
- },
1759
- });
1760
-
1761
- // ../core/types/src/oauth/types.ts
1762
- var init_types5 = __esm({
1763
- '../core/types/src/oauth/types.ts'() {
1764
- 'use strict';
1765
- },
1766
- });
1767
-
1768
- // ../core/types/src/oauth/schemas.ts
1769
- var githubRepoConfigSchema,
1770
- githubPermissionSchema,
1771
- grantGitHubAccessSchema,
1772
- revokeGitHubAccessSchema,
1773
- checkGitHubAccessSchema,
1774
- exchangeTokenSchema,
1775
- refreshTokenSchema,
1776
- disconnectOAuthSchema,
1777
- getConnectionsSchema;
1778
- var init_schemas4 = __esm({
1779
- '../core/types/src/oauth/schemas.ts'() {
1780
- 'use strict';
1781
- init_dist();
1782
- init_constants4();
1783
- githubRepoConfigSchema = object({
1784
- owner: pipe(string(), minLength(1, 'Repository owner is required')),
1785
- repo: pipe(string(), minLength(1, 'Repository name is required')),
1786
- });
1787
- githubPermissionSchema = picklist([...GITHUB_PERMISSION_LEVELS]);
1788
- grantGitHubAccessSchema = object({
1789
- userId: pipe(string(), minLength(1, 'User ID is required')),
1790
- githubUsername: pipe(
1791
- string(),
1792
- minLength(1, 'GitHub username is required')
1793
- ),
1794
- repoConfig: githubRepoConfigSchema,
1795
- permission: optional(githubPermissionSchema, 'push'),
1796
- customClaims: optional(record(string(), any())),
1797
- });
1798
- revokeGitHubAccessSchema = object({
1799
- userId: pipe(string(), minLength(1, 'User ID is required')),
1800
- githubUsername: pipe(
1801
- string(),
1802
- minLength(1, 'GitHub username is required')
1803
- ),
1804
- repoConfig: githubRepoConfigSchema,
1805
- });
1806
- checkGitHubAccessSchema = object({
1807
- userId: pipe(string(), minLength(1, 'User ID is required')),
1808
- githubUsername: pipe(
1809
- string(),
1810
- minLength(1, 'GitHub username is required')
1811
- ),
1812
- repoConfig: githubRepoConfigSchema,
1813
- });
1814
- exchangeTokenSchema = object({
1815
- provider: string(),
1816
- purpose: picklist(['authentication', 'api-access']),
1817
- code: pipe(string(), minLength(1, 'Authorization code is required')),
1818
- redirectUri: pipe(string(), url('Valid redirect URI is required')),
1819
- codeVerifier: optional(string()),
1820
- state: optional(string()),
1821
- instance: optional(pipe(string(), url())),
1822
- });
1823
- refreshTokenSchema = object({
1824
- provider: string(),
1825
- refreshToken: pipe(string(), minLength(1, 'Refresh token is required')),
1826
- redirectUri: pipe(string(), url('Valid redirect URI is required')),
1827
- });
1828
- disconnectOAuthSchema = object({
1829
- provider: string(),
1830
- });
1831
- getConnectionsSchema = object({
1832
- userId: pipe(string(), minLength(1, 'User ID is required')),
1833
- });
1834
- },
1835
- });
1836
-
1837
- // ../core/types/src/oauth/index.ts
1838
- var init_oauth = __esm({
1839
- '../core/types/src/oauth/index.ts'() {
1840
- 'use strict';
1841
- init_constants4();
1842
- init_types5();
1843
- init_schemas4();
1844
- },
1845
- });
1846
-
1847
- // ../core/types/src/partners/constants.ts
1848
- var init_constants5 = __esm({
1849
- '../core/types/src/partners/constants.ts'() {
1850
- 'use strict';
1851
- },
1852
- });
1853
-
1854
- // ../core/types/src/partners/schemas.ts
1855
- var basePartnerSchema,
1856
- authPartnerSchema,
1857
- urlOrEmptyString,
1858
- oauthEndpointsSchema,
1859
- oauthScopesSchema,
1860
- oauthCapabilitiesSchema,
1861
- oauthPartnerSchema,
1862
- authPartnersSchema,
1863
- oauthPartnersSchema;
1864
- var init_schemas5 = __esm({
1865
- '../core/types/src/partners/schemas.ts'() {
1866
- 'use strict';
1867
- init_dist();
1868
- basePartnerSchema = object({
1869
- name: string(),
1870
- color: string(),
1871
- icon: string(),
1872
- customParameters: optional(record(string(), string())),
1873
- button: object({
1874
- backgroundColor: string(),
1875
- textColor: string(),
1876
- borderColor: string(),
1877
- hoverBackgroundColor: string(),
1878
- focusOutlineColor: string(),
1879
- fontWeight: optional(string(), '500'),
1880
- textKey: optional(string()),
1881
- }),
1882
- });
1883
- authPartnerSchema = object({
1884
- ...basePartnerSchema.entries,
1885
- type: picklist(['auth', 'both']),
1886
- scopes: optional(array(string())),
1887
- firebaseProviderId: optional(string()),
1888
- });
1889
- urlOrEmptyString = union([literal(''), pipe(string(), url())]);
1890
- oauthEndpointsSchema = object({
1891
- authUrl: urlOrEmptyString,
1892
- tokenUrl: urlOrEmptyString,
1893
- profileUrl: urlOrEmptyString,
1894
- revokeUrl: optional(urlOrEmptyString),
1895
- });
1896
- oauthScopesSchema = object({
1897
- authentication: optional(array(string())),
1898
- 'api-access': array(string()),
1899
- });
1900
- oauthCapabilitiesSchema = optional(
1901
- object({
1902
- pkce: optional(boolean(), false),
1903
- // Provider supports PKCE
1904
- codeChallengeMethod: optional(picklist(['S256', 'plain']), 'S256'),
1905
- })
1906
- );
1907
- oauthPartnerSchema = object({
1908
- ...basePartnerSchema.entries,
1909
- type: picklist(['oauth', 'both']),
1910
- scopes: oauthScopesSchema,
1911
- endpoints: oauthEndpointsSchema,
1912
- capabilities: oauthCapabilitiesSchema,
1913
- });
1914
- authPartnersSchema = record(string(), authPartnerSchema);
1915
- oauthPartnersSchema = record(string(), oauthPartnerSchema);
1916
- },
1917
- });
1918
-
1919
- // ../core/types/src/partners/types.ts
1920
- var init_types6 = __esm({
1921
- '../core/types/src/partners/types.ts'() {
1922
- 'use strict';
1923
- },
1924
- });
1925
-
1926
- // ../core/types/src/partners/index.ts
1927
- var init_partners = __esm({
1928
- '../core/types/src/partners/index.ts'() {
1929
- 'use strict';
1930
- init_constants5();
1931
- init_schemas5();
1932
- init_types6();
1933
- },
1934
- });
1935
-
1936
- // ../core/types/src/stores/storeTypes.ts
1937
- var init_storeTypes = __esm({
1938
- '../core/types/src/stores/storeTypes.ts'() {
1939
- 'use strict';
1940
- },
1941
- });
1942
-
1943
- // ../core/types/src/stores/index.ts
1944
- var init_stores = __esm({
1945
- '../core/types/src/stores/index.ts'() {
1946
- 'use strict';
1947
- init_storeTypes();
1948
- },
1949
- });
1950
-
1951
- // ../core/types/src/ui/uiTypes.ts
1952
- var CONSENT_CATEGORY, FEATURE_CONSENT_MATRIX;
1953
- var init_uiTypes = __esm({
1954
- '../core/types/src/ui/uiTypes.ts'() {
1955
- 'use strict';
1956
- CONSENT_CATEGORY = {
1957
- NECESSARY: 'necessary',
1958
- FUNCTIONAL: 'functional',
1959
- ANALYTICS: 'analytics',
1960
- MARKETING: 'marketing',
1961
- };
1962
- FEATURE_CONSENT_MATRIX = {
1963
- /** Authentication - Firebase Auth, user sessions */
1964
- auth: { requiresConsent: null },
1965
- /** OAuth - Third-party authentication (Google, GitHub, etc.) */
1966
- oauth: { requiresConsent: null },
1967
- /** Billing - Stripe subscriptions, payments */
1968
- billing: { requiresConsent: null },
1969
- /** Analytics - Usage tracking, performance monitoring */
1970
- analytics: { requiresConsent: CONSENT_CATEGORY.ANALYTICS },
1971
- /** Marketing - Advertising, retargeting */
1972
- marketing: { requiresConsent: CONSENT_CATEGORY.MARKETING },
1973
- };
1974
- },
1975
- });
1976
-
1977
- // ../core/types/src/ui/index.ts
1978
- var init_ui = __esm({
1979
- '../core/types/src/ui/index.ts'() {
1980
- 'use strict';
1981
- init_uiTypes();
1982
- },
1983
- });
1984
-
1985
- // ../core/types/src/utils/networkManager.ts
1986
- var init_networkManager = __esm({
1987
- '../core/types/src/utils/networkManager.ts'() {
1988
- 'use strict';
1989
- },
1990
- });
1991
-
1992
- // ../core/types/src/utils/rateLimiter.ts
1993
- var init_rateLimiter = __esm({
1994
- '../core/types/src/utils/rateLimiter.ts'() {
1995
- 'use strict';
1996
- },
1997
- });
1998
-
1999
- // ../core/types/src/utils/index.ts
2000
- var init_utils = __esm({
2001
- '../core/types/src/utils/index.ts'() {
2002
- 'use strict';
2003
- init_networkManager();
2004
- init_rateLimiter();
2005
- },
2006
- });
2007
-
2008
- // ../core/types/src/index.ts
2009
- var init_src = __esm({
2010
- '../core/types/src/index.ts'() {
2011
- 'use strict';
2012
- init_auth();
2013
- init_billing();
2014
- init_common();
2015
- init_crud();
2016
- init_errors();
2017
- init_events();
2018
- init_firebase();
2019
- init_functions();
2020
- init_hooks();
2021
- init_i18n();
2022
- init_layout();
2023
- init_legal();
2024
- init_oauth();
2025
- init_partners();
2026
- init_stores();
2027
- init_ui();
2028
- init_utils();
2029
- },
2030
- });
2031
-
2032
- // ../core/utils/src/common/errors/doNotDevError.ts
2033
- var init_doNotDevError = __esm({
2034
- '../core/utils/src/common/errors/doNotDevError.ts'() {
2035
- 'use strict';
2036
- init_src();
2037
- },
2038
- });
2039
-
2040
- // ../core/utils/src/common/errors/internal/errorDetection.ts
2041
- function detectErrorSource(error) {
2042
- if (
2043
- error instanceof Error &&
2044
- 'source' in error &&
2045
- typeof error.source === 'string'
2046
- ) {
2047
- return error.source;
2048
- }
2049
- if (
2050
- typeof error === 'object' &&
2051
- error !== null &&
2052
- 'code' in error &&
2053
- typeof error.code === 'string' &&
2054
- error.code.startsWith('auth/')
2055
- ) {
2056
- return 'auth';
2057
- }
2058
- if (
2059
- typeof error === 'object' &&
2060
- error !== null &&
2061
- 'code' in error &&
2062
- typeof error.code === 'string' &&
2063
- error.code.startsWith('oauth/')
2064
- ) {
2065
- return 'oauth';
2066
- }
2067
- if (
2068
- typeof error === 'object' &&
2069
- error !== null &&
2070
- 'code' in error &&
2071
- typeof error.code === 'string' &&
2072
- [
2073
- 'permission-denied',
2074
- 'unavailable',
2075
- 'not-found',
2076
- 'already-exists',
2077
- 'unauthenticated',
2078
- 'invalid-argument',
2079
- 'failed-precondition',
2080
- 'resource-exhausted',
2081
- ].includes(error.code)
2082
- ) {
2083
- return 'firebase';
2084
- }
2085
- if (
2086
- typeof error === 'object' &&
2087
- error !== null &&
2088
- 'issues' in error &&
2089
- Array.isArray(error.issues) &&
2090
- 'name' in error &&
2091
- error.name === 'ValiError'
2092
- ) {
2093
- return 'validation';
2094
- }
2095
- if (error instanceof Error && error.name === 'EntityHookError') {
2096
- return 'entity';
2097
- }
2098
- if (
2099
- typeof error === 'object' &&
2100
- error !== null &&
2101
- ('response' in error || 'status' in error || 'statusText' in error)
2102
- ) {
2103
- return 'api';
2104
- }
2105
- if (
2106
- typeof error === 'object' &&
2107
- error !== null &&
2108
- 'componentStack' in error
2109
- ) {
2110
- return 'ui';
2111
- }
2112
- return 'unknown';
2113
- }
2114
- var init_errorDetection = __esm({
2115
- '../core/utils/src/common/errors/internal/errorDetection.ts'() {
2116
- 'use strict';
2117
- __name(detectErrorSource, 'detectErrorSource');
2118
- },
2119
- });
2120
-
2121
- // ../core/utils/src/common/errors/internal/serviceErrorHandler.ts
2122
- function createErrorHandler(config) {
2123
- return (error, userMessage) => {
2124
- if (error instanceof DoNotDevError) {
2125
- return error;
2126
- }
2127
- if (typeof error !== 'object' || error === null) {
2128
- const message2 =
2129
- typeof error === 'string' ? error : config.defaultErrorMessage;
2130
- return new DoNotDevError(
2131
- userMessage || message2,
2132
- config.defaultErrorCode,
2133
- {
2134
- details: { originalError: error },
2135
- source: config.errorSource,
2136
- }
2137
- );
2138
- }
2139
- let errorCode;
2140
- if (config.extractErrorCode) {
2141
- errorCode = config.extractErrorCode(error);
2142
- } else if ('code' in error && typeof error.code === 'string') {
2143
- errorCode = error.code;
2144
- }
2145
- let standardErrorCode = config.defaultErrorCode;
2146
- if (
2147
- errorCode &&
2148
- config.errorCodeMapping &&
2149
- errorCode in config.errorCodeMapping
2150
- ) {
2151
- standardErrorCode = config.errorCodeMapping[errorCode];
2152
- }
2153
- let message;
2154
- if (config.extractErrorMessage) {
2155
- message = config.extractErrorMessage(error);
2156
- } else if ('message' in error && typeof error.message === 'string') {
2157
- message = error.message;
2158
- } else if (error instanceof Error) {
2159
- message = error.message;
2160
- }
2161
- if (
2162
- errorCode &&
2163
- config.friendlyMessageMapping &&
2164
- errorCode in config.friendlyMessageMapping
2165
- ) {
2166
- message = config.friendlyMessageMapping[errorCode];
2167
- }
2168
- if (!message) {
2169
- message = config.defaultErrorMessage;
2170
- }
2171
- let metadata;
2172
- if (config.processMetadata) {
2173
- metadata = config.processMetadata(error);
2174
- } else {
2175
- metadata = { originalError: error };
2176
- if (errorCode) {
2177
- metadata.originalCode = errorCode;
2178
- }
2179
- }
2180
- if (!('originalError' in metadata)) {
2181
- metadata.originalError = error;
2182
- }
2183
- return new DoNotDevError(userMessage || message, standardErrorCode, {
2184
- details: metadata,
2185
- source: config.errorSource,
2186
- });
2187
- };
2188
- }
2189
- var commonErrorCodeMappings;
2190
- var init_serviceErrorHandler = __esm({
2191
- '../core/utils/src/common/errors/internal/serviceErrorHandler.ts'() {
2192
- 'use strict';
2193
- init_doNotDevError();
2194
- __name(createErrorHandler, 'createErrorHandler');
2195
- commonErrorCodeMappings = {
2196
- 'permission-denied': 'permission-denied',
2197
- unavailable: 'unavailable',
2198
- 'not-found': 'not-found',
2199
- 'already-exists': 'already-exists',
2200
- unauthenticated: 'unauthenticated',
2201
- 'invalid-argument': 'invalid-argument',
2202
- 'failed-precondition': 'invalid-argument',
2203
- 'resource-exhausted': 'rate-limit-exceeded',
2204
- 'deadline-exceeded': 'timeout',
2205
- cancelled: 'cancelled',
2206
- 'not-implemented': 'unimplemented',
2207
- };
2208
- },
2209
- });
2210
-
2211
- // ../core/utils/src/common/errors/internal/errorMapper.ts
2212
- function mapToDoNotDevError(error, source, userMessage) {
2213
- if (error instanceof DoNotDevError) {
2214
- return error;
2215
- }
2216
- const handler =
2217
- ERROR_HANDLER_REGISTRY[source] || ERROR_HANDLER_REGISTRY.unknown;
2218
- return handler(error, userMessage);
2219
- }
2220
- var DEFAULT_ERROR_MESSAGES,
2221
- HTTP_STATUS_CODE_MAPPING,
2222
- ENTITY_ERROR_MAPPING,
2223
- ERROR_HANDLERS,
2224
- handleValidationError,
2225
- handleEntityError,
2226
- ERROR_HANDLER_REGISTRY;
2227
- var init_errorMapper = __esm({
2228
- '../core/utils/src/common/errors/internal/errorMapper.ts'() {
2229
- 'use strict';
2230
- init_dist();
2231
- init_src();
2232
- init_doNotDevError();
2233
- init_serviceErrorHandler();
2234
- DEFAULT_ERROR_MESSAGES = {
2235
- 'already-exists': 'The resource already exists.',
2236
- cancelled: 'The operation was cancelled.',
2237
- 'deadline-exceeded': 'The operation timed out.',
2238
- internal: 'An internal error occurred.',
2239
- 'invalid-argument': 'Invalid argument provided.',
2240
- 'not-found': 'The requested resource was not found.',
2241
- 'permission-denied': 'You do not have permission to perform this action.',
2242
- 'rate-limit-exceeded': 'Too many requests. Please try again later.',
2243
- timeout: 'The operation timed out.',
2244
- unauthenticated: 'Authentication is required for this action.',
2245
- unavailable: 'The service is currently unavailable.',
2246
- unimplemented: 'This feature is not implemented.',
2247
- unknown: 'An unknown error occurred.',
2248
- 'validation-failed': 'Validation failed.',
2249
- };
2250
- HTTP_STATUS_CODE_MAPPING = {
2251
- 400: 'invalid-argument',
2252
- 401: 'unauthenticated',
2253
- 403: 'permission-denied',
2254
- 404: 'not-found',
2255
- 409: 'already-exists',
2256
- 422: 'validation-failed',
2257
- 429: 'rate-limit-exceeded',
2258
- 500: 'internal',
2259
- 501: 'unimplemented',
2260
- 502: 'unavailable',
2261
- 503: 'unavailable',
2262
- 504: 'timeout',
2263
- };
2264
- ENTITY_ERROR_MAPPING = {
2265
- INTERNAL_ERROR: 'internal',
2266
- VALIDATION_ERROR: 'validation-failed',
2267
- PERMISSION_DENIED: 'permission-denied',
2268
- NOT_FOUND: 'not-found',
2269
- ALREADY_EXISTS: 'already-exists',
2270
- NETWORK_ERROR: 'unavailable',
2271
- };
2272
- ERROR_HANDLERS = {
2273
- // Auth error configuration
2274
- auth: {
2275
- errorSource: 'auth',
2276
- defaultErrorCode: 'unknown',
2277
- defaultErrorMessage: 'An authentication error occurred',
2278
- errorCodeMapping: {
2279
- // Authentication errors
2280
- 'auth/user-not-found': 'not-found',
2281
- 'auth/wrong-password': 'invalid-argument',
2282
- 'auth/email-already-in-use': 'already-exists',
2283
- 'auth/weak-password': 'validation-failed',
2284
- 'auth/invalid-email': 'validation-failed',
2285
- 'auth/account-exists-with-different-credential': 'already-exists',
2286
- 'auth/credential-already-in-use': 'already-exists',
2287
- 'auth/requires-recent-login': 'unauthenticated',
2288
- 'auth/user-disabled': 'permission-denied',
2289
- 'auth/too-many-requests': 'rate-limit-exceeded',
2290
- 'auth/network-request-failed': 'unavailable',
2291
- 'auth/popup-blocked': 'unavailable',
2292
- 'auth/popup-closed-by-user': 'invalid-argument',
2293
- 'auth/cancelled-popup-request': 'invalid-argument',
2294
- 'auth/operation-not-allowed': 'unimplemented',
2295
- 'auth/invalid-credential': 'invalid-argument',
2296
- 'auth/invalid-verification-code': 'invalid-argument',
2297
- 'auth/captcha-check-failed': 'validation-failed',
2298
- 'auth/invalid-phone-number': 'validation-failed',
2299
- 'auth/missing-phone-number': 'invalid-argument',
2300
- 'auth/quota-exceeded': 'rate-limit-exceeded',
2301
- 'auth/timeout': 'unavailable',
2302
- 'auth/web-storage-unsupported': 'unavailable',
2303
- 'auth/unauthorized-domain': 'permission-denied',
2304
- 'auth/internal-error': 'internal',
2305
- 'auth/invalid-action-code': 'invalid-argument',
2306
- 'auth/invalid-continue-uri': 'invalid-argument',
2307
- 'auth/missing-continue-uri': 'invalid-argument',
2308
- 'auth/missing-ios-bundle-id': 'invalid-argument',
2309
- 'auth/missing-android-pkg-name': 'invalid-argument',
2310
- 'auth/unauthorized-continue-uri': 'permission-denied',
2311
- 'auth/invalid-dynamic-link-domain': 'invalid-argument',
2312
- 'auth/invalid-tenant-id': 'invalid-argument',
2313
- 'auth/tenant-id-mismatch': 'invalid-argument',
2314
- 'auth/provider-already-linked': 'already-exists',
2315
- 'auth/invalid-persistence-type': 'invalid-argument',
2316
- 'auth/unsupported-persistence-type': 'unimplemented',
2317
- 'auth/invalid-provider': 'invalid-argument',
2318
- 'auth/invalid-client-id': 'invalid-argument',
2319
- 'oauth/unauthorized-app': 'permission-denied',
2320
- 'auth/provider-not-enabled': 'unimplemented',
2321
- 'auth/unknown-provider': 'invalid-argument',
2322
- 'auth/missing-provider': 'invalid-argument',
2323
- 'auth/no-user-signed-in': 'unauthenticated',
2324
- // Include common Firebase error mappings
2325
- ...commonErrorCodeMappings,
2326
- },
2327
- friendlyMessageMapping: {
2328
- 'auth/user-not-found': 'No account found with this email address.',
2329
- 'auth/wrong-password': 'Incorrect password. Please try again.',
2330
- 'auth/email-already-in-use':
2331
- 'An account with this email already exists.',
2332
- 'auth/weak-password':
2333
- 'Password is too weak. It should be at least 6 characters.',
2334
- 'auth/invalid-email': 'Please enter a valid email address.',
2335
- 'auth/account-exists-with-different-credential':
2336
- 'An account already exists with the same email but different sign-in method.',
2337
- 'auth/credential-already-in-use':
2338
- 'This credential is already associated with a different user account.',
2339
- 'auth/requires-recent-login':
2340
- 'This operation requires you to sign in again for security reasons.',
2341
- 'auth/user-disabled': 'This account has been disabled.',
2342
- 'auth/too-many-requests':
2343
- 'Too many sign-in attempts. Please try again later.',
2344
- 'auth/network-request-failed':
2345
- 'Network connection error. Please check your internet connection.',
2346
- 'auth/popup-blocked':
2347
- 'Sign-in popup was blocked. Please allow popups for this site.',
2348
- 'auth/popup-closed-by-user':
2349
- 'Sign-in popup was closed before completion.',
2350
- 'auth/operation-not-allowed':
2351
- 'This sign-in method is not enabled for this project.',
2352
- 'auth/internal-error':
2353
- 'An internal authentication error occurred. Please try again.',
2354
- 'auth/invalid-action-code':
2355
- 'The action code is invalid. This can happen if the code is malformed, expired, or has already been used.',
2356
- 'auth/invalid-continue-uri': 'The continue URL provided is invalid.',
2357
- 'auth/missing-continue-uri':
2358
- 'A continue URL must be provided in the request.',
2359
- 'auth/missing-ios-bundle-id':
2360
- 'An iOS Bundle ID must be provided in the request.',
2361
- 'auth/missing-android-pkg-name':
2362
- 'An Android package name must be provided in the request.',
2363
- 'auth/unauthorized-continue-uri':
2364
- 'The domain of the continue URL is not allowlisted.',
2365
- 'auth/invalid-dynamic-link-domain':
2366
- 'The provided dynamic link domain is not authorized.',
2367
- 'auth/invalid-tenant-id': 'The provided tenant ID is invalid.',
2368
- 'auth/tenant-id-mismatch':
2369
- 'The tenant ID of the provider does not match the tenant ID of the current user.',
2370
- 'auth/provider-already-linked':
2371
- 'This authentication provider is already linked to the account.',
2372
- 'auth/invalid-persistence-type':
2373
- 'The specified persistence type is invalid.',
2374
- 'auth/unsupported-persistence-type':
2375
- 'The current environment does not support the specified persistence type.',
2376
- 'auth/invalid-provider':
2377
- 'The specified authentication provider is invalid.',
2378
- 'auth/invalid-client-id':
2379
- 'The authentication client ID provided is invalid.',
2380
- 'oauth/unauthorized-app':
2381
- 'This application is not authorized to use OAuth with the provided client ID.',
2382
- 'auth/provider-not-enabled':
2383
- 'This authentication provider is not enabled.',
2384
- 'auth/unknown-provider': 'Unknown authentication provider.',
2385
- 'auth/missing-provider':
2386
- 'No authentication provider specified in the request.',
2387
- 'auth/no-user-signed-in': 'No user is currently signed in.',
2388
- },
2389
- },
2390
- // OAuth error configuration
2391
- oauth: {
2392
- errorSource: 'oauth',
2393
- defaultErrorCode: 'unknown',
2394
- defaultErrorMessage: 'An OAuth error occurred',
2395
- errorCodeMapping: {
2396
- 'oauth/invalid-request': 'invalid-argument',
2397
- 'oauth/invalid-client': 'invalid-argument',
2398
- 'oauth/invalid-grant': 'invalid-argument',
2399
- 'oauth/unauthorized-client': 'permission-denied',
2400
- 'oauth/unsupported-grant-type': 'unimplemented',
2401
- 'oauth/invalid-scope': 'invalid-argument',
2402
- 'oauth/insufficient-scope': 'permission-denied',
2403
- 'oauth/invalid-token': 'unauthenticated',
2404
- 'oauth/expired-token': 'unauthenticated',
2405
- 'oauth/redirect-uri-mismatch': 'invalid-argument',
2406
- 'oauth/access-denied': 'permission-denied',
2407
- 'oauth/server-error': 'unavailable',
2408
- 'oauth/temporarily-unavailable': 'unavailable',
2409
- 'oauth/state-mismatch': 'invalid-argument',
2410
- 'oauth/invalid-callback': 'invalid-argument',
2411
- 'oauth/client-secret-mismatch': 'permission-denied',
2412
- 'oauth/unauthorized-scope': 'permission-denied',
2413
- 'oauth/rate-limit-exceeded': 'rate-limit-exceeded',
2414
- 'oauth/token-expired': 'unauthenticated',
2415
- 'oauth/missing-token': 'invalid-argument',
2416
- 'oauth/invalid-code': 'invalid-argument',
2417
- 'oauth/invalid-redirect': 'invalid-argument',
2418
- 'oauth/provider-error': 'unavailable',
2419
- 'oauth/invalid-response': 'unavailable',
2420
- 'oauth/unauthorized-access': 'permission-denied',
2421
- ...commonErrorCodeMappings,
2422
- },
2423
- friendlyMessageMapping: {
2424
- 'oauth/invalid-request':
2425
- 'The OAuth request was invalid or missing parameters.',
2426
- 'oauth/invalid-client': 'Client authentication failed.',
2427
- 'oauth/invalid-grant': 'The provided authorization grant is invalid.',
2428
- 'oauth/unauthorized-client':
2429
- 'The client is not authorized to use this grant type.',
2430
- 'oauth/unsupported-grant-type':
2431
- 'The requested grant type is not supported.',
2432
- 'oauth/invalid-scope': 'The requested scope is invalid or unknown.',
2433
- 'oauth/insufficient-scope':
2434
- 'The token does not have the required scope for this resource.',
2435
- 'oauth/invalid-token': 'The access token is invalid.',
2436
- 'oauth/expired-token': 'The access token has expired.',
2437
- 'oauth/redirect-uri-mismatch':
2438
- 'The redirect URI does not match the registered URI.',
2439
- 'oauth/access-denied': 'The resource owner denied the request.',
2440
- 'oauth/server-error':
2441
- 'The authorization server encountered an unexpected error.',
2442
- 'oauth/temporarily-unavailable':
2443
- 'The authorization server is temporarily unavailable.',
2444
- 'oauth/state-mismatch':
2445
- 'Invalid state parameter. This could be a security issue.',
2446
- 'oauth/invalid-callback':
2447
- 'The callback URL is invalid or not registered.',
2448
- 'oauth/client-secret-mismatch':
2449
- 'The client secret does not match the registered secret.',
2450
- 'oauth/unauthorized-scope':
2451
- 'The requested scope is not authorized for this client.',
2452
- 'oauth/rate-limit-exceeded':
2453
- 'Too many requests. Please try again later.',
2454
- 'oauth/token-expired':
2455
- 'The OAuth token has expired and needs to be refreshed.',
2456
- 'oauth/missing-token': 'No OAuth token was provided in the request.',
2457
- 'oauth/invalid-code': 'The authorization code is invalid or expired.',
2458
- 'oauth/invalid-redirect':
2459
- 'The redirect URL is invalid or does not match the registered redirect URL.',
2460
- 'oauth/provider-error': 'The OAuth provider returned an error.',
2461
- 'oauth/invalid-response':
2462
- 'The response from the OAuth provider was invalid.',
2463
- 'oauth/unauthorized-access':
2464
- 'Unauthorized access to OAuth resources.',
2465
- },
2466
- },
2467
- // API error configuration
2468
- api: {
2469
- errorSource: 'api',
2470
- defaultErrorCode: 'unknown',
2471
- defaultErrorMessage: 'API request failed',
2472
- // Convert HTTP status code mapping to string keys for the handler
2473
- errorCodeMapping: Object.fromEntries(
2474
- Object.entries(HTTP_STATUS_CODE_MAPPING).map(([key, value]) => [
2475
- key,
2476
- value,
2477
- ])
2478
- ),
2479
- friendlyMessageMapping: {},
2480
- // We'll use DEFAULT_ERROR_MESSAGES instead of duplicating
2481
- extractErrorCode: /* @__PURE__ */ __name((error) => {
2482
- if (typeof error !== 'object' || error === null) return void 0;
2483
- let statusCode;
2484
- if (
2485
- 'response' in error &&
2486
- error.response &&
2487
- 'status' in error.response
2488
- ) {
2489
- statusCode = error.response.status;
2490
- } else if ('status' in error && typeof error.status === 'number') {
2491
- statusCode = error.status;
2492
- }
2493
- return statusCode?.toString();
2494
- }, 'extractErrorCode'),
2495
- processMetadata: /* @__PURE__ */ __name((error) => {
2496
- const metadata = { originalError: error };
2497
- if (typeof error !== 'object' || error === null) return metadata;
2498
- if ('response' in error && error.response) {
2499
- if ('status' in error.response) {
2500
- metadata.statusCode = error.response.status;
2501
- }
2502
- if ('data' in error.response) {
2503
- metadata.responseData = error.response.data;
2504
- }
2505
- } else if ('status' in error) {
2506
- metadata.statusCode = error.status;
2507
- }
2508
- return metadata;
2509
- }, 'processMetadata'),
2510
- },
2511
- // Firebase error configuration
2512
- firebase: {
2513
- errorSource: 'firebase',
2514
- defaultErrorCode: 'unknown',
2515
- defaultErrorMessage: 'A Firebase error occurred',
2516
- errorCodeMapping: commonErrorCodeMappings,
2517
- friendlyMessageMapping: {},
2518
- // Use default messages
2519
- },
2520
- // UI error configuration
2521
- ui: {
2522
- errorSource: 'ui',
2523
- defaultErrorCode: 'internal',
2524
- defaultErrorMessage: DEFAULT_ERROR_MESSAGES['internal'],
2525
- errorCodeMapping: {},
2526
- friendlyMessageMapping: {},
2527
- processMetadata: /* @__PURE__ */ __name((error) => {
2528
- const metadata = { originalError: error };
2529
- if (
2530
- typeof error === 'object' &&
2531
- error !== null &&
2532
- 'componentStack' in error
2533
- ) {
2534
- metadata.componentStack = error.componentStack;
2535
- }
2536
- return metadata;
2537
- }, 'processMetadata'),
2538
- },
2539
- // Validation error configuration - used only as fallback,
2540
- // as validation errors have specialized handling
2541
- validation: {
2542
- errorSource: 'validation',
2543
- defaultErrorCode: 'validation-failed',
2544
- defaultErrorMessage: DEFAULT_ERROR_MESSAGES['validation-failed'],
2545
- errorCodeMapping: {},
2546
- friendlyMessageMapping: {},
2547
- },
2548
- // Entity error configuration - used only as fallback,
2549
- // as entity errors have specialized handling
2550
- entity: {
2551
- errorSource: 'entity',
2552
- defaultErrorCode: 'unknown',
2553
- defaultErrorMessage: 'An entity operation error occurred',
2554
- errorCodeMapping: {},
2555
- friendlyMessageMapping: {},
2556
- },
2557
- // Unknown error configuration
2558
- unknown: {
2559
- errorSource: 'unknown',
2560
- defaultErrorCode: 'unknown',
2561
- defaultErrorMessage: DEFAULT_ERROR_MESSAGES['unknown'],
2562
- errorCodeMapping: {
2563
- TypeError: 'invalid-argument',
2564
- ReferenceError: 'internal',
2565
- RangeError: 'invalid-argument',
2566
- },
2567
- friendlyMessageMapping: {},
2568
- extractErrorCode: /* @__PURE__ */ __name((error) => {
2569
- if (error instanceof Error) {
2570
- return error.name;
2571
- }
2572
- return void 0;
2573
- }, 'extractErrorCode'),
2574
- },
2575
- };
2576
- handleValidationError = /* @__PURE__ */ __name((error) => {
2577
- if (!(error instanceof ValiError)) {
2578
- return createErrorHandler(ERROR_HANDLERS.validation)(error);
2579
- }
2580
- return new DoNotDevError(
2581
- DEFAULT_ERROR_MESSAGES['validation-failed'],
2582
- 'validation-failed',
2583
- {
2584
- details: {
2585
- validationErrors: error.issues.map((e) => ({
2586
- path: e.path.join('.'),
2587
- message: e.message,
2588
- })),
2589
- originalError: error,
2590
- },
2591
- source: 'validation',
2592
- }
2593
- );
2594
- }, 'handleValidationError');
2595
- handleEntityError = /* @__PURE__ */ __name((error) => {
2596
- if (
2597
- error instanceof Error &&
2598
- 'type' in error &&
2599
- typeof error.type === 'string' &&
2600
- error.type in ENTITY_ERROR_MAPPING
2601
- ) {
2602
- const entityError = error;
2603
- const errorCode = ENTITY_ERROR_MAPPING[entityError.type] || 'unknown';
2604
- return new DoNotDevError(
2605
- entityError.message || DEFAULT_ERROR_MESSAGES[errorCode],
2606
- errorCode,
2607
- {
2608
- details: { originalError: error },
2609
- source: 'entity',
2610
- }
2611
- );
2612
- }
2613
- if (
2614
- typeof error === 'object' &&
2615
- error !== null &&
2616
- 'code' in error &&
2617
- typeof error.code === 'string' &&
2618
- FIREBASE_ERROR_MAP[error.code]
2619
- ) {
2620
- const firebaseError = error;
2621
- const mappedError = FIREBASE_ERROR_MAP[firebaseError.code];
2622
- if (mappedError) {
2623
- const errorCode = ENTITY_ERROR_MAPPING[mappedError.type] || 'unknown';
2624
- return new DoNotDevError(
2625
- mappedError.message || DEFAULT_ERROR_MESSAGES[errorCode],
2626
- errorCode,
2627
- {
2628
- details: {
2629
- originalCode: firebaseError.code,
2630
- originalError: error,
2631
- },
2632
- source: 'entity',
2633
- }
2634
- );
2635
- }
2636
- }
2637
- return createErrorHandler(ERROR_HANDLERS.entity)(error);
2638
- }, 'handleEntityError');
2639
- ERROR_HANDLER_REGISTRY = {
2640
- auth: createErrorHandler(ERROR_HANDLERS.auth),
2641
- oauth: createErrorHandler(ERROR_HANDLERS.oauth),
2642
- api: createErrorHandler(ERROR_HANDLERS.api),
2643
- firebase: createErrorHandler(ERROR_HANDLERS.firebase),
2644
- ui: createErrorHandler(ERROR_HANDLERS.ui),
2645
- validation: handleValidationError,
2646
- // Use specialized handler
2647
- entity: handleEntityError,
2648
- // Use specialized handler
2649
- unknown: createErrorHandler(ERROR_HANDLERS.unknown),
2650
- };
2651
- __name(mapToDoNotDevError, 'mapToDoNotDevError');
2652
- },
2653
- });
2654
-
2655
- // ../core/utils/src/common/errors/internal/sentryCapture.ts
2656
- function captureErrorToSentry(error, source, context = {}) {
2657
- const Sentry = globalThis.Sentry;
2658
- if (!Sentry) {
2659
- return;
2660
- }
2661
- Sentry.withScope((scope) => {
2662
- scope.setTag('errorSource', source);
2663
- scope.setTag('errorCode', error.code);
2664
- if (error.details) {
2665
- Object.entries(error.details).forEach(([key, value]) => {
2666
- if (typeof value !== 'function' && key !== 'originalError') {
2667
- try {
2668
- scope.setExtra(key, value);
2669
- } catch (e) {
2670
- scope.setExtra(key, `[${typeof value}]`);
2671
- }
2672
- }
2673
- });
2674
- }
2675
- Object.entries(context).forEach(([key, value]) => {
2676
- if (typeof value !== 'function') {
2677
- try {
2678
- scope.setExtra(`context.${key}`, value);
2679
- } catch (e) {
2680
- scope.setExtra(`context.${key}`, `[${typeof value}]`);
2681
- }
2682
- }
2683
- });
2684
- if (error.details?.userId || context.userId) {
2685
- scope.setUser({
2686
- id: error.details?.userId || context.userId,
2687
- email: error.details?.userEmail || context.userEmail,
2688
- });
2689
- }
2690
- Sentry.captureException(error);
2691
- });
2692
- }
2693
- var init_sentryCapture = __esm({
2694
- '../core/utils/src/common/errors/internal/sentryCapture.ts'() {
2695
- 'use strict';
2696
- init_doNotDevError();
2697
- __name(captureErrorToSentry, 'captureErrorToSentry');
2698
- },
2699
- });
2700
-
2701
- // ../core/utils/src/common/errors/handleError.ts
2702
- function isDev() {
2703
- if (typeof import.meta !== 'undefined' && import.meta.env) {
2704
- if (import.meta.env.DEV === true) {
2705
- return true;
2706
- }
2707
- if (import.meta.env.MODE && import.meta.env.MODE !== 'production') {
2708
- return true;
2709
- }
2710
- }
2711
- if (typeof process !== 'undefined' && process.env) {
2712
- const env = 'production'.toLowerCase();
2713
- return env !== 'production';
2714
- }
2715
- return true;
2716
- }
2717
- function handleError(error, optionsOrMessage) {
2718
- const options =
2719
- typeof optionsOrMessage === 'string'
2720
- ? { userMessage: optionsOrMessage }
2721
- : optionsOrMessage || {};
2722
- const {
2723
- userMessage,
2724
- context = {},
2725
- log = true,
2726
- reportToSentry = true,
2727
- showNotification = false,
2728
- severity = 'error',
2729
- } = options;
2730
- const errorSource = detectErrorSource(error);
2731
- let standardError =
2732
- error instanceof DoNotDevError
2733
- ? error
2734
- : mapToDoNotDevError(error, errorSource, userMessage);
2735
- if (userMessage && !standardError.userMessageProvided) {
2736
- const isGenericMessage =
2737
- standardError.message.includes('Error') ||
2738
- standardError.message.includes('Failed') ||
2739
- standardError.message.length < 10;
2740
- if (isGenericMessage) {
2741
- standardError = new DoNotDevError(userMessage, standardError.code, {
2742
- details: {
2743
- ...standardError.details,
2744
- originalMessage: standardError.message,
2745
- },
2746
- source: errorSource,
2747
- userMessageProvided: true,
2748
- });
2749
- } else {
2750
- standardError = new DoNotDevError(
2751
- standardError.message,
2752
- standardError.code,
2753
- {
2754
- details: {
2755
- ...standardError.details,
2756
- userMessage,
2757
- },
2758
- source: errorSource,
2759
- userMessageProvided: true,
2760
- }
2761
- );
2762
- }
2763
- }
2764
- if (log) {
2765
- const isDevelopment =
2766
- isDev() || (typeof window !== 'undefined' && window.__DNDEV_DEBUG);
2767
- const logInfo = {
2768
- code: standardError.code,
2769
- message: standardError.message,
2770
- source: errorSource,
2771
- };
2772
- switch (severity) {
2773
- case 'warning':
2774
- console.warn(
2775
- `[DoNotDev] ${standardError.code}: ${standardError.message}`,
2776
- isDevelopment
2777
- ? { ...logInfo, details: standardError.details }
2778
- : logInfo
2779
- );
2780
- break;
2781
- case 'info':
2782
- console.info(
2783
- `[DoNotDev] ${standardError.code}: ${standardError.message}`,
2784
- isDevelopment
2785
- ? { ...logInfo, details: standardError.details }
2786
- : logInfo
2787
- );
2788
- break;
2789
- case 'success':
2790
- console.log(
2791
- `[DoNotDev] ${standardError.code}: ${standardError.message}`,
2792
- isDevelopment
2793
- ? { ...logInfo, details: standardError.details }
2794
- : logInfo
2795
- );
2796
- break;
2797
- case 'error':
2798
- default:
2799
- console.error(
2800
- `[DoNotDev] ${standardError.code}: ${standardError.message}`,
2801
- isDevelopment
2802
- ? {
2803
- ...logInfo,
2804
- details: standardError.details,
2805
- stack: standardError.stack,
2806
- }
2807
- : logInfo
2808
- );
2809
- }
2810
- }
2811
- if (reportToSentry) {
2812
- captureErrorToSentry(standardError, errorSource, context);
2813
- }
2814
- if (showNotification && typeof window !== 'undefined') {
2815
- console.warn(
2816
- '[handleError] showNotification requires client-side toast setup'
2817
- );
2818
- }
2819
- return standardError;
2820
- }
2821
- var init_handleError = __esm({
2822
- '../core/utils/src/common/errors/handleError.ts'() {
2823
- 'use strict';
2824
- init_doNotDevError();
2825
- init_errorDetection();
2826
- init_errorMapper();
2827
- init_sentryCapture();
2828
- __name(isDev, 'isDev');
2829
- __name(handleError, 'handleError');
2830
- },
2831
- });
2832
-
2833
- // ../core/utils/src/common/errors/index.ts
2834
- var init_errors2 = __esm({
2835
- '../core/utils/src/common/errors/index.ts'() {
2836
- 'use strict';
2837
- init_doNotDevError();
2838
- init_handleError();
2839
- init_errorDetection();
2840
- init_errorMapper();
2841
- init_sentryCapture();
2842
- init_serviceErrorHandler();
2843
- },
2844
- });
2845
-
2846
- // ../core/utils/src/common/maybeTranslate.ts
2847
- var init_maybeTranslate = __esm({
2848
- '../core/utils/src/common/maybeTranslate.ts'() {
2849
- 'use strict';
2850
- },
2851
- });
2852
-
2853
- // ../core/utils/src/common/pkce.ts
2854
- var init_pkce = __esm({
2855
- '../core/utils/src/common/pkce.ts'() {
2856
- 'use strict';
2857
- },
2858
- });
2859
-
2860
- // ../core/utils/src/common/gracefulInit.ts
2861
- var init_gracefulInit = __esm({
2862
- '../core/utils/src/common/gracefulInit.ts'() {
2863
- 'use strict';
2864
- },
2865
- });
2866
-
2867
- // ../core/utils/src/common/lazyImport.ts
2868
- var init_lazyImport = __esm({
2869
- '../core/utils/src/common/lazyImport.ts'() {
2870
- 'use strict';
2871
- },
2872
- });
2873
-
2874
- // ../core/utils/src/common/roleHierarchy.ts
2875
- var ROLE_HIERARCHY;
2876
- var init_roleHierarchy = __esm({
2877
- '../core/utils/src/common/roleHierarchy.ts'() {
2878
- 'use strict';
2879
- init_src();
2880
- ROLE_HIERARCHY = {
2881
- [USER_ROLES.GUEST]: 0,
2882
- [USER_ROLES.USER]: 1,
2883
- [USER_ROLES.ADMIN]: 2,
2884
- [USER_ROLES.SUPER]: 3,
2885
- };
2886
- },
2887
- });
2888
-
2889
- // ../core/utils/src/common/tierHierarchy.ts
2890
- var init_tierHierarchy = __esm({
2891
- '../core/utils/src/common/tierHierarchy.ts'() {
2892
- 'use strict';
2893
- init_src();
2894
- },
2895
- });
2896
-
2897
- // ../core/utils/src/common/singleton.ts
2898
- function createSingleton(ClassOrFactory, ...args) {
2899
- let instance = null;
2900
- let isInitializing = false;
2901
- return /* @__PURE__ */ __name(function getInstance() {
2902
- if (instance !== null) {
2903
- return instance;
2904
- }
2905
- if (isInitializing) {
2906
- throw new Error(
2907
- 'Circular dependency detected in singleton initialization'
2908
- );
2909
- }
2910
- isInitializing = true;
2911
- try {
2912
- if (typeof ClassOrFactory === 'function' && ClassOrFactory.prototype) {
2913
- instance = new ClassOrFactory(...args);
2914
- } else {
2915
- instance = ClassOrFactory();
2916
- }
2917
- return instance;
2918
- } finally {
2919
- isInitializing = false;
2920
- }
2921
- }, 'getInstance');
2922
- }
2923
- var init_singleton = __esm({
2924
- '../core/utils/src/common/singleton.ts'() {
2925
- 'use strict';
2926
- __name(createSingleton, 'createSingleton');
2927
- },
2928
- });
2929
-
2930
- // ../core/utils/src/common/updateMetadata.ts
2931
- var init_updateMetadata = __esm({
2932
- '../core/utils/src/common/updateMetadata.ts'() {
2933
- 'use strict';
2934
- },
2935
- });
2936
-
2937
- // ../core/utils/src/common/schema/getVisibleFields.ts
2938
- var init_getVisibleFields = __esm({
2939
- '../core/utils/src/common/schema/getVisibleFields.ts'() {
2940
- 'use strict';
2941
- init_roleHierarchy();
2942
- },
2943
- });
2944
-
2945
- // ../core/utils/src/common/schema/filterVisibleFields.ts
2946
- var init_filterVisibleFields = __esm({
2947
- '../core/utils/src/common/schema/filterVisibleFields.ts'() {
2948
- 'use strict';
2949
- init_getVisibleFields();
2950
- },
2951
- });
2952
-
2953
- // ../core/utils/src/common/schema/index.ts
2954
- var init_schema = __esm({
2955
- '../core/utils/src/common/schema/index.ts'() {
2956
- 'use strict';
2957
- init_filterVisibleFields();
2958
- init_getVisibleFields();
2959
- },
2960
- });
2961
-
2962
- // ../core/utils/src/common/index.ts
2963
- var init_common2 = __esm({
2964
- '../core/utils/src/common/index.ts'() {
2965
- 'use strict';
2966
- init_arrayTranslations();
2967
- init_createMetadata();
2968
- init_dateUtils();
2969
- init_errors2();
2970
- init_maybeTranslate();
2971
- init_pkce();
2972
- init_gracefulInit();
2973
- init_lazyImport();
2974
- init_roleHierarchy();
2975
- init_tierHierarchy();
2976
- init_singleton();
2977
- init_updateMetadata();
2978
- init_schema();
2979
- },
2980
- });
2981
-
2982
- // ../core/utils/src/server/dateUtils.ts
2983
- var init_dateUtils2 = __esm({
2984
- '../core/utils/src/server/dateUtils.ts'() {
2985
- 'use strict';
2986
- },
2987
- });
2988
-
2989
- // ../core/utils/src/server/validation.ts
2990
- var init_validation = __esm({
2991
- '../core/utils/src/server/validation.ts'() {
2992
- 'use strict';
2993
- },
2994
- });
2995
-
2996
- // ../core/utils/src/server/cookieUtils.ts
2997
- var init_cookieUtils = __esm({
2998
- '../core/utils/src/server/cookieUtils.ts'() {
2999
- 'use strict';
3000
- },
3001
- });
3002
-
3003
- // ../core/utils/src/server/index.ts
3004
- var init_server = __esm({
3005
- '../core/utils/src/server/index.ts'() {
3006
- init_common2();
3007
- init_dateUtils2();
3008
- init_validation();
3009
- init_cookieUtils();
3010
- },
3011
- });
3012
-
3013
- // ../core/schemas/src/common/validation/enhanceSchema.ts
3014
- var init_enhanceSchema = __esm({
3015
- '../core/schemas/src/common/validation/enhanceSchema.ts'() {
3016
- 'use strict';
3017
- },
3018
- });
3019
-
3020
- // ../core/schemas/src/common/validation/getSchemaType.ts
3021
- function registerSchemaGenerator(type, generator) {
3022
- schemaRegistry.set(type, generator);
3023
- }
3024
- function registerBuiltinSchemas() {
3025
- registerSchemaGenerator('text', textSchema);
3026
- registerSchemaGenerator('textarea', textSchema);
3027
- registerSchemaGenerator('richtext', textSchema);
3028
- registerSchemaGenerator('color', textSchema);
3029
- registerSchemaGenerator('email', emailSchema);
3030
- registerSchemaGenerator('password', passwordSchema);
3031
- registerSchemaGenerator('url', urlSchema);
3032
- registerSchemaGenerator('tel', telSchema);
3033
- registerSchemaGenerator('number', numberSchema);
3034
- registerSchemaGenerator('range', numberSchema);
3035
- registerSchemaGenerator('boolean', booleanSchema);
3036
- registerSchemaGenerator('checkbox', booleanSchema);
3037
- registerSchemaGenerator('date', dateSchema);
3038
- registerSchemaGenerator('datetime-local', dateSchema);
3039
- registerSchemaGenerator('time', dateSchema);
3040
- registerSchemaGenerator('week', dateSchema);
3041
- registerSchemaGenerator('month', dateSchema);
3042
- registerSchemaGenerator('timestamp', dateSchema);
3043
- registerSchemaGenerator('file', fileSchema);
3044
- registerSchemaGenerator('files', filesSchema);
3045
- registerSchemaGenerator('document', fileSchema);
3046
- registerSchemaGenerator('documents', filesSchema);
3047
- registerSchemaGenerator('image', pictureSchema);
3048
- registerSchemaGenerator('images', picturesSchema);
3049
- registerSchemaGenerator('geopoint', geopointSchema);
3050
- registerSchemaGenerator('address', addressSchema);
3051
- registerSchemaGenerator('map', mapSchema);
3052
- registerSchemaGenerator('array', arraySchema);
3053
- registerSchemaGenerator('select', selectSchema);
3054
- registerSchemaGenerator('multiselect', multiselectSchema);
3055
- registerSchemaGenerator('radio', selectSchema);
3056
- registerSchemaGenerator('reference', referenceSchema);
3057
- registerSchemaGenerator('hidden', stringSchema);
3058
- registerSchemaGenerator('avatar', stringSchema);
3059
- registerSchemaGenerator('badge', stringSchema);
3060
- registerSchemaGenerator('submit', neverSchema);
3061
- registerSchemaGenerator('reset', neverSchema);
3062
- }
3063
- var schemaRegistry,
3064
- textSchema,
3065
- emailSchema,
3066
- passwordSchema,
3067
- urlSchema,
3068
- numberSchema,
3069
- booleanSchema,
3070
- dateSchema,
3071
- fileAssetObjectSchema,
3072
- fileSchema,
3073
- filesSchema,
3074
- pictureObjectSchema,
3075
- pictureSchema,
3076
- picturesSchema,
3077
- geopointSchema,
3078
- addressSchema,
3079
- mapSchema,
3080
- arraySchema,
3081
- selectSchema,
3082
- multiselectSchema,
3083
- referenceSchema,
3084
- stringSchema,
3085
- telSchema,
3086
- neverSchema;
3087
- var init_getSchemaType = __esm({
3088
- '../core/schemas/src/common/validation/getSchemaType.ts'() {
3089
- 'use strict';
3090
- init_dist();
3091
- init_src();
3092
- schemaRegistry = /* @__PURE__ */ new Map();
3093
- __name(registerSchemaGenerator, 'registerSchemaGenerator');
3094
- textSchema = /* @__PURE__ */ __name((field) => {
3095
- const validations = [];
3096
- if (field.validation?.minLength !== void 0) {
3097
- validations.push(
3098
- minLength(
3099
- field.validation.minLength,
3100
- `Must be at least ${field.validation.minLength} characters`
3101
- )
3102
- );
3103
- }
3104
- if (field.validation?.maxLength !== void 0) {
3105
- validations.push(
3106
- maxLength(
3107
- field.validation.maxLength,
3108
- `Must be at most ${field.validation.maxLength} characters`
3109
- )
3110
- );
3111
- }
3112
- if (field.validation?.pattern) {
3113
- validations.push(
3114
- regex(new RegExp(field.validation.pattern), 'Invalid format')
3115
- );
3116
- }
3117
- const schema =
3118
- validations.length > 0 ? pipe(string(), ...validations) : string();
3119
- return field.validation?.required ? schema : optional(schema);
3120
- }, 'textSchema');
3121
- emailSchema = /* @__PURE__ */ __name((field) => {
3122
- const schema = pipe(string(), email('Invalid email address'));
3123
- return field.validation?.required ? schema : optional(schema);
3124
- }, 'emailSchema');
3125
- passwordSchema = /* @__PURE__ */ __name((field) => {
3126
- const schema =
3127
- field.validation?.minLength !== void 0
3128
- ? pipe(
3129
- string(),
3130
- minLength(
3131
- field.validation.minLength,
3132
- `Must be at least ${field.validation.minLength} characters`
3133
- )
3134
- )
3135
- : string();
3136
- return field.validation?.required ? schema : optional(schema);
3137
- }, 'passwordSchema');
3138
- urlSchema = /* @__PURE__ */ __name((field) => {
3139
- const schema = pipe(string(), url('Invalid URL'));
3140
- return field.validation?.required ? schema : optional(schema);
3141
- }, 'urlSchema');
3142
- numberSchema = /* @__PURE__ */ __name((field) => {
3143
- const validations = [];
3144
- if (field.validation?.min !== void 0) {
3145
- validations.push(
3146
- minValue(
3147
- field.validation.min,
3148
- `Must be at least ${field.validation.min}`
3149
- )
3150
- );
3151
- }
3152
- if (field.validation?.max !== void 0) {
3153
- validations.push(
3154
- maxValue(
3155
- field.validation.max,
3156
- `Must be at most ${field.validation.max}`
3157
- )
3158
- );
3159
- }
3160
- const schema =
3161
- validations.length > 0 ? pipe(number(), ...validations) : number();
3162
- return field.validation?.required ? schema : optional(schema);
3163
- }, 'numberSchema');
3164
- booleanSchema = /* @__PURE__ */ __name((field) => {
3165
- const schema = boolean();
3166
- return field.validation?.required ? schema : optional(schema);
3167
- }, 'booleanSchema');
3168
- dateSchema = /* @__PURE__ */ __name((field) => {
3169
- const schema = pipe(string(), isoTimestamp('Invalid date format'));
3170
- return field.validation?.required ? schema : optional(schema);
3171
- }, 'dateSchema');
3172
- fileAssetObjectSchema = object({
3173
- url: string(),
3174
- filename: string(),
3175
- size: number(),
3176
- mimeType: optional(string()),
3177
- uploadedAt: optional(string()),
3178
- });
3179
- fileSchema = /* @__PURE__ */ __name((field) => {
3180
- const schema = nullable(fileAssetObjectSchema);
3181
- return field.validation?.required ? schema : optional(schema);
3182
- }, 'fileSchema');
3183
- filesSchema = /* @__PURE__ */ __name((field) => {
3184
- const schema = array(fileAssetObjectSchema);
3185
- return field.validation?.required ? schema : optional(schema);
3186
- }, 'filesSchema');
3187
- pictureObjectSchema = object({
3188
- fullUrl: string(),
3189
- thumbUrl: string(),
3190
- });
3191
- pictureSchema = /* @__PURE__ */ __name((field) => {
3192
- const schema = pictureObjectSchema;
3193
- return field.validation?.required ? schema : optional(schema);
3194
- }, 'pictureSchema');
3195
- picturesSchema = /* @__PURE__ */ __name((field) => {
3196
- const schema = array(pictureObjectSchema);
3197
- return field.validation?.required ? schema : optional(schema);
3198
- }, 'picturesSchema');
3199
- geopointSchema = /* @__PURE__ */ __name((field) => {
3200
- const schema = object({ lat: number(), lng: number() });
3201
- return field.validation?.required ? schema : optional(schema);
3202
- }, 'geopointSchema');
3203
- addressSchema = /* @__PURE__ */ __name((field) => {
3204
- const schema = object({
3205
- formatted_address: string(),
3206
- latitude: number(),
3207
- longitude: number(),
3208
- street_number: optional(string()),
3209
- route: optional(string()),
3210
- locality: optional(string()),
3211
- administrative_area_level_1: optional(string()),
3212
- administrative_area_level_2: optional(string()),
3213
- country: optional(string()),
3214
- postal_code: optional(string()),
3215
- });
3216
- return field.validation?.required ? schema : optional(schema);
3217
- }, 'addressSchema');
3218
- mapSchema = /* @__PURE__ */ __name((field) => {
3219
- const schema = record(string(), unknown());
3220
- return field.validation?.required ? schema : optional(schema);
3221
- }, 'mapSchema');
3222
- arraySchema = /* @__PURE__ */ __name((field) => {
3223
- const schema = array(unknown());
3224
- return field.validation?.required ? schema : optional(schema);
3225
- }, 'arraySchema');
3226
- selectSchema = /* @__PURE__ */ __name((field) => {
3227
- const options = field.validation?.options;
3228
- if (Array.isArray(options) && options.length > 0) {
3229
- const values = options.map((opt) => opt.value);
3230
- const schema2 = picklist(values);
3231
- return field.validation?.required ? schema2 : optional(schema2);
3232
- }
3233
- const schema = string();
3234
- return field.validation?.required ? schema : optional(schema);
3235
- }, 'selectSchema');
3236
- multiselectSchema = /* @__PURE__ */ __name((field) => {
3237
- const options = field.validation?.options;
3238
- if (Array.isArray(options) && options.length > 0) {
3239
- const values = options.map((opt) => opt.value);
3240
- const schema2 = array(picklist(values));
3241
- return field.validation?.required ? schema2 : optional(schema2);
3242
- }
3243
- const schema = array(string());
3244
- return field.validation?.required ? schema : optional(schema);
3245
- }, 'multiselectSchema');
3246
- referenceSchema = /* @__PURE__ */ __name((field) => {
3247
- const schema = pipe(
3248
- string(),
3249
- regex(FIRESTORE_ID_PATTERN, 'Invalid ID format')
3250
- );
3251
- return field.validation?.required ? schema : optional(schema);
3252
- }, 'referenceSchema');
3253
- stringSchema = /* @__PURE__ */ __name((field) => {
3254
- const schema = string();
3255
- return field.validation?.required ? schema : optional(schema);
3256
- }, 'stringSchema');
3257
- telSchema = /* @__PURE__ */ __name((field) => {
3258
- const schema = string();
3259
- return field.validation?.required ? schema : optional(schema);
3260
- }, 'telSchema');
3261
- neverSchema = /* @__PURE__ */ __name(() => never(), 'neverSchema');
3262
- __name(registerBuiltinSchemas, 'registerBuiltinSchemas');
3263
- registerBuiltinSchemas();
3264
- },
3265
- });
3266
-
3267
- // ../core/schemas/src/common/validation/validateDates.ts
3268
- var init_validateDates = __esm({
3269
- '../core/schemas/src/common/validation/validateDates.ts'() {
3270
- 'use strict';
3271
- init_server();
3272
- },
3273
- });
3274
-
3275
- // ../core/schemas/src/common/validation/validateUniqueFields.ts
3276
- var init_validateUniqueFields = __esm({
3277
- '../core/schemas/src/common/validation/validateUniqueFields.ts'() {
3278
- 'use strict';
3279
- init_server();
3280
- },
3281
- });
3282
-
3283
- // ../core/schemas/src/common/validation/validateDocument.ts
3284
- var init_validateDocument = __esm({
3285
- '../core/schemas/src/common/validation/validateDocument.ts'() {
3286
- 'use strict';
3287
- init_validateDates();
3288
- init_validateUniqueFields();
3289
- },
3290
- });
3291
-
3292
- // ../core/schemas/src/common/validation/index.ts
3293
- var init_validation2 = __esm({
3294
- '../core/schemas/src/common/validation/index.ts'() {
3295
- 'use strict';
3296
- init_enhanceSchema();
3297
- init_getSchemaType();
3298
- init_validateDates();
3299
- init_validateDocument();
3300
- init_validateUniqueFields();
3301
- },
3302
- });
3303
-
3304
- // ../core/schemas/src/common/utils.ts
3305
- var init_utils2 = __esm({
3306
- '../core/schemas/src/common/utils.ts'() {
3307
- 'use strict';
3308
- init_server();
3309
- },
3310
- });
3311
-
3312
- // ../core/schemas/src/common/visibility.ts
3313
- var DEFAULT_STATUS_OPTIONS,
3314
- BACKEND_GENERATED_FIELD_NAMES,
3315
- TECHNICAL_FIELD_NAMES,
3316
- baseFields;
3317
- var init_visibility = __esm({
3318
- '../core/schemas/src/common/visibility.ts'() {
3319
- 'use strict';
3320
- init_src();
3321
- DEFAULT_STATUS_OPTIONS = [
3322
- { value: 'draft', label: 'dndev:status.draft' },
3323
- { value: 'available', label: 'dndev:status.available' },
3324
- { value: 'deleted', label: 'dndev:status.deleted' },
3325
- ];
3326
- BACKEND_GENERATED_FIELD_NAMES = [
3327
- 'id',
3328
- // Firestore auto-generates document ID
3329
- 'createdAt',
3330
- // Server sets creation timestamp
3331
- 'updatedAt',
3332
- // Server sets update timestamp
3333
- 'createdById',
3334
- // Server extracts from auth context
3335
- 'updatedById',
3336
- // Server extracts from auth context
3337
- ];
3338
- TECHNICAL_FIELD_NAMES = [
3339
- ...BACKEND_GENERATED_FIELD_NAMES,
3340
- 'status',
3341
- // Framework-enforced, user-settable (NOT backend-generated)
3342
- ];
3343
- baseFields = {
3344
- id: {
3345
- type: 'text',
3346
- visibility: 'technical',
3347
- validation: {
3348
- required: true,
3349
- pattern: FIRESTORE_ID_PATTERN.source,
3350
- },
3351
- },
3352
- createdAt: {
3353
- type: 'timestamp',
3354
- visibility: 'technical',
3355
- validation: { required: true },
3356
- },
3357
- updatedAt: {
3358
- type: 'timestamp',
3359
- visibility: 'technical',
3360
- validation: { required: true },
3361
- },
3362
- createdById: {
3363
- type: 'reference',
3364
- visibility: 'technical',
3365
- validation: { required: true },
3366
- },
3367
- updatedById: {
3368
- type: 'reference',
3369
- visibility: 'technical',
3370
- validation: { required: true },
3371
- },
3372
- status: {
3373
- type: 'select',
3374
- visibility: 'admin',
3375
- editable: 'admin',
3376
- // REQUIRED: Status must be editable to be included in forms
3377
- validation: {
3378
- required: true,
3379
- options: [...DEFAULT_STATUS_OPTIONS],
3380
- },
3381
- },
3382
- };
3383
- },
3384
- });
3385
-
3386
- // ../core/schemas/src/common/defineEntity.ts
3387
- var init_defineEntity = __esm({
3388
- '../core/schemas/src/common/defineEntity.ts'() {
3389
- 'use strict';
3390
- init_server();
3391
- init_visibility();
3392
- },
3393
- });
3394
-
3395
- // ../core/schemas/src/common/createSchema.ts
3396
- var init_createSchema = __esm({
3397
- '../core/schemas/src/common/createSchema.ts'() {
3398
- 'use strict';
3399
- init_src();
3400
- init_getSchemaType();
3401
- init_visibility();
3402
- },
3403
- });
3404
-
3405
- // ../core/schemas/src/common/index.ts
3406
- var init_common3 = __esm({
3407
- '../core/schemas/src/common/index.ts'() {
3408
- 'use strict';
3409
- init_validation2();
3410
- init_utils2();
3411
- init_visibility();
3412
- init_defineEntity();
3413
- init_createSchema();
3414
- },
3415
- });
3416
-
3417
- // ../core/schemas/src/server/index.ts
3418
- var init_server2 = __esm({
3419
- '../core/schemas/src/server/index.ts'() {
3420
- init_common3();
3421
- },
3422
- });
3423
-
3424
- // ../core/server.ts
3425
- var init_server3 = __esm({
3426
- '../core/server.ts'() {
3427
- init_server();
3428
- init_src();
3429
- init_server2();
3430
- init_server();
3431
- },
3432
- });
3433
-
3434
- // ../providers/firebase/src/server/init.ts
3435
- import { initializeApp, getApps, cert } from 'firebase-admin/app';
3436
- import { getAuth } from 'firebase-admin/auth';
3437
- import { getFirestore } from 'firebase-admin/firestore';
3438
- import { getFunctions } from 'firebase-admin/functions';
3439
- function initializeFirebaseAdminServices() {
3440
- const existingApps = getApps();
3441
- let app = null;
3442
- if (existingApps.length === 0) {
3443
- const isVercelEnv =
3444
- process.env.FIREBASE_ADMIN_PRIVATE_KEY &&
3445
- process.env.FIREBASE_PROJECT_ID &&
3446
- process.env.FIREBASE_CLIENT_EMAIL;
3447
- if (isVercelEnv) {
3448
- app = initializeApp({
3449
- credential: cert({
3450
- projectId: process.env.FIREBASE_PROJECT_ID,
3451
- clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
3452
- privateKey: process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(
3453
- /\\n/g,
3454
- '\n'
3455
- ),
3456
- }),
3457
- projectId: process.env.FIREBASE_PROJECT_ID,
3458
- });
3459
- } else {
3460
- app = initializeApp();
3461
- }
3462
- } else {
3463
- app = existingApps[0] || null;
3464
- }
3465
- if (!app) {
3466
- throw new Error('Failed to initialize Firebase Admin app');
3467
- }
3468
- return {
3469
- app,
3470
- auth: getAuth(app),
3471
- firestore: getFirestore(app),
3472
- functions: getFunctions(app),
3473
- };
3474
- }
3475
- async function getFirebaseAdminApp() {
3476
- const services = getFirebaseAdminServices();
3477
- if (!services.app) {
3478
- throw new Error('Firebase Admin not initialized');
3479
- }
3480
- return services.app;
3481
- }
3482
- function getFirebaseAdminAuth() {
3483
- const services = getFirebaseAdminServices();
3484
- if (!services.auth) {
3485
- throw new Error('Firebase Admin auth not initialized');
3486
- }
3487
- return services.auth;
3488
- }
3489
- function getFirebaseAdminFirestore() {
3490
- const services = getFirebaseAdminServices();
3491
- if (!services.firestore) {
3492
- throw new Error('Firebase Admin firestore not initialized');
3493
- }
3494
- return services.firestore;
3495
- }
3496
- var getFirebaseAdminServices;
3497
- var init_init = __esm({
3498
- '../providers/firebase/src/server/init.ts'() {
3499
- 'use strict';
3500
- init_server3();
3501
- __name(initializeFirebaseAdminServices, 'initializeFirebaseAdminServices');
3502
- getFirebaseAdminServices = createSingleton(initializeFirebaseAdminServices);
3503
- __name(getFirebaseAdminApp, 'getFirebaseAdminApp');
3504
- __name(getFirebaseAdminAuth, 'getFirebaseAdminAuth');
3505
- __name(getFirebaseAdminFirestore, 'getFirebaseAdminFirestore');
3506
- },
3507
- });
3508
-
3509
- // ../providers/firebase/src/server/utils.ts
3510
- var serverImplementations, getServerAdmin, getServerFirestore, generateServerId;
3511
- var init_utils3 = __esm({
3512
- '../providers/firebase/src/server/utils.ts'() {
3513
- 'use strict';
3514
- init_server3();
3515
- serverImplementations = {
3516
- async getServerAdmin() {
3517
- try {
3518
- const adminModule = await import('firebase-admin');
3519
- return adminModule.default || adminModule;
3520
- } catch (error) {
3521
- throw handleError(error, 'Error getting Firebase Admin');
3522
- }
3523
- },
3524
- async getServerFirestore() {
3525
- try {
3526
- const firestoreModule = await import('firebase-admin/firestore');
3527
- return firestoreModule.getFirestore();
3528
- } catch (error) {
3529
- throw handleError(error, 'Error getting Admin Firestore');
3530
- }
3531
- },
3532
- async generateServerId() {
3533
- const firestore = await serverImplementations.getServerFirestore();
3534
- return firestore.collection('_').doc().id;
3535
- },
3536
- };
3537
- getServerAdmin = serverImplementations.getServerAdmin;
3538
- getServerFirestore = serverImplementations.getServerFirestore;
3539
- generateServerId = serverImplementations.generateServerId;
3540
- },
3541
- });
3542
-
3543
- // ../providers/firebase/src/shared/transform.ts
3544
- function createTimestamp(date) {
3545
- return {
3546
- seconds: Math.floor(date.getTime() / 1e3),
3547
- nanoseconds: (date.getTime() % 1e3) * 1e6,
3548
- toDate: /* @__PURE__ */ __name(() => new Date(date), 'toDate'),
3549
- toMillis: /* @__PURE__ */ __name(() => date.getTime(), 'toMillis'),
3550
- isEqual: /* @__PURE__ */ __name(
3551
- (other) =>
3552
- other.seconds === Math.floor(date.getTime() / 1e3) &&
3553
- other.nanoseconds === (date.getTime() % 1e3) * 1e6,
3554
- 'isEqual'
3555
- ),
3556
- valueOf: /* @__PURE__ */ __name(
3557
- () =>
3558
- `Timestamp(seconds=${Math.floor(date.getTime() / 1e3)}, nanoseconds=${(date.getTime() % 1e3) * 1e6})`,
3559
- 'valueOf'
3560
- ),
3561
- };
3562
- }
3563
- function toTimestamp(date) {
3564
- try {
3565
- if (typeof date === 'string') {
3566
- const parsed = new Date(date);
3567
- if (isNaN(parsed.getTime())) {
3568
- throw handleError(new Error('Invalid date string format'), {
3569
- context: { value: date },
3570
- });
3571
- }
3572
- return createTimestamp(parsed);
3573
- }
3574
- if (date instanceof Date) {
3575
- if (isNaN(date.getTime())) {
3576
- throw handleError(new Error('Invalid Date object'), {
3577
- context: { value: date },
3578
- });
3579
- }
3580
- return createTimestamp(date);
3581
- }
3582
- throw handleError(new Error('Invalid date value type'), {
3583
- context: { valueType: typeof date },
3584
- });
3585
- } catch (error) {
3586
- throw handleError(error, 'Failed to convert to Timestamp');
3587
- }
3588
- }
3589
- function firestoreToISOString(date) {
3590
- try {
3591
- if (date instanceof Date) {
3592
- if (isNaN(date.getTime())) {
3593
- throw handleError(new Error('Invalid Date object'), {
3594
- context: { value: date },
3595
- });
3596
- }
3597
- return date.toISOString();
3598
- }
3599
- if (
3600
- typeof date === 'object' &&
3601
- date !== null &&
3602
- 'toDate' in date &&
3603
- typeof date.toDate === 'function'
3604
- ) {
3605
- return date.toDate().toISOString();
3606
- }
3607
- if (typeof date === 'string') {
3608
- const parsed = new Date(date);
3609
- if (isNaN(parsed.getTime())) {
3610
- throw handleError(new Error('Invalid date string format'), {
3611
- context: { value: date },
3612
- });
3613
- }
3614
- return parsed.toISOString();
3615
- }
3616
- throw handleError(new Error('Invalid date value type'), {
3617
- context: { valueType: typeof date },
3618
- });
3619
- } catch (error) {
3620
- throw handleError(error, 'Failed to convert to ISO string');
3621
- }
3622
- }
3623
- function isTimestamp(value) {
3624
- return (
3625
- typeof value === 'object' &&
3626
- value !== null &&
3627
- 'toDate' in value &&
3628
- typeof value.toDate === 'function' &&
3629
- 'seconds' in value &&
3630
- 'nanoseconds' in value
3631
- );
3632
- }
3633
- function transformFirestoreData(data, includeDocumentIds = false) {
3634
- if (!data) return data;
3635
- if (
3636
- includeDocumentIds &&
3637
- typeof data === 'object' &&
3638
- data !== null &&
3639
- 'id' in data &&
3640
- 'ref' in data &&
3641
- 'data' in data &&
3642
- typeof data.data === 'function'
3643
- ) {
3644
- const doc = data;
3645
- const documentData = doc.data();
3646
- return {
3647
- id: doc.id,
3648
- ...transformFirestoreData(documentData),
3649
- };
3650
- }
3651
- if (Array.isArray(data)) {
3652
- return data.map((item) => transformFirestoreData(item));
3653
- }
3654
- if (isTimestamp(data)) {
3655
- return firestoreToISOString(data);
3656
- }
3657
- if (typeof data === 'object' && data !== null) {
3658
- const transformed = {};
3659
- for (const [key, value] of Object.entries(data)) {
3660
- transformed[key] = transformFirestoreData(value);
3661
- }
3662
- return transformed;
3663
- }
3664
- return data;
3665
- }
3666
- function prepareForFirestore(data, removeFields = []) {
3667
- if (!data) return data;
3668
- if (Array.isArray(data)) {
3669
- return data.map((item) => prepareForFirestore(item, removeFields));
3670
- }
3671
- if (
3672
- typeof data === 'string' &&
3673
- /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(data)
3674
- ) {
3675
- try {
3676
- return toTimestamp(data);
3677
- } catch (error) {
3678
- return data;
3679
- }
3680
- }
3681
- if (data instanceof Date) {
3682
- try {
3683
- return toTimestamp(data);
3684
- } catch (error) {
3685
- return data;
3686
- }
3687
- }
3688
- if (typeof data === 'object' && data !== null) {
3689
- const prepared = {};
3690
- for (const [key, value] of Object.entries(data)) {
3691
- if (removeFields.includes(key)) {
3692
- continue;
3693
- }
3694
- if (value === void 0) {
3695
- continue;
3696
- }
3697
- prepared[key] = prepareForFirestore(value, removeFields);
3698
- }
3699
- return prepared;
3700
- }
3701
- return data;
3702
- }
3703
- var init_transform = __esm({
3704
- '../providers/firebase/src/shared/transform.ts'() {
3705
- 'use strict';
3706
- init_server3();
3707
- __name(createTimestamp, 'createTimestamp');
3708
- __name(toTimestamp, 'toTimestamp');
3709
- __name(firestoreToISOString, 'firestoreToISOString');
3710
- __name(isTimestamp, 'isTimestamp');
3711
- __name(transformFirestoreData, 'transformFirestoreData');
3712
- __name(prepareForFirestore, 'prepareForFirestore');
3713
- },
3714
- });
3715
-
3716
- // ../providers/firebase/src/server/batch.ts
3717
- var isClient,
3718
- serverImplementations2,
3719
- notAvailableInBrowser,
3720
- batchWrite,
3721
- batchCreate,
3722
- batchUpdate,
3723
- batchDelete,
3724
- runTransaction,
3725
- bulkGet;
3726
- var init_batch = __esm({
3727
- '../providers/firebase/src/server/batch.ts'() {
3728
- 'use strict';
3729
- init_dist();
3730
- init_server3();
3731
- init_utils3();
3732
- init_transform();
3733
- isClient = typeof window !== 'undefined';
3734
- serverImplementations2 = {
3735
- /**
3736
- * Performs a batch write operation on multiple documents
3737
- */
3738
- async batchWrite(collection, items, operation, schema, options = {}) {
3739
- if (!items || !items.length) {
3740
- return { successes: 0, failures: 0 };
3741
- }
3742
- const {
3743
- idField = 'id',
3744
- generateIds = true,
3745
- maxBatchSize = 450,
3746
- removeFields = [],
3747
- validate = !!schema,
3748
- } = options;
3749
- const result = {
3750
- successes: 0,
3751
- failures: 0,
3752
- failedItems: [],
3753
- };
3754
- try {
3755
- const batches = [];
3756
- const firestore = await getServerFirestore();
3757
- let currentBatch = firestore.batch();
3758
- let currentBatchSize = 0;
3759
- for (let i = 0; i < items.length; i++) {
3760
- let item = items[i];
3761
- if (!item) {
3762
- result.failures++;
3763
- result.failedItems?.push({
3764
- index: i,
3765
- error: new Error('Item is null or undefined'),
3766
- });
3767
- continue;
3768
- }
3769
- try {
3770
- if (operation === 'delete') {
3771
- if (!item[idField]) {
3772
- throw handleError(
3773
- new Error(`Missing ID for delete operation (${idField})`),
3774
- {
3775
- userMessage: 'Unable to delete item: missing ID',
3776
- severity: 'error',
3777
- context: { collection, idField, operation },
3778
- }
3779
- );
3780
- }
3781
- const docRef = firestore
3782
- .collection(collection)
3783
- .doc(item[idField]);
3784
- currentBatch.delete(docRef);
3785
- } else {
3786
- if (validate && schema) {
3787
- try {
3788
- parse(schema, item);
3789
- } catch (error) {
3790
- throw handleError(error, {
3791
- userMessage: 'Validation failed for item',
3792
- severity: 'warning',
3793
- context: {
3794
- collection,
3795
- operation,
3796
- idField,
3797
- itemId: item[idField],
3798
- },
3799
- });
3800
- }
3801
- }
3802
- let docId = item[idField];
3803
- if (!docId && operation === 'create' && generateIds) {
3804
- docId = firestore.collection(collection).doc().id;
3805
- item = { ...item, [idField]: docId };
3806
- } else if (!docId) {
3807
- throw handleError(
3808
- new Error(
3809
- `Missing ID for ${operation} operation (${idField})`
3810
- ),
3811
- {
3812
- userMessage: `Unable to ${operation} item: missing ID`,
3813
- severity: 'error',
3814
- context: { collection, idField, operation },
3815
- }
3816
- );
3817
- }
3818
- const fieldsToRemove = [idField, ...removeFields];
3819
- const preparedData = prepareForFirestore(item, fieldsToRemove);
3820
- const docRef = firestore.collection(collection).doc(docId);
3821
- if (operation === 'create') {
3822
- currentBatch.create(docRef, preparedData);
3823
- } else if (operation === 'update') {
3824
- currentBatch.update(docRef, preparedData);
3825
- }
3826
- }
3827
- result.successes++;
3828
- currentBatchSize++;
3829
- if (currentBatchSize >= maxBatchSize) {
3830
- batches.push(currentBatch);
3831
- currentBatch = firestore.batch();
3832
- currentBatchSize = 0;
3833
- }
3834
- } catch (error) {
3835
- result.failures++;
3836
- result.failedItems?.push({
3837
- index: i,
3838
- error:
3839
- error instanceof Error ? error : new Error(String(error)),
3840
- });
3841
- }
3842
- }
3843
- if (currentBatchSize > 0) {
3844
- batches.push(currentBatch);
3845
- }
3846
- if (batches.length > 0) {
3847
- await Promise.all(batches.map((batch) => batch.commit()));
3848
- }
3849
- return result;
3850
- } catch (error) {
3851
- throw handleError(error, {
3852
- userMessage: `Batch ${operation} operation failed for collection ${collection}`,
3853
- context: {
3854
- collection,
3855
- operation,
3856
- itemCount: items.length,
3857
- processedCount: result.successes + result.failures,
3858
- successCount: result.successes,
3859
- failureCount: result.failures,
3860
- },
3861
- });
3862
- }
3863
- },
3864
- /**
3865
- * Performs a batch create operation
3866
- */
3867
- async batchCreate(collection, items, schema, options = {}) {
3868
- return serverImplementations2.batchWrite(
3869
- collection,
3870
- items,
3871
- 'create',
3872
- schema,
3873
- options
3874
- );
3875
- },
3876
- /**
3877
- * Performs a batch update operation
3878
- */
3879
- async batchUpdate(collection, items, schema, options = {}) {
3880
- return serverImplementations2.batchWrite(
3881
- collection,
3882
- items,
3883
- 'update',
3884
- schema,
3885
- options
3886
- );
3887
- },
3888
- /**
3889
- * Performs a batch delete operation
3890
- */
3891
- async batchDelete(collection, items, options = {}) {
3892
- if (items.length > 0 && typeof items[0] === 'string') {
3893
- const idField = options.idField || 'id';
3894
- const objectItems = items.map((id) => {
3895
- return { [idField]: id };
3896
- });
3897
- return serverImplementations2.batchWrite(
3898
- collection,
3899
- objectItems,
3900
- 'delete',
3901
- void 0,
3902
- options
3903
- );
3904
- }
3905
- return serverImplementations2.batchWrite(
3906
- collection,
3907
- items,
3908
- 'delete',
3909
- void 0,
3910
- options
3911
- );
3912
- },
3913
- /**
3914
- * Runs a transaction with proper error handling
3915
- */
3916
- async runTransaction(updateFunction) {
3917
- try {
3918
- const firestore = await getServerFirestore();
3919
- return await firestore.runTransaction(updateFunction);
3920
- } catch (error) {
3921
- throw handleError(error, {
3922
- userMessage: 'Transaction failed',
3923
- });
3924
- }
3925
- },
3926
- /**
3927
- * Fetches multiple documents by ID in a single batch
3928
- */
3929
- async bulkGet(collection, ids, options = {}) {
3930
- if (!ids.length) return [];
3931
- const { maxBatchSize = 450, transform = true } = options;
3932
- try {
3933
- const batches = [];
3934
- for (let i = 0; i < ids.length; i += maxBatchSize) {
3935
- batches.push(ids.slice(i, i + maxBatchSize));
3936
- }
3937
- const batchPromises = batches.map(async (batchIds) => {
3938
- const firestore = await getServerFirestore();
3939
- const collectionRef = firestore.collection(collection);
3940
- const docs = await collectionRef
3941
- .where('__name__', 'in', batchIds)
3942
- .get();
3943
- const docMap = /* @__PURE__ */ new Map();
3944
- docs.forEach((doc) => {
3945
- docMap.set(doc.id, doc.data());
3946
- });
3947
- return batchIds.map((id) => {
3948
- const data = docMap.get(id);
3949
- if (!data) return null;
3950
- const result = transform
3951
- ? transformFirestoreData({ id, ...data })
3952
- : { id, ...data };
3953
- return result;
3954
- });
3955
- });
3956
- const results = await Promise.all(batchPromises);
3957
- return results.flat();
3958
- } catch (error) {
3959
- throw handleError(error, {
3960
- userMessage: `Bulk get operation failed for collection ${collection}`,
3961
- context: {
3962
- collection,
3963
- idCount: ids.length,
3964
- },
3965
- });
3966
- }
3967
- },
3968
- };
3969
- notAvailableInBrowser = /* @__PURE__ */ __name(
3970
- (fnName) => () => {
3971
- throw new Error(
3972
- `Firebase Admin function '${fnName}' is not available in browser environments`
3973
- );
3974
- },
3975
- 'notAvailableInBrowser'
3976
- );
3977
- batchWrite = isClient
3978
- ? notAvailableInBrowser('batchWrite')
3979
- : serverImplementations2.batchWrite;
3980
- batchCreate = isClient
3981
- ? notAvailableInBrowser('batchCreate')
3982
- : serverImplementations2.batchCreate;
3983
- batchUpdate = isClient
3984
- ? notAvailableInBrowser('batchUpdate')
3985
- : serverImplementations2.batchUpdate;
3986
- batchDelete = isClient
3987
- ? notAvailableInBrowser('batchDelete')
3988
- : serverImplementations2.batchDelete;
3989
- runTransaction = isClient
3990
- ? notAvailableInBrowser('runTransaction')
3991
- : serverImplementations2.runTransaction;
3992
- bulkGet = isClient
3993
- ? notAvailableInBrowser('bulkGet')
3994
- : serverImplementations2.bulkGet;
3995
- },
3996
- });
3997
-
3998
- // ../providers/firebase/src/shared/utils.ts
3999
- var isClient2, notAvailableInBrowser2, admin, getAdminFirestore, generateId;
4000
- var init_utils4 = __esm({
4001
- '../providers/firebase/src/shared/utils.ts'() {
4002
- 'use strict';
4003
- init_server3();
4004
- isClient2 = typeof window !== 'undefined';
4005
- notAvailableInBrowser2 = /* @__PURE__ */ __name(
4006
- (fnName) => () => {
4007
- throw handleError(
4008
- new Error(
4009
- `Firebase Admin function '${fnName}' is not available in browser environments`
4010
- ),
4011
- {
4012
- userMessage: 'This operation requires server-side Firebase access',
4013
- context: { function: fnName },
4014
- }
4015
- );
4016
- },
4017
- 'notAvailableInBrowser'
4018
- );
4019
- admin = isClient2 ? null : notAvailableInBrowser2('admin');
4020
- getAdminFirestore = isClient2
4021
- ? notAvailableInBrowser2('getAdminFirestore')
4022
- : notAvailableInBrowser2('getAdminFirestore');
4023
- generateId = isClient2
4024
- ? notAvailableInBrowser2('generateId')
4025
- : notAvailableInBrowser2('generateId');
4026
- },
4027
- });
4028
-
4029
- // ../providers/firebase/src/server/subscription.ts
4030
- var init_subscription = __esm({
4031
- '../providers/firebase/src/server/subscription.ts'() {
4032
- 'use strict';
4033
- init_server3();
4034
- init_utils3();
4035
- init_transform();
4036
- init_utils4();
4037
- },
4038
- });
4039
-
4040
- // ../providers/firebase/src/server/uniqueness.ts
4041
- var init_uniqueness = __esm({
4042
- '../providers/firebase/src/server/uniqueness.ts'() {
4043
- 'use strict';
4044
- init_server3();
4045
- init_utils3();
4046
- },
4047
- });
4048
-
4049
- // ../providers/firebase/src/server/validation.ts
4050
- var init_validation3 = __esm({
4051
- '../providers/firebase/src/server/validation.ts'() {
4052
- 'use strict';
4053
- init_server3();
4054
- init_uniqueness();
4055
- init_uniqueness();
4056
- },
4057
- });
4058
-
4059
- // ../providers/firebase/src/server/index.ts
4060
- import { FieldValue, Query, Timestamp } from 'firebase-admin/firestore';
4061
- var init_server4 = __esm({
4062
- '../providers/firebase/src/server/index.ts'() {
4063
- 'use strict';
4064
- init_init();
4065
- init_utils3();
4066
- init_batch();
4067
- init_subscription();
4068
- init_validation3();
4069
- init_uniqueness();
4070
- init_transform();
4071
- },
4072
- });
4073
-
4074
- // src/shared/errorHandling.ts
4075
- init_server3();
4076
- import { HttpsError } from 'firebase-functions/v2/https';
4077
- var DoNotDevError3 = class _DoNotDevError extends Error {
4078
- static {
4079
- __name(this, 'DoNotDevError');
4080
- }
4081
- code;
4082
- details;
4083
- constructor(message, code = 'unknown', details) {
4084
- super(message);
4085
- Object.setPrototypeOf(this, _DoNotDevError.prototype);
4086
- this.code = code;
4087
- this.details = details;
4088
- this.name = this.constructor.name;
4089
- if (Error.captureStackTrace) {
4090
- Error.captureStackTrace(this, this.constructor);
4091
- }
4092
- }
4093
- toString() {
4094
- return `${this.name} [${this.code}]: ${this.message}`;
4095
- }
4096
- toJSON() {
4097
- return {
4098
- name: this.name,
4099
- code: this.code,
4100
- message: this.message,
4101
- details: this.details,
4102
- };
4103
- }
4104
- };
4105
- function handleError2(error) {
4106
- console.error('Function error:', error);
4107
- let code;
4108
- let message;
4109
- let details;
4110
- if (error instanceof DoNotDevError3) {
4111
- code = error.code;
4112
- message = error.message;
4113
- details = error.details;
4114
- } else if (
4115
- error &&
4116
- typeof error === 'object' &&
4117
- 'issues' in error &&
4118
- ((error instanceof Error && error.name === 'ValiError') ||
4119
- error.name === 'ValiError')
4120
- ) {
4121
- code = 'invalid-argument';
4122
- message = 'Validation failed';
4123
- details = { validationErrors: error.issues };
4124
- } else if (
4125
- error &&
4126
- typeof error === 'object' &&
4127
- 'type' in error &&
4128
- ((error instanceof Error && error.name === 'EntityHookError') ||
4129
- error.name === 'EntityHookError')
4130
- ) {
4131
- const entityError = error;
4132
- switch (entityError.type) {
4133
- case 'PERMISSION_DENIED':
4134
- code = 'permission-denied';
4135
- break;
4136
- case 'NOT_FOUND':
4137
- code = 'not-found';
4138
- break;
4139
- case 'ALREADY_EXISTS':
4140
- code = 'already-exists';
4141
- break;
4142
- case 'VALIDATION_ERROR':
4143
- code = 'invalid-argument';
4144
- break;
4145
- case 'NETWORK_ERROR':
4146
- code = 'unavailable';
4147
- break;
4148
- default:
4149
- code = 'internal';
4150
- }
4151
- message = entityError.message;
4152
- details = void 0;
4153
- } else {
4154
- code = 'internal';
4155
- message =
4156
- error instanceof Error ? error.message : 'An unexpected error occurred';
4157
- details = {
4158
- originalError:
4159
- error instanceof Error
4160
- ? {
4161
- name: error.name,
4162
- message: error.message,
4163
- stack: error.stack,
4164
- }
4165
- : String(error),
4166
- };
4167
- }
4168
- if (isFirebaseEnvironment()) {
4169
- throwFirebaseError(code, message, details);
4170
- } else if (isVercelEnvironment()) {
4171
- throwVercelError(code, message, details);
4172
- } else {
4173
- throw new Error(`${code}: ${message}`);
4174
- }
4175
- }
4176
- __name(handleError2, 'handleError');
4177
- function isFirebaseEnvironment() {
4178
- return (
4179
- typeof process !== 'undefined' &&
4180
- (process.env.FUNCTIONS_EMULATOR === 'true' ||
4181
- process.env.FIREBASE_CONFIG !== void 0 ||
4182
- process.env.GCLOUD_PROJECT !== void 0)
4183
- );
4184
- }
4185
- __name(isFirebaseEnvironment, 'isFirebaseEnvironment');
4186
- function isVercelEnvironment() {
4187
- return (
4188
- typeof process !== 'undefined' &&
4189
- (process.env.VERCEL === '1' || process.env.VERCEL_ENV !== void 0)
4190
- );
4191
- }
4192
- __name(isVercelEnvironment, 'isVercelEnvironment');
4193
- function throwFirebaseError(code, message, details) {
4194
- throw new HttpsError(code, message, details);
4195
- }
4196
- __name(throwFirebaseError, 'throwFirebaseError');
4197
- function throwVercelError(code, message, details) {
4198
- const error = new Error(message);
4199
- error.code = code;
4200
- error.details = details;
4201
- throw error;
4202
- }
4203
- __name(throwVercelError, 'throwVercelError');
4204
-
4205
- // src/shared/utils.ts
4206
- init_server3();
4207
- init_server4();
4208
- import Stripe from 'stripe';
4209
- var _stripe = null;
4210
- function initStripe(apiKey) {
4211
- if (!apiKey) throw new Error('Stripe API key is required');
4212
- const apiVersion = process.env.STRIPE_API_VERSION || '2024-12-18.acacia';
4213
- _stripe = new Stripe(apiKey, {
4214
- apiVersion,
4215
- });
4216
- return _stripe;
4217
- }
4218
- __name(initStripe, 'initStripe');
4219
- function getStripe() {
4220
- if (!_stripe) {
4221
- const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
4222
- if (STRIPE_SECRET_KEY) {
4223
- initStripe(STRIPE_SECRET_KEY);
4224
- } else {
4225
- throw new Error(
4226
- 'Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.'
4227
- );
4228
- }
4229
- }
4230
- return _stripe;
4231
- }
4232
- __name(getStripe, 'getStripe');
4233
- var stripe = new Proxy(
4234
- {},
4235
- {
4236
- get(target, prop) {
4237
- return getStripe()[prop];
4238
- },
4239
- }
4240
- );
4241
- function assertAuthenticated(auth) {
4242
- if (!auth || !auth.uid) {
4243
- throw new Error('User must be authenticated');
4244
- }
4245
- return auth.uid;
4246
- }
4247
- __name(assertAuthenticated, 'assertAuthenticated');
4248
- function validateStripeEnvironment() {
4249
- const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
4250
- if (!STRIPE_SECRET_KEY) {
4251
- throw new Error('Missing STRIPE_SECRET_KEY environment variable');
4252
- }
4253
- }
4254
- __name(validateStripeEnvironment, 'validateStripeEnvironment');
4255
-
4256
- // src/vercel/baseFunction.ts
4257
- init_dist();
4258
-
4259
- // src/shared/utils/internal/monitoring.ts
4260
- init_server4();
4261
- import { logger } from 'firebase-functions/v2';
4262
- async function recordPaymentMetrics(metrics) {
4263
- try {
4264
- const db = getFirebaseAdminFirestore();
4265
- const metricsRef = db.collection('payment_metrics').doc();
4266
- await metricsRef.set({
4267
- ...metrics,
4268
- recordedAt: /* @__PURE__ */ new Date().toISOString(),
4269
- });
4270
- logger.info('Payment metrics recorded', {
4271
- operation: metrics.operation,
4272
- status: metrics.status,
4273
- userId: metrics.userId,
4274
- });
4275
- } catch (error) {
4276
- logger.error('Failed to record payment metrics', {
4277
- error: error instanceof Error ? error.message : String(error),
4278
- metrics,
4279
- });
4280
- }
4281
- }
4282
- __name(recordPaymentMetrics, 'recordPaymentMetrics');
4283
-
4284
- // src/shared/utils/internal/rateLimiter.ts
4285
- init_server4();
4286
- import { logger as logger2 } from 'firebase-functions/v2';
4287
- async function checkRateLimitWithFirestore(key, config) {
4288
- const db = getFirebaseAdminFirestore();
4289
- const rateLimitRef = db.collection('rateLimits').doc(key);
4290
- try {
4291
- const now = Date.now();
4292
- const doc = await rateLimitRef.get();
4293
- if (!doc.exists) {
4294
- await rateLimitRef.set({
4295
- attempts: 1,
4296
- windowStart: now,
4297
- blockUntil: null,
4298
- lastUpdated: now,
4299
- });
4300
- return {
4301
- allowed: true,
4302
- remaining: config.maxAttempts - 1,
4303
- resetAt: new Date(now + config.windowMs),
4304
- blockRemainingSeconds: null,
4305
- };
4306
- }
4307
- const data = doc.data();
4308
- if (data.blockUntil && now < data.blockUntil) {
4309
- return {
4310
- allowed: false,
4311
- remaining: 0,
4312
- resetAt: new Date(data.blockUntil),
4313
- blockRemainingSeconds: Math.ceil((data.blockUntil - now) / 1e3),
4314
- };
4315
- }
4316
- if (now >= data.windowStart + config.windowMs) {
4317
- await rateLimitRef.set({
4318
- attempts: 1,
4319
- windowStart: now,
4320
- blockUntil: null,
4321
- lastUpdated: now,
4322
- });
4323
- return {
4324
- allowed: true,
4325
- remaining: config.maxAttempts - 1,
4326
- resetAt: new Date(now + config.windowMs),
4327
- blockRemainingSeconds: null,
4328
- };
4329
- }
4330
- if (data.attempts >= config.maxAttempts) {
4331
- const blockUntil = now + config.blockDurationMs;
4332
- await rateLimitRef.update({
4333
- blockUntil,
4334
- lastUpdated: now,
4335
- });
4336
- logger2.warn('Rate limit exceeded (Firestore)', {
4337
- key,
4338
- attempts: data.attempts,
4339
- blockUntil: new Date(blockUntil),
4340
- });
4341
- return {
4342
- allowed: false,
4343
- remaining: 0,
4344
- resetAt: new Date(blockUntil),
4345
- blockRemainingSeconds: Math.ceil(config.blockDurationMs / 1e3),
4346
- };
4347
- }
4348
- await rateLimitRef.update({
4349
- attempts: data.attempts + 1,
4350
- lastUpdated: now,
4351
- });
4352
- return {
4353
- allowed: true,
4354
- remaining: config.maxAttempts - (data.attempts + 1),
4355
- resetAt: new Date(data.windowStart + config.windowMs),
4356
- blockRemainingSeconds: null,
4357
- };
4358
- } catch (error) {
4359
- logger2.error('Rate limit check failed', {
4360
- key,
4361
- error: error instanceof Error ? error.message : String(error),
4362
- });
4363
- return {
4364
- allowed: true,
4365
- remaining: config.maxAttempts,
4366
- resetAt: null,
4367
- blockRemainingSeconds: null,
4368
- };
4369
- }
4370
- }
4371
- __name(checkRateLimitWithFirestore, 'checkRateLimitWithFirestore');
4372
- var DEFAULT_RATE_LIMITS = {
4373
- checkout: {
4374
- maxAttempts: 5,
4375
- windowMs: 60 * 1e3,
4376
- // 1 minute
4377
- blockDurationMs: 5 * 60 * 1e3,
4378
- // 5 minutes
4379
- },
4380
- webhook: {
4381
- maxAttempts: 100,
4382
- windowMs: 60 * 1e3,
4383
- // 1 minute
4384
- blockDurationMs: 60 * 1e3,
4385
- // 1 minute
4386
- },
4387
- auth: {
4388
- maxAttempts: 10,
4389
- windowMs: 60 * 1e3,
4390
- // 1 minute
4391
- blockDurationMs: 5 * 60 * 1e3,
4392
- // 5 minutes
4393
- },
4394
- api: {
4395
- maxAttempts: 100,
4396
- windowMs: 60 * 1e3,
4397
- // 1 minute
4398
- blockDurationMs: 60 * 1e3,
4399
- // 1 minute
4400
- },
4401
- };
4402
-
4403
- // src/vercel/baseFunction.ts
4404
- function createVercelBaseFunction(method, schema, operation, businessLogic) {
4405
- return async (req, res) => {
4406
- try {
4407
- if (req.method !== method) {
4408
- return res.status(405).json({ error: 'Method not allowed' });
4409
- }
4410
- const validationResult = safeParse(schema, req.body);
4411
- if (!validationResult.success) {
4412
- return res.status(400).json({
4413
- error: `Validation failed: ${validationResult.issues.map((e) => e.message).join(', ')}`,
4414
- });
4415
- }
4416
- const validatedData = validationResult.output;
4417
- const uid = assertAuthenticated(req.headers.authorization);
4418
- const rateLimitKey = `${operation}_${uid}`;
4419
- const rateLimitConfig =
4420
- DEFAULT_RATE_LIMITS[operation] || DEFAULT_RATE_LIMITS.api;
4421
- const rateLimitResult = await checkRateLimitWithFirestore(
4422
- rateLimitKey,
4423
- rateLimitConfig
4424
- );
4425
- if (!rateLimitResult.allowed) {
4426
- return res.status(429).json({
4427
- error: `Rate limit exceeded. Try again in ${rateLimitResult.blockRemainingSeconds} seconds.`,
4428
- retryAfter: rateLimitResult.blockRemainingSeconds,
4429
- });
4430
- }
4431
- const result = await businessLogic(req, res, validatedData, { uid });
4432
- await recordPaymentMetrics({
4433
- operation,
4434
- userId: uid,
4435
- status: 'success',
4436
- timestamp: /* @__PURE__ */ new Date().toISOString(),
4437
- metadata: {
4438
- requestId: req.headers['x-request-id'] || 'unknown',
4439
- },
4440
- });
4441
- return result;
4442
- } catch (error) {
4443
- await recordPaymentMetrics({
4444
- operation,
4445
- userId: req.headers.authorization ? 'authenticated' : 'anonymous',
4446
- status: 'failed',
4447
- timestamp: /* @__PURE__ */ new Date().toISOString(),
4448
- metadata: {
4449
- error: error instanceof Error ? error.message : 'Unknown error',
4450
- requestId: req.headers['x-request-id'] || 'unknown',
4451
- },
4452
- });
4453
- const errorResponse = handleVercelError(error);
4454
- return res
4455
- .status(errorResponse.status)
4456
- .json({ error: errorResponse.message });
4457
- }
4458
- };
4459
- }
4460
- __name(createVercelBaseFunction, 'createVercelBaseFunction');
4461
- function handleVercelError(error) {
4462
- if (error instanceof Error) {
4463
- if (error.message.includes('Rate limit exceeded')) {
4464
- return { status: 429, message: error.message };
4465
- }
4466
- if (error.message.includes('Validation failed')) {
4467
- return { status: 400, message: error.message };
4468
- }
4469
- if (error.message.includes('permission-denied')) {
4470
- return { status: 403, message: 'Permission denied' };
4471
- }
4472
- if (error.message.includes('not-found')) {
4473
- return { status: 404, message: 'Resource not found' };
4474
- }
4475
- if (error.message.includes('already-exists')) {
4476
- return { status: 409, message: 'Resource already exists' };
4477
- }
4478
- if (error.message.includes('invalid-argument')) {
4479
- return { status: 400, message: error.message };
4480
- }
4481
- }
4482
- return { status: 500, message: 'Internal server error' };
4483
- }
4484
- __name(handleVercelError, 'handleVercelError');
4485
-
4486
- // src/shared/billing/helpers/updateUserSubscription.ts
4487
- async function updateUserSubscription(userId, subscriptionData, authProvider) {
4488
- const user = await authProvider.getUser(userId);
4489
- const currentClaims = user.customClaims || {};
4490
- if (!subscriptionData.tier || !subscriptionData.status) {
4491
- throw new Error('Invalid subscription data: missing tier or status');
4492
- }
4493
- const subscriptionClaims = {
4494
- tier: subscriptionData.tier,
4495
- subscriptionId: subscriptionData.subscriptionId || null,
4496
- customerId: subscriptionData.customerId || userId,
4497
- status: subscriptionData.status,
4498
- // Keep as ISO string - no conversion needed
4499
- subscriptionEnd: subscriptionData.subscriptionEnd,
4500
- cancelAtPeriodEnd: subscriptionData.cancelAtPeriodEnd || false,
4501
- updatedAt: /* @__PURE__ */ new Date().toISOString(),
4502
- isDefault: false,
4503
- };
4504
- const updatedClaims = {
4505
- ...currentClaims,
4506
- subscription: subscriptionClaims,
4507
- };
4508
- await authProvider.setCustomUserClaims(userId, updatedClaims);
4509
- }
4510
- __name(updateUserSubscription, 'updateUserSubscription');
4511
-
4512
- // src/vercel/api/billing/cancel.ts
4513
- init_server4();
4514
- init_dist();
4515
-
4516
- // src/shared/billing/helpers/subscriptionManagement.ts
4517
- init_server3();
4518
- import 'stripe';
4519
- async function cancelUserSubscription(userId, authProvider) {
4520
- validateStripeEnvironment();
4521
- const user = await authProvider.getUser(userId);
4522
- const currentClaims = user.customClaims || {};
4523
- const subscription = currentClaims.subscription;
4524
- const subscriptionId = subscription?.subscriptionId;
4525
- if (!subscriptionId) {
4526
- throw handleError2(new Error('No active subscription found'));
4527
- }
4528
- const updatedSubscription = await stripe.subscriptions.update(
4529
- subscriptionId,
4530
- {
4531
- cancel_at_period_end: true,
4532
- }
4533
- );
4534
- const validStatuses = [
4535
- 'active',
4536
- 'canceled',
4537
- 'past_due',
4538
- 'trialing',
4539
- 'incomplete',
4540
- ];
4541
- const status = validStatuses.includes(updatedSubscription.status)
4542
- ? updatedSubscription.status
4543
- : 'incomplete';
4544
- await updateUserSubscription(
4545
- userId,
4546
- {
4547
- tier: subscription?.tier || 'free',
4548
- status,
4549
- subscriptionEnd: new Date(
4550
- updatedSubscription.current_period_end * 1e3
4551
- ).toISOString(),
4552
- cancelAtPeriodEnd: true,
4553
- subscriptionId: updatedSubscription.id,
4554
- customerId: updatedSubscription.customer,
4555
- },
4556
- authProvider
4557
- );
4558
- return {
4559
- success: true,
4560
- endsAt: new Date(
4561
- updatedSubscription.current_period_end * 1e3
4562
- ).toISOString(),
4563
- };
4564
- }
4565
- __name(cancelUserSubscription, 'cancelUserSubscription');
4566
-
4567
- // src/vercel/api/billing/cancel.ts
4568
- var cancelSubscriptionSchema = object({
4569
- userId: string(),
4570
- });
4571
- async function cancelSubscriptionLogic(req, res, data, context) {
4572
- const { userId } = data;
4573
- const authProvider = {
4574
- async getUser(uid) {
4575
- return getFirebaseAdminAuth().getUser(uid);
4576
- },
4577
- async setCustomUserClaims(uid, claims) {
4578
- await getFirebaseAdminAuth().setCustomUserClaims(uid, claims);
4579
- },
4580
- };
4581
- const result = await cancelUserSubscription(userId, authProvider);
4582
- return res.status(200).json({
4583
- success: result.success,
4584
- cancelAtPeriodEnd: true,
4585
- endsAt: result.endsAt,
4586
- });
4587
- }
4588
- __name(cancelSubscriptionLogic, 'cancelSubscriptionLogic');
4589
- var cancelSubscription = /* @__PURE__ */ __name(() => {
4590
- return createVercelBaseFunction(
4591
- 'POST',
4592
- cancelSubscriptionSchema,
4593
- 'cancel_subscription',
4594
- cancelSubscriptionLogic
4595
- );
4596
- }, 'cancelSubscription');
4597
- var cancel_default = cancelSubscription;
4598
-
4599
- // src/vercel/api/billing/change-plan.ts
4600
- init_server4();
4601
- init_dist();
4602
- import 'stripe';
4603
- var changePlanSchema = object({
4604
- userId: string(),
4605
- newPriceId: string(),
4606
- billingConfigKey: string(),
4607
- });
4608
- async function changePlanLogic(req, res, data, context, billingConfig) {
4609
- validateStripeEnvironment();
4610
- const { userId, newPriceId, billingConfigKey } = data;
4611
- const billingItem = billingConfig[billingConfigKey];
4612
- if (!billingItem || billingItem.type !== 'StripeSubscription') {
4613
- throw handleError2(new Error('Invalid plan'));
4614
- }
4615
- if (billingItem.priceId !== newPriceId) {
4616
- throw handleError2(new Error('Price ID mismatch'));
4617
- }
4618
- const user = await getFirebaseAdminAuth().getUser(userId);
4619
- const subscriptionId = user.customClaims?.subscription?.subscriptionId;
4620
- if (!subscriptionId) {
4621
- throw handleError2(new Error('No active subscription'));
4622
- }
4623
- const subscription = await stripe.subscriptions.retrieve(subscriptionId);
4624
- const updatedSubscription = await stripe.subscriptions.update(
4625
- subscriptionId,
4626
- {
4627
- items: [{ id: subscription.items.data[0]?.id, price: newPriceId }],
4628
- proration_behavior: 'create_prorations',
4629
- }
4630
- );
4631
- const validStatuses = [
4632
- 'active',
4633
- 'canceled',
4634
- 'past_due',
4635
- 'trialing',
4636
- 'incomplete',
4637
- ];
4638
- const status = validStatuses.includes(updatedSubscription.status)
4639
- ? updatedSubscription.status
4640
- : 'incomplete';
4641
- await updateUserSubscription(
4642
- userId,
4643
- {
4644
- tier: billingItem.tier,
4645
- status,
4646
- subscriptionEnd: new Date(
4647
- updatedSubscription.current_period_end * 1e3
4648
- ).toISOString(),
4649
- cancelAtPeriodEnd: updatedSubscription.cancel_at_period_end,
4650
- subscriptionId: updatedSubscription.id,
4651
- customerId: updatedSubscription.customer,
4652
- },
4653
- {
4654
- async getUser(uid) {
4655
- return getFirebaseAdminAuth().getUser(uid);
4656
- },
4657
- async setCustomUserClaims(uid, claims) {
4658
- await getFirebaseAdminAuth().setCustomUserClaims(uid, claims);
4659
- },
4660
- }
4661
- );
4662
- return res.status(200).json({
4663
- success: true,
4664
- newTier: billingItem.tier,
4665
- newPrice: billingItem.price,
4666
- });
4667
- }
4668
- __name(changePlanLogic, 'changePlanLogic');
4669
- var changePlan = /* @__PURE__ */ __name((billingConfig) => {
4670
- return createVercelBaseFunction(
4671
- 'POST',
4672
- changePlanSchema,
4673
- 'change_plan',
4674
- (req, res, data, context) =>
4675
- changePlanLogic(req, res, data, context, billingConfig)
4676
- );
4677
- }, 'changePlan');
4678
- var change_plan_default = changePlan;
4679
-
4680
- // src/vercel/api/billing/customer-portal.ts
4681
- init_server4();
4682
- init_dist();
4683
- var customerPortalSchema = object({
4684
- userId: string(),
4685
- returnUrl: optional(pipe(string(), url())),
4686
- });
4687
- async function createCustomerPortalLogic(req, res, data, context) {
4688
- validateStripeEnvironment();
4689
- const { userId, returnUrl } = data;
4690
- const user = await getFirebaseAdminAuth().getUser(userId);
4691
- const customerId = user.customClaims?.subscription?.customerId;
4692
- if (!customerId) {
4693
- throw handleError2(new Error('No customer found'));
4694
- }
4695
- const session = await stripe.billingPortal.sessions.create({
4696
- customer: customerId,
4697
- return_url: returnUrl || `${process.env.FRONTEND_URL}/billing`,
4698
- });
4699
- return res.status(200).json({ url: session.url });
4700
- }
4701
- __name(createCustomerPortalLogic, 'createCustomerPortalLogic');
4702
- var createCustomerPortal = /* @__PURE__ */ __name(() => {
4703
- return createVercelBaseFunction(
4704
- 'POST',
4705
- customerPortalSchema,
4706
- 'create_customer_portal',
4707
- createCustomerPortalLogic
4708
- );
4709
- }, 'createCustomerPortal');
4710
- var customer_portal_default = createCustomerPortal;
4711
-
4712
- // src/vercel/api/config/constants.ts
4713
- var FIREBASE_REGION = process.env.FIREBASE_REGION || 'europe-west1';
4714
- var FUNCTION_CONFIG = {
4715
- // Default region for all functions
4716
- region: FIREBASE_REGION,
4717
- // Memory and timeout defaults
4718
- memory: '1GiB',
4719
- timeoutSeconds: 60,
4720
- };
4721
- var STRIPE_CONFIG = {
4722
- region: FIREBASE_REGION,
4723
- memory: '512MiB',
4724
- timeoutSeconds: 30,
4725
- };
4726
- var AUTH_CONFIG = {
4727
- region: FIREBASE_REGION,
4728
- memory: '256MiB',
4729
- timeoutSeconds: 20,
4730
- };
4731
- var CRUD_CONFIG = {
4732
- region: FIREBASE_REGION,
4733
- memory: '256MiB',
4734
- timeoutSeconds: 15,
4735
- };
4736
- var AVAILABLE_REGIONS = {
4737
- // Europe (recommended for France)
4738
- 'europe-west1': 'Belgium',
4739
- 'europe-west2': 'London',
4740
- 'europe-west3': 'Frankfurt',
4741
- 'europe-west6': 'Zurich',
4742
- 'europe-central2': 'Warsaw',
4743
- // US
4744
- 'us-central1': 'Iowa',
4745
- 'us-east1': 'South Carolina',
4746
- 'us-east4': 'Northern Virginia',
4747
- 'us-west1': 'Oregon',
4748
- // Asia
4749
- 'asia-east1': 'Taiwan',
4750
- 'asia-northeast1': 'Tokyo',
4751
- 'asia-southeast1': 'Singapore',
4752
- };
4753
- var validateEnvironment = /* @__PURE__ */ __name(() => {
4754
- const required = ['STRIPE_SECRET_KEY', 'STRIPE_WEBHOOK_SECRET'];
4755
- const missing = required.filter((key) => !process.env[key]);
4756
- if (missing.length > 0) {
4757
- throw new Error(
4758
- `Missing required environment variables: ${missing.join(', ')}`
4759
- );
4760
- }
4761
- console.log(
4762
- `\u{1F30D} Firebase Functions configured for region: ${FIREBASE_REGION}`
4763
- );
4764
- }, 'validateEnvironment');
4765
-
4766
- // src/vercel/api/config/firebase-admin.ts
4767
- init_server4();
4768
- async function initializeFirebaseAdmin() {
4769
- return await getFirebaseAdminApp();
4770
- }
4771
- __name(initializeFirebaseAdmin, 'initializeFirebaseAdmin');
4772
- async function getFirebaseAdmin() {
4773
- return await getFirebaseAdminApp();
4774
- }
4775
- __name(getFirebaseAdmin, 'getFirebaseAdmin');
4776
- export {
4777
- AUTH_CONFIG,
4778
- AVAILABLE_REGIONS,
4779
- CRUD_CONFIG,
4780
- FIREBASE_REGION,
4781
- FUNCTION_CONFIG,
4782
- STRIPE_CONFIG,
4783
- cancel_default as cancelSubscription,
4784
- change_plan_default as changePlan,
4785
- customer_portal_default as createCustomerPortal,
4786
- getFirebaseAdmin,
4787
- initializeFirebaseAdmin,
4788
- updateUserSubscription,
4789
- validateEnvironment,
4790
- };
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname } from 'node:path';
4
+ import { Buffer } from 'node:buffer';
5
+ import process from 'node:process';
6
+
7
+ const require = __createRequire(import.meta.url);
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ if (typeof globalThis !== 'undefined') {
12
+ globalThis.require = require;
13
+ globalThis.__filename = __filename;
14
+ globalThis.__dirname = __dirname;
15
+ globalThis.Buffer = Buffer;
16
+ globalThis.process = process;
17
+ if (typeof global === 'undefined') {
18
+ globalThis.global = globalThis;
19
+ }
20
+ }
21
+ var Xn=Object.defineProperty;var n=(e,t)=>Xn(e,"name",{value:t,configurable:!0});var u=(e,t)=>()=>(e&&(t=e(e=0)),t);var Z,Rt,Ct,It,We=u(()=>{"use strict";Z={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"},Rt={FREE:"free",PRO:"pro",PREMIUM:"premium"},Ct={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"},It={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"}});function Ye(e){return{lang:e?.lang??Ke?.lang,message:e?.message,abortEarly:e?.abortEarly??Ke?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Ke?.abortPipeEarly}}function Jn(e){return Zn?.get(e)}function ei(e){return Qn?.get(e)}function ri(e,t){return ti?.get(e)?.get(t)}function te(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function x(e,t,r,i,a){let s=a&&"input"in a?a.input:r.value,c=a?.expected??e.expects??null,m=a?.received??te(s),l={kind:e.kind,type:e.type,input:s,expected:c,received:m,message:`Invalid ${t}: ${c?`Expected ${c} but r`:"R"}eceived ${m}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:i.lang,abortEarly:i.abortEarly,abortPipeEarly:i.abortPipeEarly},h=e.kind==="schema",p=a?.message??e.message??ri(e.reference,l.lang)??(h?ei(l.lang):null)??i.message??Jn(l.lang);p!==void 0&&(l.message=typeof p=="function"?p(l):p),h&&(r.typed=!1),r.issues?r.issues.push(l):r.issues=[l]}function O(e){return{version:1,vendor:"valibot",validate(t){return e["~run"]({value:t},Ye())}}}function Dt(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function Xe(e,t){let r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function K(e){return{kind:"validation",type:"email",reference:K,expects:null,async:!1,requirement:ni,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&x(this,"email",t,r),t}}}function $(e){return{kind:"validation",type:"iso_timestamp",reference:$,async:!1,expects:null,requirement:ii,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&x(this,"timestamp",t,r),t}}}function Pe(e,t){return{kind:"validation",type:"length",reference:Pe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&r.value.length!==this.requirement&&x(this,"length",r,i,{received:`${r.value.length}`}),r}}}function De(e,t){return{kind:"validation",type:"max_length",reference:De,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&r.value.length>this.requirement&&x(this,"length",r,i,{received:`${r.value.length}`}),r}}}function ue(e,t){return{kind:"validation",type:"max_value",reference:ue,async:!1,expects:`<=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(r,i){return r.typed&&!(r.value<=this.requirement)&&x(this,"value",r,i,{received:r.value instanceof Date?r.value.toJSON():te(r.value)}),r}}}function v(e,t){return{kind:"validation",type:"min_length",reference:v,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&r.value.length<this.requirement&&x(this,"length",r,i,{received:`${r.value.length}`}),r}}}function re(e,t){return{kind:"validation",type:"min_value",reference:re,async:!1,expects:`>=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(r,i){return r.typed&&!(r.value>=this.requirement)&&x(this,"value",r,i,{received:r.value instanceof Date?r.value.toJSON():te(r.value)}),r}}}function Oe(e,t){return{kind:"validation",type:"regex",reference:Oe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&!this.requirement.test(r.value)&&x(this,"format",r,i),r}}}function F(e){return{kind:"validation",type:"url",reference:F,async:!1,expects:null,requirement(t){try{return new URL(t),!0}catch{return!1}},message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&x(this,"URL",t,r),t}}}function Ot(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function be(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function ne(){return{kind:"schema",type:"any",reference:ne,expects:"any",async:!1,get"~standard"(){return O(this)},"~run"(e){return e.typed=!0,e}}}function R(e,t){return{kind:"schema",type:"array",reference:R,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a=r.value;if(Array.isArray(a)){r.typed=!0,r.value=[];for(let s=0;s<a.length;s++){let c=a[s],m=this.item["~run"]({value:c},i);if(m.issues){let l={type:"array",origin:"value",input:a,key:s,value:c};for(let h of m.issues)h.path?h.path.unshift(l):h.path=[l],r.issues?.push(h);if(r.issues||(r.issues=m.issues),i.abortEarly){r.typed=!1;break}}m.typed||(r.typed=!1),r.value.push(m.value)}}else x(this,"type",r,i);return r}}}function C(e){return{kind:"schema",type:"boolean",reference:C,expects:"boolean",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return typeof t.value=="boolean"?t.typed=!0:x(this,"type",t,r),t}}}function Je(e,t){return{kind:"schema",type:"custom",reference:Je,expects:"unknown",async:!1,check:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){return this.check(r.value)?r.typed=!0:x(this,"type",r,i),r}}}function ce(e,t){return{kind:"schema",type:"literal",reference:ce,expects:te(e),async:!1,literal:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){return r.value===this.literal?r.typed=!0:x(this,"type",r,i),r}}}function Qe(e,t){return{kind:"schema",type:"loose_object",reference:Qe,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a=r.value;if(a&&typeof a=="object"){r.typed=!0,r.value={};for(let s in this.entries){let c=this.entries[s];if(s in a||(c.type==="exact_optional"||c.type==="optional"||c.type==="nullish")&&c.default!==void 0){let m=s in a?a[s]:be(c),l=c["~run"]({value:m},i);if(l.issues){let h={type:"object",origin:"value",input:a,key:s,value:m};for(let p of l.issues)p.path?p.path.unshift(h):p.path=[h],r.issues?.push(p);if(r.issues||(r.issues=l.issues),i.abortEarly){r.typed=!1;break}}l.typed||(r.typed=!1),r.value[s]=l.value}else if(c.fallback!==void 0)r.value[s]=Ot(c);else if(c.type!=="exact_optional"&&c.type!=="optional"&&c.type!=="nullish"&&(x(this,"key",r,i,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:a,key:s,value:a[s]}]}),i.abortEarly))break}if(!r.issues||!i.abortEarly)for(let s in a)Dt(a,s)&&!(s in this.entries)&&(r.value[s]=a[s])}else x(this,"type",r,i);return r}}}function et(e){return{kind:"schema",type:"never",reference:et,expects:"never",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return x(this,"type",t,r),t}}}function _(e,t){return{kind:"schema",type:"nullable",reference:_,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return O(this)},"~run"(r,i){return r.value===null&&(this.default!==void 0&&(r.value=be(this,r,i)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,i)}}}function G(e,t){return{kind:"schema",type:"nullish",reference:G,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return O(this)},"~run"(r,i){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=be(this,r,i)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,i)}}}function U(e){return{kind:"schema",type:"number",reference:U,expects:"number",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:x(this,"type",t,r),t}}}function g(e,t){return{kind:"schema",type:"object",reference:g,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a=r.value;if(a&&typeof a=="object"){r.typed=!0,r.value={};for(let s in this.entries){let c=this.entries[s];if(s in a||(c.type==="exact_optional"||c.type==="optional"||c.type==="nullish")&&c.default!==void 0){let m=s in a?a[s]:be(c),l=c["~run"]({value:m},i);if(l.issues){let h={type:"object",origin:"value",input:a,key:s,value:m};for(let p of l.issues)p.path?p.path.unshift(h):p.path=[h],r.issues?.push(p);if(r.issues||(r.issues=l.issues),i.abortEarly){r.typed=!1;break}}l.typed||(r.typed=!1),r.value[s]=l.value}else if(c.fallback!==void 0)r.value[s]=Ot(c);else if(c.type!=="exact_optional"&&c.type!=="optional"&&c.type!=="nullish"&&(x(this,"key",r,i,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:a,key:s,value:a[s]}]}),i.abortEarly))break}}else x(this,"type",r,i);return r}}}function d(e,t){return{kind:"schema",type:"optional",reference:d,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return O(this)},"~run"(r,i){return r.value===void 0&&(this.default!==void 0&&(r.value=be(this,r,i)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,i)}}}function S(e,t){return{kind:"schema",type:"picklist",reference:S,expects:Xe(e.map(te),"|"),async:!1,options:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){return this.options.includes(r.value)?r.typed=!0:x(this,"type",r,i),r}}}function I(e,t,r){return{kind:"schema",type:"record",reference:I,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return O(this)},"~run"(i,a){let s=i.value;if(s&&typeof s=="object"){i.typed=!0,i.value={};for(let c in s)if(Dt(s,c)){let m=s[c],l=this.key["~run"]({value:c},a);if(l.issues){let p={type:"object",origin:"key",input:s,key:c,value:m};for(let b of l.issues)b.path=[p],i.issues?.push(b);if(i.issues||(i.issues=l.issues),a.abortEarly){i.typed=!1;break}}let h=this.value["~run"]({value:m},a);if(h.issues){let p={type:"object",origin:"value",input:s,key:c,value:m};for(let b of h.issues)b.path?b.path.unshift(p):b.path=[p],i.issues?.push(b);if(i.issues||(i.issues=h.issues),a.abortEarly){i.typed=!1;break}}(!l.typed||!h.typed)&&(i.typed=!1),l.typed&&(i.value[l.value]=h.value)}}else x(this,"type",i,a);return i}}}function o(e){return{kind:"schema",type:"string",reference:o,expects:"string",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return typeof t.value=="string"?t.typed=!0:x(this,"type",t,r),t}}}function Pt(e){let t;if(e)for(let r of e)t?t.push(...r.issues):t=r.issues;return t}function Ee(e,t){return{kind:"schema",type:"union",reference:Ee,expects:Xe(e.map(r=>r.expects),"|"),async:!1,options:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a,s,c;for(let m of this.options){let l=m["~run"]({value:r.value},i);if(l.typed)if(l.issues)s?s.push(l):s=[l];else{a=l;break}else c?c.push(l):c=[l]}if(a)return a;if(s){if(s.length===1)return s[0];x(this,"type",r,i,{issues:Pt(s)}),r.typed=!0}else{if(c?.length===1)return c[0];x(this,"type",r,i,{issues:Pt(c)})}return r}}}function J(){return{kind:"schema",type:"unknown",reference:J,expects:"unknown",async:!1,get"~standard"(){return O(this)},"~run"(e){return e.typed=!0,e}}}function tt(e,t,r){return{kind:"schema",type:"variant",reference:tt,expects:"Object",async:!1,key:e,options:t,message:r,get"~standard"(){return O(this)},"~run"(i,a){let s=i.value;if(s&&typeof s=="object"){let c,m=0,l=this.key,h=[],p=n((b,E)=>{for(let w of b.options){if(w.type==="variant")p(w,new Set(E).add(w.key));else{let D=!0,L=0;for(let P of E){let N=w.entries[P];if(P in s?N["~run"]({typed:!1,value:s[P]},{abortEarly:!0}).issues:N.type!=="exact_optional"&&N.type!=="optional"&&N.type!=="nullish"){D=!1,l!==P&&(m<L||m===L&&P in s&&!(l in s))&&(m=L,l=P,h=[]),l===P&&h.push(w.entries[P].expects);break}L++}if(D){let P=w["~run"]({value:s},a);(!c||!c.typed&&P.typed)&&(c=P)}}if(c&&!c.issues)break}},"parseOptions");if(p(this,new Set([this.key])),c)return c;x(this,"type",i,a,{input:s[l],expected:Xe(h,"|"),path:[{type:"object",origin:"value",input:s,key:l,value:s[l]}]})}else x(this,"type",i,a);return i}}}function rt(e,t,r){let i=e["~run"]({value:t},Ye(r));if(i.issues)throw new Ze(i.issues);return i.value}function f(...e){return{...e[0],pipe:e,get"~standard"(){return O(this)},"~run"(t,r){for(let i of e)if(i.kind!=="metadata"){if(t.issues&&(i.kind==="schema"||i.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=i["~run"](t,r))}return t}}}function Se(e,t,r){let i=e["~run"]({value:t},Ye(r));return{typed:i.typed,success:!i.issues,output:i.value,issues:i.issues}}var Ke,Zn,Qn,ti,Ze,ni,bo,ii,j=u(()=>{n(Ye,"getGlobalConfig");n(Jn,"getGlobalMessage");n(ei,"getSchemaMessage");n(ri,"getSpecificMessage");n(te,"_stringify");n(x,"_addIssue");n(O,"_getStandardProps");n(Dt,"_isValidObjectKey");n(Xe,"_joinExpects");Ze=class extends Error{static{n(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}},ni=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,bo=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u"),ii=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z|[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;n(K,"email");n($,"isoTimestamp");n(Pe,"length");n(De,"maxLength");n(ue,"maxValue");n(v,"minLength");n(re,"minValue");n(Oe,"regex");n(F,"url");n(Ot,"getFallback");n(be,"getDefault");n(ne,"any");n(R,"array");n(C,"boolean");n(Je,"custom");n(ce,"literal");n(Qe,"looseObject");n(et,"never");n(_,"nullable");n(G,"nullish");n(U,"number");n(g,"object");n(d,"optional");n(S,"picklist");n(I,"record");n(o,"string");n(Pt,"_subIssues");n(Ee,"union");n(J,"unknown");n(tt,"variant");n(rt,"parse");n(f,"pipe");n(Se,"safeParse")});var xe,nt,xo,it=u(()=>{"use strict";xe={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"},nt={PAYMENT:"payment",SUBSCRIPTION:"subscription"},xo={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}});var To,Ro,Co,Io,Po,Do,oi,si,ai,Oo,_o,No,_t=u(()=>{"use strict";j();it();To=g({userId:d(o()),productId:d(o()),priceId:o(),successUrl:f(o(),F()),cancelUrl:f(o(),F()),customerEmail:d(f(o(),K())),userEmail:d(f(o(),K())),metadata:d(I(o(),o())),allowPromotionCodes:d(C()),mode:d(S([nt.PAYMENT,nt.SUBSCRIPTION]))}),Ro=g({sessionId:o(),sessionUrl:_(f(o(),F()))}),Co=g({userId:o(),tier:o(),status:S(Object.values(xe)),subscriptionId:_(o()),customerId:o(),subscriptionEnd:_(f(o(),$())),cancelAtPeriodEnd:C(),updatedAt:f(o(),$())}),Io=g({tier:o(),subscriptionId:_(o()),customerId:o(),status:S(Object.values(xe)),subscriptionEnd:_(f(o(),$())),cancelAtPeriodEnd:C(),updatedAt:f(o(),$()),isDefault:d(C())}),Po=g({id:o(),type:o(),data:g({object:ne()}),created:f(o(),$())}),Do=Qe({userId:d(o()),firebaseUid:d(o()),productType:d(o())}),oi=g({type:ce("StripePayment"),name:f(o(),v(1,"Product name is required")),description:d(o()),price:o(),currency:d(f(o(),Pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:f(o(),v(1,"Stripe price ID is required")),tier:f(o(),v(1,"Tier is required")),duration:f(o(),v(1,"Duration is required")),allowPromotionCodes:d(C()),metadata:d(I(o(),o()))}),si=g({type:ce("StripeSubscription"),name:f(o(),v(1,"Product name is required")),description:d(o()),price:o(),currency:d(f(o(),Pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:f(o(),v(1,"Stripe price ID is required")),tier:f(o(),v(1,"Tier is required")),duration:S(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:d(C()),metadata:d(I(o(),o()))}),ai=tt("type",[oi,si]),Oo=I(o(),ai),_o=I(o(),g({name:o(),price:o(),currency:o(),description:d(o()),features:d(R(o())),priceId:o(),allowPromotionCodes:d(C())})),No=I(o(),g({type:S(["StripePayment","StripeSubscription"]),name:o(),price:U(),currency:o(),priceId:o(),tier:o(),duration:o(),description:d(o()),metadata:d(I(o(),o())),allowPromotionCodes:d(C())}))});var Nt=u(()=>{"use strict"});var ot=u(()=>{"use strict";it();_t();Nt()});var $o,ui,Go,Ft=u(()=>{"use strict";j();We();ot();$o=g({id:o(),email:d(_(f(o(),K()))),displayName:d(_(o())),photoURL:d(_(f(o(),F()))),emailVerified:d(C()),lastLoginAt:d(o()),providerData:d(R(g({providerId:o(),uid:o(),email:d(_(f(o(),K()))),displayName:d(_(o())),photoURL:d(_(f(o(),F()))),phoneNumber:d(_(o()))}))),role:d(S(Object.values(Z))),customClaims:d(I(o(),ne()))}),ui=g({userId:o(),tier:S(Object.values(Rt)),status:S(Object.values(xe)),isActive:d(C()),features:d(R(o())),subscriptionId:_(o()),customerId:o(),subscriptionEnd:_(f(o(),$())),cancelAtPeriodEnd:C(),updatedAt:f(o(),$())}),Go=g({role:d(S(Object.values(Z))),subscription:d(ui),features:d(R(S(Object.values(Ct)))),permissions:d(R(S(Object.values(It)))),githubAccess:d(g({username:d(o()),teamAccess:d(R(o())),repoAccess:d(R(o()))}))})});var Ut=u(()=>{"use strict"});var Mt=u(()=>{"use strict"});var Lt=u(()=>{"use strict";We();Ft();Ut();Mt()});var Bt=u(()=>{"use strict"});var qt=u(()=>{"use strict"});var ie,_e=u(()=>{"use strict";ie={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"}});var ns,Vt=u(()=>{"use strict";_e();ns={EQ:ie.EQ,NEQ:ie.NEQ,LT:ie.LT,LTE:ie.LTE,GT:ie.GT,GTE:ie.GTE}});var jt=u(()=>{"use strict"});var $t=u(()=>{"use strict"});var cs,ls,ps,ds,fs,Gt=u(()=>{"use strict";j();_e();cs=g({collection:f(o(),v(1,"Collection name is required")),data:I(o(),J()),idempotencyKey:d(o())}),ls=g({collection:f(o(),v(1,"Collection name is required")),id:f(o(),v(1,"Entity ID is required"))}),ps=g({collection:f(o(),v(1,"Collection name is required")),id:f(o(),v(1,"Entity ID is required")),data:I(o(),J()),merge:d(C(),!1)}),ds=g({collection:f(o(),v(1,"Collection name is required")),id:f(o(),v(1,"Entity ID is required"))}),fs=g({collection:f(o(),v(1,"Collection name is required")),limit:d(f(U(),re(1),ue(1e3)),1e3),offset:d(f(U(),re(0)),0),orderBy:d(o()),orderDirection:d(S(["asc","desc"]),"desc"),where:d(R(g({field:o(),operator:S(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:J()})))})});var Ht=u(()=>{"use strict"});var zt=u(()=>{"use strict";qt();Vt();jt();_e();$t();Gt();Ht()});var ke,Ne,st,A,Wt=u(()=>{"use strict";ke={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},Ne={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},st={[ke.PERMISSION_DENIED]:{type:Ne.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[ke.NOT_FOUND]:{type:Ne.NOT_FOUND,message:"The requested resource was not found"},[ke.ALREADY_EXISTS]:{type:Ne.ALREADY_EXISTS,message:"The resource already exists"},[ke.INVALID_ARGUMENT]:{type:Ne.VALIDATION_ERROR,message:"Invalid argument provided"}},A=class e extends Error{static{n(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=ke.INTERNAL,i){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=i?.details,this.source=i?.source,this.originalError=i?.originalError,this.context=i?.context,this.displayable=i?.displayable??!0,this.userMessageProvided=i?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}}});var Kt=u(()=>{"use strict";Wt()});var Yt=u(()=>{"use strict"});var Xt=u(()=>{"use strict"});var Zt=u(()=>{"use strict"});var Jt=u(()=>{"use strict"});var Qt=u(()=>{"use strict"});var er=u(()=>{"use strict"});var tr=u(()=>{"use strict";Xt();Zt();Jt();Qt();er()});var rr=u(()=>{"use strict"});var nr=u(()=>{"use strict";rr()});var ir=u(()=>{"use strict"});var or=u(()=>{"use strict";ir()});var sr=u(()=>{"use strict"});var ar=u(()=>{"use strict";sr()});var ur=u(()=>{"use strict"});var cr=u(()=>{"use strict";ur()});var lr=u(()=>{"use strict"});var pr=u(()=>{"use strict"});var dr=u(()=>{"use strict"});var fr=u(()=>{"use strict";lr();pr();dr()});var mr=u(()=>{"use strict"});var gr=u(()=>{"use strict";mr()});var yr,at=u(()=>{"use strict";yr=["pull","push","admin","maintain","triage"]});var hr=u(()=>{"use strict"});var ut,li,Js,Qs,ea,ta,ra,na,ia,vr=u(()=>{"use strict";j();at();ut=g({owner:f(o(),v(1,"Repository owner is required")),repo:f(o(),v(1,"Repository name is required"))}),li=S([...yr]),Js=g({userId:f(o(),v(1,"User ID is required")),githubUsername:f(o(),v(1,"GitHub username is required")),repoConfig:ut,permission:d(li,"push"),customClaims:d(I(o(),ne()))}),Qs=g({userId:f(o(),v(1,"User ID is required")),githubUsername:f(o(),v(1,"GitHub username is required")),repoConfig:ut}),ea=g({userId:f(o(),v(1,"User ID is required")),githubUsername:f(o(),v(1,"GitHub username is required")),repoConfig:ut}),ta=g({provider:o(),purpose:S(["authentication","api-access"]),code:f(o(),v(1,"Authorization code is required")),redirectUri:f(o(),F("Valid redirect URI is required")),codeVerifier:d(o()),state:d(o()),instance:d(f(o(),F()))}),ra=g({provider:o(),refreshToken:f(o(),v(1,"Refresh token is required")),redirectUri:f(o(),F("Valid redirect URI is required"))}),na=g({provider:o()}),ia=g({userId:f(o(),v(1,"User ID is required"))})});var br=u(()=>{"use strict";at();hr();vr()});var Er=u(()=>{"use strict"});var Sr,pi,Fe,di,fi,mi,gi,pa,da,xr=u(()=>{"use strict";j();Sr=g({name:o(),color:o(),icon:o(),customParameters:d(I(o(),o())),button:g({backgroundColor:o(),textColor:o(),borderColor:o(),hoverBackgroundColor:o(),focusOutlineColor:o(),fontWeight:d(o(),"500"),textKey:d(o())})}),pi=g({...Sr.entries,type:S(["auth","both"]),scopes:d(R(o())),firebaseProviderId:d(o())}),Fe=Ee([ce(""),f(o(),F())]),di=g({authUrl:Fe,tokenUrl:Fe,profileUrl:Fe,revokeUrl:d(Fe)}),fi=g({authentication:d(R(o())),"api-access":R(o())}),mi=d(g({pkce:d(C(),!1),codeChallengeMethod:d(S(["S256","plain"]),"S256")})),gi=g({...Sr.entries,type:S(["oauth","both"]),scopes:fi,endpoints:di,capabilities:mi}),pa=I(o(),pi),da=I(o(),gi)});var kr=u(()=>{"use strict"});var wr=u(()=>{"use strict";Er();xr();kr()});var Ar=u(()=>{"use strict"});var Tr=u(()=>{"use strict"});var Rr=u(()=>{"use strict";Ar();Tr()});var Cr=u(()=>{"use strict"});var Ir=u(()=>{"use strict";Cr()});var Pr=u(()=>{"use strict"});var Dr=u(()=>{"use strict";Pr()});var Or,ka,_r=u(()=>{"use strict";Or={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},ka={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Or.ANALYTICS},marketing:{requiresConsent:Or.MARKETING}}});var Nr=u(()=>{"use strict";_r()});var Fr=u(()=>{"use strict"});var Ur=u(()=>{"use strict"});var Mr=u(()=>{"use strict";Fr();Ur()});var Y=u(()=>{"use strict";Lt();ot();Bt();zt();Kt();Yt();tr();nr();or();ar();cr();fr();gr();br();wr();Rr();Ir();Dr();Nr();Mr()});var we=u(()=>{"use strict";Y()});function Lr(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}var ct=u(()=>{"use strict";n(Lr,"detectErrorSource")});function X(e){return(t,r)=>{if(t instanceof A)return t;if(typeof t!="object"||t===null){let m=typeof t=="string"?t:e.defaultErrorMessage;return new A(r||m,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let i;e.extractErrorCode?i=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(i=t.code);let a=e.defaultErrorCode;i&&e.errorCodeMapping&&i in e.errorCodeMapping&&(a=e.errorCodeMapping[i]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),i&&e.friendlyMessageMapping&&i in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[i]),s||(s=e.defaultErrorMessage);let c;return e.processMetadata?c=e.processMetadata(t):(c={originalError:t},i&&(c.originalCode=i)),"originalError"in c||(c.originalError=t),new A(r||s,a,{details:c,source:e.errorSource})}}var Ue,lt=u(()=>{"use strict";we();n(X,"createErrorHandler");Ue={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"}});function dt(e,t,r){return e instanceof A?e:(Br[t]||Br.unknown)(e,r)}var le,yi,pt,Q,hi,vi,Br,ft=u(()=>{"use strict";j();Y();we();lt();le={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},yi={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},pt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},Q={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...Ue},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...Ue},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(yi).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:n(e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},"extractErrorCode"),processMetadata:n(e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:Ue,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:le.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:n(e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t},"processMetadata")},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:le["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:le.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:n(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},hi=n(e=>e instanceof Ze?new A(le["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):X(Q.validation)(e),"handleValidationError"),vi=n(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in pt){let t=e,r=pt[t.type]||"unknown";return new A(t.message||le[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&st[e.code]){let t=e,r=st[t.code];if(r){let i=pt[r.type]||"unknown";return new A(r.message||le[i],i,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return X(Q.entity)(e)},"handleEntityError"),Br={auth:X(Q.auth),oauth:X(Q.oauth),api:X(Q.api),firebase:X(Q.firebase),ui:X(Q.ui),validation:hi,entity:vi,unknown:X(Q.unknown)};n(dt,"mapToDoNotDevError")});function qr(e,t,r={}){let i=globalThis.Sentry;i&&i.withScope(a=>{a.setTag("errorSource",t),a.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,c])=>{if(typeof c!="function"&&s!=="originalError")try{a.setExtra(s,c)}catch{a.setExtra(s,`[${typeof c}]`)}}),Object.entries(r).forEach(([s,c])=>{if(typeof c!="function")try{a.setExtra(`context.${s}`,c)}catch{a.setExtra(`context.${s}`,`[${typeof c}]`)}}),(e.details?.userId||r.userId)&&a.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),i.captureException(e)})}var mt=u(()=>{"use strict";n(qr,"captureErrorToSentry")});function bi(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}function T(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:i,context:a={},log:s=!0,reportToSentry:c=!0,showNotification:m=!1,severity:l="error"}=r,h=Lr(e),p=e instanceof A?e:dt(e,h,i);if(i&&!p.userMessageProvided&&(p.message.includes("Error")||p.message.includes("Failed")||p.message.length<10?p=new A(i,p.code,{details:{...p.details,originalMessage:p.message},source:h,userMessageProvided:!0}):p=new A(p.message,p.code,{details:{...p.details,userMessage:i},source:h,userMessageProvided:!0})),s){let b=bi()||typeof window<"u"&&window.__DNDEV_DEBUG,E={code:p.code,message:p.message,source:h};switch(l){case"warning":console.warn(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details}:E);break;case"info":console.info(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details}:E);break;case"success":console.log(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details}:E);break;default:console.error(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details,stack:p.stack}:E)}}return c&&qr(p,h,a),m&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),p}var Vr=u(()=>{"use strict";we();ct();ft();mt();n(bi,"isDev");n(T,"handleError")});var Me=u(()=>{"use strict";we();Vr();ct();ft();mt();lt()});var jr=u(()=>{"use strict";Me()});var $r=u(()=>{"use strict";Me()});var Gr=u(()=>{"use strict";jr();$r()});var Hr=u(()=>{"use strict"});var zr=u(()=>{"use strict"});var Wr=u(()=>{"use strict"});var Kr=u(()=>{"use strict"});var Yr=u(()=>{"use strict"});var Xr=u(()=>{"use strict"});var Zr=u(()=>{"use strict"});var Jr=u(()=>{"use strict"});var Qr=u(()=>{"use strict"});var Zu,gt=u(()=>{"use strict";Y();Zu={[Z.GUEST]:0,[Z.USER]:1,[Z.ADMIN]:2,[Z.SUPER]:3}});var en=u(()=>{"use strict";Y()});function tn(e){if(!yt)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let t=yt[e];if(!t)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return t}function rn(e){return!!yt?.[e]}var yt,nn=u(()=>{"use strict";yt=null;n(tn,"getProvider");n(rn,"hasProvider")});function on(e,...t){let r=null,i=!1;return n(function(){if(r!==null)return r;if(i)throw new Error("Circular dependency detected in singleton initialization");i=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{i=!1}},"getInstance")}var sn=u(()=>{"use strict";n(on,"createSingleton")});var an=u(()=>{"use strict"});var ht=u(()=>{"use strict";gt()});var un=u(()=>{"use strict";ht()});var cn=u(()=>{"use strict"});var ln=u(()=>{"use strict"});var pn=u(()=>{"use strict";un();cn();ht();ln()});var dn=u(()=>{"use strict"});var fn=u(()=>{"use strict";dn()});var mn=u(()=>{"use strict"});var gn=u(()=>{"use strict";Gr();Hr();zr();Wr();Kr();Me();Yr();Xr();Zr();Jr();Qr();gt();en();nn();sn();an();pn();fn();mn()});var yn=u(()=>{"use strict"});var hn=u(()=>{"use strict"});var vn=u(()=>{"use strict"});var ee=u(()=>{gn();yn();hn();vn()});var bn=u(()=>{"use strict"});var En=u(()=>{"use strict"});function y(e,t){Si.set(e,t)}function k(e,t){return t?e:G(e)}function Li(){y("text",Le),y("textarea",Le),y("richtext",Le),y("color",Le),y("email",xi),y("password",ki),y("url",wi),y("tel",_i),y("iban",Ni),y("number",pe),y("currency",pe),y("price",Mi),y("range",pe),y("year",pe),y("rating",pe),y("duration",pe),y("boolean",Sn),y("checkbox",Sn),y("gdprConsent",Ui),y("date",de),y("datetime-local",de),y("time",de),y("week",de),y("month",de),y("timestamp",de),y("file",xn),y("files",kn),y("document",xn),y("documents",kn),y("image",Ai),y("images",Ti),y("geopoint",Ri),y("address",Ci),y("map",Ii),y("array",Pi),y("select",vt),y("multiselect",Di),y("radio",vt),y("combobox",vt),y("switch",Fi),y("reference",Oi),y("hidden",bt),y("avatar",bt),y("badge",bt),y("submit",wn),y("reset",wn)}var Si,Le,xi,ki,wi,pe,Sn,de,An,xn,kn,Tn,Ai,Ti,Ri,Ci,Ii,Pi,vt,Di,Oi,bt,_i,Ni,wn,Fi,Ui,Mi,Et=u(()=>{"use strict";j();Si=new Map;n(y,"registerSchemaGenerator");n(k,"applyRequired");Le=n(e=>{let t=[];e.validation?.minLength!==void 0&&t.push(v(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(De(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(Oe(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?f(o(),...t):o();return k(r,e.validation?.required)},"textSchema"),xi=n(e=>{let t=f(o(),K("Invalid email address"));return k(t,e.validation?.required)},"emailSchema"),ki=n(e=>{let t=e.validation?.minLength!==void 0?f(o(),v(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):o();return k(t,e.validation?.required)},"passwordSchema"),wi=n(e=>{let t=f(o(),F("Invalid URL"));return k(t,e.validation?.required)},"urlSchema"),pe=n(e=>{let t=[];e.validation?.min!==void 0&&t.push(re(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(ue(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?f(U(),...t):U();return k(r,e.validation?.required)},"numberSchema"),Sn=n(e=>{let t=C();return k(t,e.validation?.required)},"booleanSchema"),de=n(e=>{let t=f(o(),$("Invalid date format"));return k(t,e.validation?.required)},"dateSchema"),An=g({url:o(),filename:o(),size:U(),mimeType:G(o()),uploadedAt:G(o())}),xn=n(e=>{let t=_(An);return k(t,e.validation?.required)},"fileSchema"),kn=n(e=>{let t=R(An);return k(t,e.validation?.required)},"filesSchema"),Tn=g({fullUrl:o(),thumbUrl:o()}),Ai=n(e=>k(Tn,e.validation?.required),"pictureSchema"),Ti=n(e=>{let t=R(Tn);return k(t,e.validation?.required)},"picturesSchema"),Ri=n(e=>{let t=g({lat:U(),lng:U()});return k(t,e.validation?.required)},"geopointSchema"),Ci=n(e=>{let t=g({formatted_address:o(),latitude:U(),longitude:U(),street_number:G(o()),route:G(o()),locality:G(o()),administrative_area_level_1:G(o()),administrative_area_level_2:G(o()),country:G(o()),postal_code:G(o())});return k(t,e.validation?.required)},"addressSchema"),Ii=n(e=>{let t=I(o(),J());return k(t,e.validation?.required)},"mapSchema"),Pi=n(e=>{let t=R(J());return k(t,e.validation?.required)},"arraySchema"),vt=n(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let i=t.map(s=>s.value),a=S(i);return k(a,e.validation?.required)}let r=Ee([o(),U()]);return k(r,e.validation?.required)},"selectSchema"),Di=n(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let i=t.map(s=>s.value),a=R(S(i));return k(a,e.validation?.required)}let r=R(o());return k(r,e.validation?.required)},"multiselectSchema"),Oi=n(e=>{let t=f(o(),v(1,"Invalid ID format"));return k(t,e.validation?.required)},"referenceSchema"),bt=n(e=>{let t=o();return k(t,e.validation?.required)},"stringSchema"),_i=n(e=>{let t=o();return k(t,e.validation?.required)},"telSchema"),Ni=n(e=>{let t=e.validation?.minLength??15,r=e.validation?.maxLength??34,i=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",a=[];if(t!==void 0&&a.push(v(t,`IBAN must be at least ${t} characters`)),r!==void 0&&a.push(De(r,`IBAN must not exceed ${r} characters`)),i){let c=typeof i=="string"?new RegExp(i):i;a.push(Oe(c,"Invalid IBAN format"))}let s=a.length>0?f(o(),...a):o();return k(s,e.validation?.required)},"ibanSchema"),wn=n(()=>et(),"neverSchema"),Fi=n(e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let i=[t.checkedValue,t.uncheckedValue],a=S(i);return k(a,e.validation?.required)}let r=C();return k(r,e.validation?.required)},"switchSchema"),Ui=n(e=>Je(r=>e.validation?.required?typeof r=="object"&&r!==null?r.gdprConsent===!0:!1:r===!1||r===null||r===void 0?!0:typeof r=="object"&&r!==null?r.gdprConsent===!0:!1,"GDPR consent must be given"),"gdprConsentSchema"),Mi=n(e=>{let t=g({amount:U(),currency:d(o()),vatIncluded:d(C()),discountPercent:d(f(U(),re(0),ue(100)))});return k(t,e.validation?.required)},"priceSchema");n(Li,"registerBuiltinSchemas");Li()});var St=u(()=>{"use strict";ee()});var xt=u(()=>{"use strict";ee()});var Rn=u(()=>{"use strict";St();xt()});var Cn=u(()=>{"use strict";En();Et();St();Rn();xt()});var In=u(()=>{"use strict";ee()});var Pn,Dn,Ul,On,Be=u(()=>{"use strict";Y();Pn=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],Dn=["id","createdAt","updatedAt","createdById","updatedById"],Ul=[...Dn,"status"],On={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...Pn]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}}});var _n=u(()=>{"use strict";Y();ee();Be()});var Nn=u(()=>{"use strict";Y();ee();Et();Be()});var Fn=u(()=>{"use strict"});var Un=u(()=>{"use strict"});var Mn=u(()=>{"use strict";Cn();In();Be();_n();Nn();Fn();Un()});var Ln=u(()=>{"use strict";bn();Mn()});var q=u(()=>{ee();Y();Ln();ee()});import{initializeApp as Bn,getApps as qi,cert as Vi}from"firebase-admin/app";import{getAuth as ji}from"firebase-admin/auth";import{getFirestore as $i}from"firebase-admin/firestore";import{getFunctions as Gi}from"firebase-admin/functions";function Hi(){let e=qi(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=Bn({credential:Vi({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
22
+ `)}),projectId:process.env.FIREBASE_PROJECT_ID}):t=Bn():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:ji(t),firestore:$i(t),functions:Gi(t)}}async function Ae(){let e=kt();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}function M(){let e=kt();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}function oe(){let e=kt();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}var kt,qe=u(()=>{"use strict";q();n(Hi,"initializeFirebaseAdminServices");kt=on(Hi);n(Ae,"getFirebaseAdminApp");n(M,"getFirebaseAdminAuth");n(oe,"getFirebaseAdminFirestore")});var qn=u(()=>{"use strict";q();qe()});var Ve,Pp,fe,Dp,Te=u(()=>{"use strict";q();qe();Ve={async getServerAdmin(){try{return Ae()}catch(e){throw T(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return oe()}catch(e){throw T(e,"Error getting Admin Firestore")}},async generateServerId(){return(await Ve.getServerFirestore()).collection("_").doc().id}},Pp=Ve.getServerAdmin,fe=Ve.getServerFirestore,Dp=Ve.generateServerId});function zi(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw T(new Error("Invalid Date object"),{context:{value:e}});return e.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw T(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw T(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw T(t,"Failed to convert to ISO string")}}function Wi(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}function me(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&e!==null&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e,i=r.data();return{id:r.id,...me(i)}}if(Array.isArray(e))return e.map(r=>me(r));if(Wi(e))return zi(e);if(typeof e=="object"&&e!==null){let r={};for(let[i,a]of Object.entries(e))r[i]=me(a);return r}return e}function Re(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>Re(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){let r={};for(let[i,a]of Object.entries(e))t.includes(i)||a!==void 0&&(r[i]=Re(a,t));return r}return e}var je=u(()=>{"use strict";q();n(zi,"firestoreToISOString");n(Wi,"isTimestamp");n(me,"transformFirestoreData");n(Re,"prepareForFirestore")});var ge,z,ye,Bp,qp,Vp,jp,$p,Gp,Vn=u(()=>{"use strict";j();q();Te();je();ge=typeof window<"u",z={async batchWrite(e,t,r,i,a={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:s="id",generateIds:c=!0,maxBatchSize:m=450,removeFields:l=[],validate:h=!!i}=a,p={successes:0,failures:0,failedItems:[]};try{let b=[],E=await fe(),w=E.batch(),D=0;for(let P=0;P<t.length;P++){let N=t[P];if(!N){p.failures++,p.failedItems?.push({index:P,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!N[s])throw T(new Error(`Missing ID for delete operation (${s})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:s,operation:r}});let B=E.collection(e).doc(N[s]);w.delete(B)}else{if(h&&i)try{rt(i,N)}catch(Yn){throw T(Yn,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:s,itemId:N[s]}})}let B=N[s];if(!B&&r==="create"&&c)B=E.collection(e).doc().id,N={...N,[s]:B};else if(!B)throw T(new Error(`Missing ID for ${r} operation (${s})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:s,operation:r}});let ze=[s,...l],ae=Re(N,ze),Tt=E.collection(e).doc(B);r==="create"?w.create(Tt,ae):r==="update"&&w.update(Tt,ae)}D++,D>=m&&(b.push({batch:w,size:D}),w=E.batch(),D=0)}catch(B){p.failures++,p.failedItems?.push({index:P,error:B instanceof Error?B:new Error(String(B))})}}D>0&&b.push({batch:w,size:D});let L=0;for(let{batch:P,size:N}of b){try{await P.commit(),p.successes+=N}catch(B){let ze=B instanceof Error?B:new Error(String(B));for(let ae=L;ae<L+N;ae++)p.failures++,p.failedItems?.push({index:ae,error:ze})}L+=N}return p}catch(b){throw T(b,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:p.successes+p.failures,successCount:p.successes,failureCount:p.failures}})}},async batchCreate(e,t,r,i={}){return z.batchWrite(e,t,"create",r,i)},async batchUpdate(e,t,r,i={}){return z.batchWrite(e,t,"update",r,i)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){let i=r.idField||"id",a=t.map(s=>({[i]:s}));return z.batchWrite(e,a,"delete",void 0,r)}return z.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await fe()).runTransaction(e)}catch(t){throw T(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:i=30,transform:a=!0}=r;try{let s=[];for(let l=0;l<t.length;l+=i)s.push(t.slice(l,l+i));let c=s.map(async l=>{let b=await(await fe()).collection(e).where("__name__","in",l).get(),E=new Map;return b.forEach(w=>{E.set(w.id,w.data())}),l.map(w=>{let D=E.get(w);return D?a?me({id:w,...D}):{id:w,...D}:null})});return(await Promise.all(c)).flat()}catch(s){throw T(s,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},ye=n(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),Bp=ge?ye("batchWrite"):z.batchWrite,qp=ge?ye("batchCreate"):z.batchCreate,Vp=ge?ye("batchUpdate"):z.batchUpdate,jp=ge?ye("batchDelete"):z.batchDelete,$p=ge?ye("runTransaction"):z.runTransaction,Gp=ge?ye("bulkGet"):z.bulkGet});var jn=u(()=>{"use strict";q()});var $n=u(()=>{"use strict";q();Te();je();jn()});var $e=u(()=>{"use strict";q();Te()});var Gn=u(()=>{"use strict";q();$e();$e()});import{FieldValue as Cd,Query as Id,Timestamp as Pd}from"firebase-admin/firestore";var W=u(()=>{"use strict";qn();qe();Te();Vn();$n();Gn();$e();je()});q();function V(e){let t,r,i;if(e instanceof A)t=e.code,r=e.message,i=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||e.name==="ValiError"))t="invalid-argument",r="Validation failed",i={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||e.name==="EntityHookError")){let a=e;switch(a.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=a.message,i=void 0}else t="internal",r=e instanceof Error?e.message:"An unexpected error occurred",i=void 0;throw new A(r,t,i?{details:i}:void 0)}n(V,"handleError");q();W();function Yi(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}n(Yi,"extractBearerToken");async function Xi(e,t){try{return t==="supabase"?await Zi(e):t==="firebase"?{uid:(await M().verifyIdToken(e)).uid}:rn("serverAuth")?{uid:(await tn("serverAuth").verifyToken(e)).uid}:{uid:(await M().verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}n(Xi,"verifyToken");async function Zi(e){let{createClient:t}=await import("@supabase/supabase-js"),r=process.env.SUPABASE_URL,i=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!r||!i)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let a=t(r,i,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:s},error:c}=await a.auth.getUser(e);if(c||!s)throw new Error("Invalid or expired token");return{uid:s.id}}n(Zi,"verifySupabaseToken");async function Ge(e,t){let r=Yi(e.headers.authorization),{uid:i}=await Xi(r,t);return i}n(Ge,"verifyAuthToken");W();var Ji=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function Vd(e){let t=new Set(e.allowedClaimKeys);for(let r of t)if(Ji.has(r))throw new Error(`Claim key "${r}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return n(async function(i,a){if(i.method!=="POST")return a.status(405).json({error:"Method not allowed"});try{let s=await Ge(i),{customClaims:c}=i.body;if(!c||typeof c!="object")throw V(new Error("customClaims must be an object"));let m=Object.keys(c).filter(b=>!t.has(b));if(m.length>0)throw V(new Error(`Claim keys not allowed: ${m.join(", ")}`));let p={...(await M().getUser(s)).customClaims||{},...c};return await M().setCustomUserClaims(s,p),a.status(200).json({success:!0,customClaims:p})}catch(s){throw V(s)}},"handler")}n(Vd,"createSetCustomClaimsHandler");import Qi from"stripe";q();W();var He=null;function eo(e){if(!e)throw new Error("Stripe API key is required");let t=process.env.STRIPE_API_VERSION||"2024-12-18.acacia";return He=new Qi(e,{apiVersion:t}),He}n(eo,"initStripe");function to(){if(!He){let e=process.env.STRIPE_SECRET_KEY;if(e)eo(e);else throw new Error("Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.")}return He}n(to,"getStripe");var se=new Proxy({},{get(e,t){return to()[t]}});function he(){if(!process.env.STRIPE_SECRET_KEY)throw new Error("Missing STRIPE_SECRET_KEY environment variable")}n(he,"validateStripeEnvironment");j();W();import{logger as Hn}from"firebase-functions/v2";async function wt(e){try{await oe().collection("payment_metrics").doc().set({...e,recordedAt:new Date().toISOString()}),Hn.info("Payment metrics recorded",{operation:e.operation,status:e.status,userId:e.userId})}catch(t){Hn.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:e})}}n(wt,"recordPaymentMetrics");W();import{logger as zn}from"firebase-functions/v2";async function Wn(e,t){let r=oe(),i=r.collection("rateLimits").doc(e);try{let a=Date.now(),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(a+t.windowMs),blockRemainingSeconds:null};return await r.runTransaction(async c=>{let m=await c.get(i);if(!m.exists){c.set(i,{attempts:1,windowStart:a,blockUntil:null,lastUpdated:a}),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(a+t.windowMs),blockRemainingSeconds:null};return}let l=m.data();if(l.blockUntil&&a<l.blockUntil){s={allowed:!1,remaining:0,resetAt:new Date(l.blockUntil),blockRemainingSeconds:Math.ceil((l.blockUntil-a)/1e3)};return}if(a>=l.windowStart+t.windowMs){c.set(i,{attempts:1,windowStart:a,blockUntil:null,lastUpdated:a}),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(a+t.windowMs),blockRemainingSeconds:null};return}if(l.attempts>=t.maxAttempts){let h=a+t.blockDurationMs;c.update(i,{blockUntil:h,lastUpdated:a}),zn.warn("Rate limit exceeded (Firestore)",{key:e,attempts:l.attempts,blockUntil:new Date(h)}),s={allowed:!1,remaining:0,resetAt:new Date(h),blockRemainingSeconds:Math.ceil(t.blockDurationMs/1e3)};return}c.update(i,{attempts:l.attempts+1,lastUpdated:a}),s={allowed:!0,remaining:t.maxAttempts-(l.attempts+1),resetAt:new Date(l.windowStart+t.windowMs),blockRemainingSeconds:null}}),s}catch(a){return zn.error("Rate limit check failed",{key:e,error:a instanceof Error?a.message:String(a)}),{allowed:!0,remaining:t.maxAttempts,resetAt:null,blockRemainingSeconds:null}}}n(Wn,"checkRateLimitWithFirestore");var At={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};function ve(e,t,r,i,a,s){return async(c,m)=>{try{if(c.method!==e)return m.status(405).json({error:"Method not allowed"});let l=Se(t,c.body);if(!l.success)return m.status(400).json({error:`Validation failed: ${l.issues.map(L=>L.message).join(", ")}`});let h=l.output,p=await Ge(c,s),b=`${r}_${p}`,E=At[r]||At.api,w=await Wn(b,E);if(!w.allowed)return a?.audit({type:"rate_limit.exceeded",userId:p,metadata:{operation:r,remaining:0}}),m.status(429).json({error:`Rate limit exceeded. Try again in ${w.blockRemainingSeconds} seconds.`,retryAfter:w.blockRemainingSeconds});let D=await i(c,m,h,{uid:p});return D==null&&console.warn(`[${r}] businessLogic returned ${D} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await wt({operation:r,userId:p,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:c.headers["x-request-id"]||"unknown"}}),D}catch(l){process.env.ENABLE_METRICS==="true"&&await wt({operation:r,userId:c.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:l instanceof Error?l.message:"Unknown error",requestId:c.headers["x-request-id"]||"unknown"}});try{V(l)}catch(h){let p=ro(h);return m.status(p.status).json({error:p.message})}return m.status(500).json({error:"Internal server error"})}}}n(ve,"createVercelBaseFunction");function ro(e){return e instanceof A?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[e.code]??500,message:e.message}:{status:500,message:"Internal server error"}}n(ro,"classifiedToHttp");async function Ce(e,t,r){let a=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");t.customerId||console.warn(`[updateUserSubscription] customerId is undefined for user ${e}. Falling back to userId. This may cause issues with Stripe API calls.`);let s={tier:t.tier,subscriptionId:t.subscriptionId||null,customerId:t.customerId||e,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd||!1,updatedAt:new Date().toISOString(),isDefault:!1},c={...a,subscription:s};await r.setCustomUserClaims(e,c)}n(Ce,"updateUserSubscription");j();W();q();async function Kn(e,t){he();let a=((await t.getUser(e)).customClaims||{}).subscription,s=a?.subscriptionId;if(!s)throw V(new Error("No active subscription found"));let c=await se.subscriptions.update(s,{cancel_at_period_end:!0}),l=["active","canceled","past_due","trialing","incomplete"].includes(c.status)?c.status:"incomplete";return await Ce(e,{tier:a?.tier||"free",status:l,subscriptionEnd:new Date(c.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:!0,subscriptionId:c.id,customerId:c.customer},t),{success:!0,endsAt:new Date(c.current_period_end*1e3).toISOString()}}n(Kn,"cancelUserSubscription");var no=g({userId:o()});async function io(e,t,r,i){let a=i.uid,c=await Kn(a,{async getUser(m){return M().getUser(m)},async setCustomUserClaims(m,l){await M().setCustomUserClaims(m,l)}});return t.status(200).json({success:c.success,cancelAtPeriodEnd:!0,endsAt:c.endsAt})}n(io,"cancelSubscriptionLogic");var oo=n(()=>ve("POST",no,"cancel_subscription",io),"cancelSubscription"),so=oo;j();W();var ao=g({userId:o(),newPriceId:o(),billingConfigKey:o()});async function uo(e,t,r,i,a){he();let s=i.uid,{newPriceId:c,billingConfigKey:m}=r,l=a[m];if(!l||l.type!=="StripeSubscription")throw V(new Error("Invalid plan"));if(l.priceId!==c)throw V(new Error("Price ID mismatch"));let p=(await M().getUser(s)).customClaims?.subscription?.subscriptionId;if(!p)throw V(new Error("No active subscription"));let b=await se.subscriptions.retrieve(p),E=await se.subscriptions.update(p,{items:[{id:b.items.data[0]?.id,price:c}],proration_behavior:"create_prorations"}),D=["active","canceled","past_due","trialing","incomplete"].includes(E.status)?E.status:"incomplete";return await Ce(s,{tier:l.tier,status:D,subscriptionEnd:new Date(E.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:E.cancel_at_period_end,subscriptionId:E.id,customerId:E.customer},{async getUser(L){return M().getUser(L)},async setCustomUserClaims(L,P){await M().setCustomUserClaims(L,P)}}),t.status(200).json({success:!0,newTier:l.tier,newPrice:l.price})}n(uo,"changePlanLogic");var co=n(e=>ve("POST",ao,"change_plan",(t,r,i,a)=>uo(t,r,i,a,e)),"changePlan"),lo=co;j();W();var po=g({userId:o(),returnUrl:d(f(o(),F()))});async function fo(e,t,r,i){he();let a=i.uid,{returnUrl:s}=r,m=(await M().getUser(a)).customClaims?.subscription?.customerId;if(!m)throw V(new Error("No customer found"));let l=await se.billingPortal.sessions.create({customer:m,return_url:s||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:l.url})}n(fo,"createCustomerPortalLogic");var mo=n(()=>ve("POST",po,"create_customer_portal",fo),"createCustomerPortal"),go=mo;var Ie=process.env.FIREBASE_REGION||"europe-west1",Wf={region:Ie,memory:"1GiB",timeoutSeconds:60},Kf={region:Ie,memory:"512MiB",timeoutSeconds:30},Yf={region:Ie,memory:"256MiB",timeoutSeconds:20},Xf={region:Ie,memory:"256MiB",timeoutSeconds:15},Zf={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},Jf=n(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(r=>!process.env[r]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${Ie}`)},"validateEnvironment");W();async function rm(){return await Ae()}n(rm,"initializeFirebaseAdmin");async function nm(){return await Ae()}n(nm,"getFirebaseAdmin");export{Yf as AUTH_CONFIG,Zf as AVAILABLE_REGIONS,Xf as CRUD_CONFIG,Ie as FIREBASE_REGION,Wf as FUNCTION_CONFIG,Kf as STRIPE_CONFIG,so as cancelSubscription,lo as changePlan,go as createCustomerPortal,Vd as createSetCustomClaimsHandler,nm as getFirebaseAdmin,rm as initializeFirebaseAdmin,Ce as updateUserSubscription,Jf as validateEnvironment};
4791
23
  //# sourceMappingURL=index.js.map