@donotdev/core 0.3.1 → 0.3.3

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 (279) hide show
  1. package/functions/index.d.ts +99 -10
  2. package/functions/index.js +20 -18
  3. package/i18n/flags/af.svg +1 -0
  4. package/i18n/flags/al.svg +1 -0
  5. package/i18n/flags/am.svg +1 -0
  6. package/i18n/flags/ar.svg +1 -0
  7. package/i18n/flags/at.svg +1 -0
  8. package/i18n/flags/au.svg +1 -0
  9. package/i18n/flags/az.svg +1 -0
  10. package/i18n/flags/ba.svg +1 -0
  11. package/i18n/flags/bd.svg +1 -0
  12. package/i18n/flags/be.svg +1 -0
  13. package/i18n/flags/bg.svg +1 -0
  14. package/i18n/flags/bn.svg +1 -0
  15. package/i18n/flags/br.svg +1 -0
  16. package/i18n/flags/bs.svg +1 -0
  17. package/i18n/flags/by.svg +1 -0
  18. package/i18n/flags/bzh.svg +1 -0
  19. package/i18n/flags/ca.svg +1 -0
  20. package/i18n/flags/ch.svg +1 -0
  21. package/i18n/flags/co.svg +1 -0
  22. package/i18n/flags/cs.svg +1 -0
  23. package/i18n/flags/cy.svg +1 -0
  24. package/i18n/flags/da.svg +1 -0
  25. package/i18n/flags/de.svg +1 -0
  26. package/i18n/flags/dz.svg +1 -0
  27. package/i18n/flags/ee.svg +1 -0
  28. package/i18n/flags/el.svg +1 -0
  29. package/i18n/flags/en.svg +1 -0
  30. package/i18n/flags/es.svg +1 -0
  31. package/i18n/flags/et.svg +1 -0
  32. package/i18n/flags/eu.svg +1 -0
  33. package/i18n/flags/fa.svg +1 -0
  34. package/i18n/flags/fi.svg +1 -0
  35. package/i18n/flags/fr-cor.svg +1 -0
  36. package/i18n/flags/fr.svg +1 -0
  37. package/i18n/flags/ga.svg +1 -0
  38. package/i18n/flags/gb-sct.svg +1 -0
  39. package/i18n/flags/gb.svg +1 -0
  40. package/i18n/flags/gd.svg +1 -0
  41. package/i18n/flags/ge.svg +1 -0
  42. package/i18n/flags/gl.svg +1 -0
  43. package/i18n/flags/gu.svg +1 -0
  44. package/i18n/flags/he.svg +1 -0
  45. package/i18n/flags/hi.svg +1 -0
  46. package/i18n/flags/hr.svg +1 -0
  47. package/i18n/flags/hu.svg +1 -0
  48. package/i18n/flags/hy.svg +1 -0
  49. package/i18n/flags/id.svg +1 -0
  50. package/i18n/flags/ie.svg +1 -0
  51. package/i18n/flags/in.svg +1 -0
  52. package/i18n/flags/ir.svg +1 -0
  53. package/i18n/flags/is.svg +1 -0
  54. package/i18n/flags/it.svg +1 -0
  55. package/i18n/flags/ja.svg +1 -0
  56. package/i18n/flags/ke.svg +1 -0
  57. package/i18n/flags/kg.svg +1 -0
  58. package/i18n/flags/kh.svg +1 -0
  59. package/i18n/flags/kk.svg +1 -0
  60. package/i18n/flags/km.svg +1 -0
  61. package/i18n/flags/kn.svg +1 -0
  62. package/i18n/flags/ko.svg +1 -0
  63. package/i18n/flags/kz.svg +1 -0
  64. package/i18n/flags/la.svg +1 -0
  65. package/i18n/flags/lb.svg +1 -0
  66. package/i18n/flags/lk.svg +1 -0
  67. package/i18n/flags/lt.svg +1 -0
  68. package/i18n/flags/lv.svg +1 -0
  69. package/i18n/flags/ly.svg +1 -0
  70. package/i18n/flags/ma.svg +1 -0
  71. package/i18n/flags/md.svg +1 -0
  72. package/i18n/flags/mk.svg +1 -0
  73. package/i18n/flags/ml.svg +1 -0
  74. package/i18n/flags/mm.svg +1 -0
  75. package/i18n/flags/mn.svg +1 -0
  76. package/i18n/flags/mr.svg +1 -0
  77. package/i18n/flags/ms.svg +1 -0
  78. package/i18n/flags/mt.svg +1 -0
  79. package/i18n/flags/mx.svg +1 -0
  80. package/i18n/flags/my.svg +1 -0
  81. package/i18n/flags/ne.svg +1 -0
  82. package/i18n/flags/nl.svg +1 -0
  83. package/i18n/flags/no.svg +1 -0
  84. package/i18n/flags/np.svg +1 -0
  85. package/i18n/flags/oc.svg +1 -0
  86. package/i18n/flags/pa.svg +1 -0
  87. package/i18n/flags/pk.svg +1 -0
  88. package/i18n/flags/pl.svg +1 -0
  89. package/i18n/flags/ps.svg +1 -0
  90. package/i18n/flags/pt.svg +1 -0
  91. package/i18n/flags/rm.svg +1 -0
  92. package/i18n/flags/ro.svg +1 -0
  93. package/i18n/flags/ru.svg +1 -0
  94. package/i18n/flags/sa.svg +1 -0
  95. package/i18n/flags/si.svg +1 -0
  96. package/i18n/flags/sk.svg +1 -0
  97. package/i18n/flags/sl.svg +1 -0
  98. package/i18n/flags/sr.svg +1 -0
  99. package/i18n/flags/sv.svg +1 -0
  100. package/i18n/flags/sw.svg +1 -0
  101. package/i18n/flags/ta.svg +1 -0
  102. package/i18n/flags/te.svg +1 -0
  103. package/i18n/flags/th.svg +1 -0
  104. package/i18n/flags/tj.svg +1 -0
  105. package/i18n/flags/tl.svg +1 -0
  106. package/i18n/flags/tn.svg +1 -0
  107. package/i18n/flags/tr.svg +1 -0
  108. package/i18n/flags/ua.svg +1 -0
  109. package/i18n/flags/ur.svg +1 -0
  110. package/i18n/flags/us.svg +1 -0
  111. package/i18n/flags/uz.svg +1 -0
  112. package/i18n/flags/vi.svg +1 -0
  113. package/i18n/flags/za.svg +1 -0
  114. package/i18n/flags/zh.svg +1 -0
  115. package/i18n/locales/eager/dndev_ar.json +2 -1
  116. package/i18n/locales/eager/dndev_da.json +2 -1
  117. package/i18n/locales/eager/dndev_de.json +2 -1
  118. package/i18n/locales/eager/dndev_en.json +2 -1
  119. package/i18n/locales/eager/dndev_es.json +2 -1
  120. package/i18n/locales/eager/dndev_fr.json +2 -1
  121. package/i18n/locales/eager/dndev_it.json +2 -1
  122. package/i18n/locales/eager/dndev_ja.json +2 -1
  123. package/i18n/locales/eager/dndev_ko.json +2 -1
  124. package/i18n/locales/eager/dndev_nl.json +2 -1
  125. package/i18n/locales/eager/dndev_pl.json +2 -1
  126. package/i18n/locales/eager/dndev_pt.json +2 -1
  127. package/i18n/locales/eager/dndev_zh.json +2 -1
  128. package/i18n/locales/lazy/auth_ar.json +19 -2
  129. package/i18n/locales/lazy/auth_da.json +22 -2
  130. package/i18n/locales/lazy/auth_de.json +19 -2
  131. package/i18n/locales/lazy/auth_en.json +19 -2
  132. package/i18n/locales/lazy/auth_es.json +19 -2
  133. package/i18n/locales/lazy/auth_fr.json +19 -2
  134. package/i18n/locales/lazy/auth_it.json +19 -2
  135. package/i18n/locales/lazy/auth_ja.json +19 -2
  136. package/i18n/locales/lazy/auth_ko.json +19 -2
  137. package/i18n/locales/lazy/auth_nl.json +22 -2
  138. package/i18n/locales/lazy/auth_pl.json +19 -2
  139. package/i18n/locales/lazy/auth_pt.json +19 -2
  140. package/i18n/locales/lazy/auth_zh.json +19 -2
  141. package/i18n/locales/lazy/crud_ar.json +3 -1
  142. package/i18n/locales/lazy/crud_da.json +3 -1
  143. package/i18n/locales/lazy/crud_de.json +3 -1
  144. package/i18n/locales/lazy/crud_en.json +3 -1
  145. package/i18n/locales/lazy/crud_es.json +3 -1
  146. package/i18n/locales/lazy/crud_fr.json +3 -1
  147. package/i18n/locales/lazy/crud_it.json +3 -1
  148. package/i18n/locales/lazy/crud_ja.json +3 -1
  149. package/i18n/locales/lazy/crud_ko.json +3 -1
  150. package/i18n/locales/lazy/crud_nl.json +3 -1
  151. package/i18n/locales/lazy/crud_pl.json +3 -1
  152. package/i18n/locales/lazy/crud_pt.json +3 -1
  153. package/i18n/locales/lazy/crud_zh.json +3 -1
  154. package/index.d.ts +6927 -6153
  155. package/index.js +3 -3
  156. package/next/index.d.ts +250 -23
  157. package/next/index.js +556 -594
  158. package/next/runtime.js +3 -3
  159. package/package.json +4 -3
  160. package/server.d.ts +6950 -6153
  161. package/shared.js +2 -1
  162. package/symbol-index.json +1 -1
  163. package/vite/index.d.ts +85 -10
  164. package/vite/index.js +152 -152
  165. package/chunks/FlagBase-IQILJTOA.js +0 -1
  166. package/chunks/chunk-I6HT4XNS.js +0 -1
  167. package/chunks/chunk-PX544BGJ.js +0 -1
  168. package/chunks/flagAF-JHV34XMS.js +0 -1
  169. package/chunks/flagAL-UH6NKHXO.js +0 -1
  170. package/chunks/flagAM-7XYXA6G6.js +0 -1
  171. package/chunks/flagAR-LO3YLUZF.js +0 -1
  172. package/chunks/flagAT-6SWWBNVY.js +0 -1
  173. package/chunks/flagAU-FIJG7J4T.js +0 -1
  174. package/chunks/flagAZ-6AIO4DNL.js +0 -1
  175. package/chunks/flagBA-PIQRWY42.js +0 -1
  176. package/chunks/flagBD-7PXOE6GM.js +0 -1
  177. package/chunks/flagBE-2ZP6HCIM.js +0 -1
  178. package/chunks/flagBG-4XSHCVYH.js +0 -1
  179. package/chunks/flagBN-OF5XRA5N.js +0 -1
  180. package/chunks/flagBR-Y2266PSZ.js +0 -1
  181. package/chunks/flagBS-UV5PVKWJ.js +0 -1
  182. package/chunks/flagBY-MNAFXBA6.js +0 -1
  183. package/chunks/flagBZH-AOCZVEVI.js +0 -1
  184. package/chunks/flagCA-VR6MSBTS.js +0 -1
  185. package/chunks/flagCH-Q7MV5SPV.js +0 -1
  186. package/chunks/flagCO-C2YBOMO2.js +0 -1
  187. package/chunks/flagCS-5BC7NJX6.js +0 -1
  188. package/chunks/flagCY-PPAUTJGB.js +0 -1
  189. package/chunks/flagDA-LPI2JRTO.js +0 -1
  190. package/chunks/flagDE-MQDJAEWL.js +0 -1
  191. package/chunks/flagDZ-M6NVCF3D.js +0 -1
  192. package/chunks/flagEE-LY2JJ44X.js +0 -1
  193. package/chunks/flagEL-PP2HZIV7.js +0 -1
  194. package/chunks/flagEN-TGFHJYK7.js +0 -1
  195. package/chunks/flagES-C3H6SSSI.js +0 -1
  196. package/chunks/flagET-GEZLWRTF.js +0 -1
  197. package/chunks/flagEU-YJF5577W.js +0 -1
  198. package/chunks/flagFA-QCQKNEUZ.js +0 -1
  199. package/chunks/flagFI-LN5ICHNF.js +0 -1
  200. package/chunks/flagFR-5JPZSUVS.js +0 -1
  201. package/chunks/flagFR-COR-KPRNU2U6.js +0 -1
  202. package/chunks/flagGA-PUAQ7VY3.js +0 -1
  203. package/chunks/flagGB-SCT-RJGHRDJP.js +0 -1
  204. package/chunks/flagGB-XD2JB7EC.js +0 -1
  205. package/chunks/flagGD-ABOZBNKE.js +0 -1
  206. package/chunks/flagGE-N7C2KHVA.js +0 -1
  207. package/chunks/flagGL-AO2LC4XU.js +0 -1
  208. package/chunks/flagGU-RNGQ3TIY.js +0 -1
  209. package/chunks/flagHE-QUAWLF43.js +0 -1
  210. package/chunks/flagHI-JOOJFNKB.js +0 -1
  211. package/chunks/flagHR-2U7YEA7P.js +0 -1
  212. package/chunks/flagHU-6SPEV3OO.js +0 -1
  213. package/chunks/flagHY-L62LW6BP.js +0 -1
  214. package/chunks/flagID-LV75M4R3.js +0 -1
  215. package/chunks/flagIE-LBTC7LCK.js +0 -1
  216. package/chunks/flagIN-3UWOJ2S3.js +0 -1
  217. package/chunks/flagIR-44N33GFX.js +0 -1
  218. package/chunks/flagIS-VCPTXPLZ.js +0 -1
  219. package/chunks/flagIT-KB4NWTBO.js +0 -1
  220. package/chunks/flagJA-KLHM6VYH.js +0 -1
  221. package/chunks/flagKE-MZONPGAJ.js +0 -1
  222. package/chunks/flagKG-VF3T4E3E.js +0 -1
  223. package/chunks/flagKH-K5ZXX3DS.js +0 -1
  224. package/chunks/flagKK-ZZTJKPMR.js +0 -1
  225. package/chunks/flagKM-Y3XA6HXW.js +0 -1
  226. package/chunks/flagKN-OMVHGIUS.js +0 -1
  227. package/chunks/flagKO-UBLOXGRF.js +0 -1
  228. package/chunks/flagKZ-PYOALOB6.js +0 -1
  229. package/chunks/flagLA-4ONTEYIB.js +0 -1
  230. package/chunks/flagLB-FGOBUCL4.js +0 -1
  231. package/chunks/flagLK-BEVYO56P.js +0 -1
  232. package/chunks/flagLT-TYWQGIIQ.js +0 -1
  233. package/chunks/flagLV-S34SVWJJ.js +0 -1
  234. package/chunks/flagLY-AVR5B6N3.js +0 -1
  235. package/chunks/flagMA-KHTPMDTL.js +0 -1
  236. package/chunks/flagMD-TQMYMRQI.js +0 -1
  237. package/chunks/flagMK-C4CIIAUH.js +0 -1
  238. package/chunks/flagML-JEE5UGDD.js +0 -1
  239. package/chunks/flagMM-M72A7CHZ.js +0 -1
  240. package/chunks/flagMN-34CH7Q43.js +0 -1
  241. package/chunks/flagMR-KIJ2BPCC.js +0 -1
  242. package/chunks/flagMS-6COZCDLY.js +0 -1
  243. package/chunks/flagMT-HDBP7BED.js +0 -1
  244. package/chunks/flagMX-3XBPZTP5.js +0 -1
  245. package/chunks/flagMY-Y7C3QGRG.js +0 -1
  246. package/chunks/flagNE-LCWCYEQW.js +0 -1
  247. package/chunks/flagNL-3RFQSLLH.js +0 -1
  248. package/chunks/flagNO-RNDXHKBT.js +0 -1
  249. package/chunks/flagNP-IKVTRWFR.js +0 -1
  250. package/chunks/flagOC-JWCST6MI.js +0 -1
  251. package/chunks/flagPA-5SGZJRNZ.js +0 -1
  252. package/chunks/flagPK-KQ674PEZ.js +0 -1
  253. package/chunks/flagPL-V2ITOKFK.js +0 -1
  254. package/chunks/flagPS-WBOKI4MV.js +0 -1
  255. package/chunks/flagPT-PFIUVBWR.js +0 -1
  256. package/chunks/flagRM-MEV6U4AJ.js +0 -1
  257. package/chunks/flagRO-JPMXEGLK.js +0 -1
  258. package/chunks/flagRU-3BBKEK34.js +0 -1
  259. package/chunks/flagSA-N7OI2M6Y.js +0 -1
  260. package/chunks/flagSI-UTODFLQZ.js +0 -1
  261. package/chunks/flagSK-EV5JZ2DI.js +0 -1
  262. package/chunks/flagSL-Y4LHIV2J.js +0 -1
  263. package/chunks/flagSR-MTRWQPJ5.js +0 -1
  264. package/chunks/flagSV-LYVDSSJ4.js +0 -1
  265. package/chunks/flagSW-GJO5P4HE.js +0 -1
  266. package/chunks/flagTA-CDT3KYEB.js +0 -1
  267. package/chunks/flagTE-5EXMXH6E.js +0 -1
  268. package/chunks/flagTH-ODJA4CWB.js +0 -1
  269. package/chunks/flagTJ-CE5SV6V4.js +0 -1
  270. package/chunks/flagTL-TRVUF3XO.js +0 -1
  271. package/chunks/flagTN-G6ERYSZ3.js +0 -1
  272. package/chunks/flagTR-33VFGL2S.js +0 -1
  273. package/chunks/flagUA-HESNDKQJ.js +0 -1
  274. package/chunks/flagUR-ECIZZCDG.js +0 -1
  275. package/chunks/flagUS-M7R4WRRU.js +0 -1
  276. package/chunks/flagUZ-YW54WCES.js +0 -1
  277. package/chunks/flagVI-K3DF2THA.js +0 -1
  278. package/chunks/flagZA-5UIOKDJH.js +0 -1
  279. package/chunks/flagZH-5IE3RZVQ.js +0 -1
package/shared.js CHANGED
@@ -1 +1,2 @@
1
- var Hn=Object.defineProperty;var Gn=(e,t,n)=>t in e?Hn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var T=(e,t,n)=>Gn(e,typeof t!="symbol"?t+"":t,n);var F={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},ye={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},ki={[F.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[F.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[F.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},Ai={maxTokens:4096,temperature:.7,stream:!0},Ci={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_API_KEY:"invalid_api_key",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",PROVIDER_ERROR:"provider_error",TOKEN_LIMIT_EXCEEDED:"token_limit_exceeded",STREAM_INTERRUPTED:"stream_interrupted"},Ii={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},wi=4,Oi={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}};import*as d from"valibot";var pt=d.object({role:d.picklist([ye.USER,ye.ASSISTANT,ye.SYSTEM]),content:d.pipe(d.string(),d.minLength(1)),id:d.optional(d.string()),createdAt:d.optional(d.string())}),$e=d.lazy(()=>d.object({type:d.picklist(["string","number","boolean","array","object"]),description:d.optional(d.string()),enum:d.optional(d.array(d.string())),items:d.optional($e),properties:d.optional(d.record(d.string(),$e)),required:d.optional(d.array(d.string()))})),Yn=d.object({description:d.pipe(d.string(),d.minLength(1)),parameters:d.object({type:d.literal("object"),properties:d.record(d.string(),$e),required:d.optional(d.array(d.string()))})}),zn=d.object({id:d.string(),name:d.string(),args:d.record(d.string(),d.unknown())}),Xn=d.object({messages:d.pipe(d.array(pt),d.minLength(1)),provider:d.optional(d.picklist([F.ANTHROPIC,F.OPENAI,F.GOOGLE])),model:d.optional(d.string()),maxTokens:d.optional(d.pipe(d.number(),d.integer(),d.minValue(1))),temperature:d.optional(d.pipe(d.number(),d.minValue(0),d.maxValue(2))),systemPrompt:d.optional(d.string()),stream:d.optional(d.boolean()),tools:d.optional(d.record(d.string(),Yn))}),Qn=d.object({promptTokens:d.number(),completionTokens:d.number(),totalTokens:d.number()}),Zn=d.object({message:pt,usage:d.optional(Qn),finishReason:d.optional(d.string()),toolCalls:d.optional(d.array(zn))}),Fi=d.object({provider:d.picklist([F.ANTHROPIC,F.OPENAI,F.GOOGLE]),model:d.optional(d.string()),maxTokens:d.optional(d.pipe(d.number(),d.integer(),d.minValue(1))),temperature:d.optional(d.pipe(d.number(),d.minValue(0),d.maxValue(2))),systemPrompt:d.optional(d.string())});function Ni(e){return d.safeParse(Xn,e)}function _i(e){return d.safeParse(Zn,e)}var he={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function Jn(e){Object.assign(he,e)}var ve={tier:"free",status:"active",subscriptionEnd:null,updatedAt:"1970-01-01T00:00:00.000Z",isDefault:!0,subscriptionId:null,customerId:null,cancelAtPeriodEnd:!1};function er(e){return{...ve,updatedAt:new Date().toISOString()}}var je={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},w={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function $i(e){Object.assign(w,e)}var tr={FREE:"free",PRO:"pro",PREMIUM:"premium"};function ji(e){Object.assign(tr,e)}var qe={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function qi(e){Object.assign(qe,e)}var We={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 Wi(e){Object.assign(We,e)}import*as l from"valibot";function se(e){let[t,...n]=Object.values(e);if(t===void 0)throw new Error("picklistOptions: constant map has no values");return[t,...n]}var mt=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(se(w))),customClaims:l.optional(l.record(l.string(),l.any()))}),_=l.object({tier:l.string(),status:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),updatedAt:l.pipe(l.string(),l.isoTimestamp()),isDefault:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.optional(l.nullable(l.string())),customerId:l.optional(l.nullable(l.string())),cancelAtPeriodEnd:l.optional(l.boolean())}),ft=l.object({..._.entries,userId:l.string(),isActive:l.optional(l.boolean())}),gt=l.object({role:l.optional(l.picklist(se(w))),subscription:l.optional(_),features:l.optional(l.array(l.picklist(se(qe)))),permissions:l.optional(l.array(l.picklist(se(We)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function zi(e){return l.safeParse(mt,e)}function Xi(e){return l.safeParse(ft,e)}function Qi(e){return l.safeParse(gt,e)}function nr(e){return l.safeParse(_,e)}function Zi(){let e={authUser:l.safeParse(mt,{}),userSubscription:l.safeParse(ft,{}),customClaims:l.safeParse(gt,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}var es={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},ts={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function ns(e){return{userId:e,role:"user",preferences:{},metadata:{}}}var be={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function us(e){Object.assign(be,e)}var cs={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};import*as o from"valibot";var yt=100,rr=o.object({productId:o.pipe(o.string(),o.minLength(1),o.maxLength(200)),quantity:o.pipe(o.number(),o.integer(),o.minValue(1),o.maxValue(1e4))}),bt=o.pipe(o.object({billingConfigKey:o.optional(o.pipe(o.string(),o.minLength(1))),lineItems:o.optional(o.pipe(o.array(rr),o.minLength(1,"At least one line item is required"),o.maxLength(yt,`At most ${yt} line items`))),successUrl:o.pipe(o.string(),o.url()),cancelUrl:o.pipe(o.string(),o.url()),customerEmail:o.optional(o.pipe(o.string(),o.email())),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean()),userId:o.optional(o.string()),productId:o.optional(o.string()),priceId:o.optional(o.string()),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code"))),userEmail:o.optional(o.pipe(o.string(),o.email())),mode:o.optional(o.picklist([be.PAYMENT,be.SUBSCRIPTION]))}),o.rawTransform(({dataset:e,addIssue:t,NEVER:n})=>{let r=e.value,i=r.billingConfigKey||r.metadata?.billingConfigKey;return i?{...r,billingConfigKey:i,lineItems:r.lineItems??[{productId:i,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),Et=o.object({sessionId:o.string(),sessionUrl:o.nullable(o.pipe(o.string(),o.url()))}),ae=o.pipe(o.string(),o.minLength(1),o.regex(/\S/)),or=o.object({sessionId:ae,billingConfigKey:ae}),ir=o.object({sessionId:ae,orderId:ae,billingConfigKey:ae,sessionStatus:o.picklist(["open","complete","expired"]),paymentStatus:o.picklist(["paid","unpaid","no_payment_required"])});function vs(e){return o.safeParse(or,e)}function bs(e){return o.safeParse(ir,e)}var St=o.object({..._.entries,userId:o.string(),subscriptionId:o.nullable(o.string()),customerId:o.string(),cancelAtPeriodEnd:o.boolean()}),xt=o.object({id:o.string(),type:o.string(),data:o.object({object:o.any()}),created:o.pipe(o.string(),o.isoTimestamp())}),Tt=o.looseObject({userId:o.optional(o.string()),firebaseUid:o.optional(o.string()),productType:o.optional(o.string())});function Es(e){return o.safeParse(bt,e)}function Ss(e){return o.safeParse(Et,e)}function xs(e){return o.safeParse(St,e)}function Ts(e){return o.safeParse(xt,e)}function Rs(e){return o.safeParse(Tt,e)}var sr=o.object({type:o.literal("StripePayment"),name:o.pipe(o.string(),o.minLength(1,"Product name is required")),description:o.optional(o.string()),price:o.string(),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:o.optional(o.pipe(o.string(),o.minLength(1,"Stripe price ID is required"))),tier:o.pipe(o.string(),o.minLength(1,"Tier is required")),duration:o.pipe(o.string(),o.minLength(1,"Duration is required")),allowPromotionCodes:o.optional(o.boolean()),metadata:o.optional(o.record(o.string(),o.string()))}),ar=o.object({type:o.literal("StripeSubscription"),name:o.pipe(o.string(),o.minLength(1,"Product name is required")),description:o.optional(o.string()),price:o.string(),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:o.pipe(o.string(),o.minLength(1,"Stripe price ID is required")),tier:o.pipe(o.string(),o.minLength(1,"Tier is required")),duration:o.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:o.optional(o.boolean()),metadata:o.optional(o.record(o.string(),o.string()))}),lr=o.variant("type",[sr,ar]),ks=o.record(o.string(),lr),ur=o.record(o.string(),o.object({name:o.string(),price:o.string(),currency:o.string(),description:o.optional(o.string()),features:o.optional(o.array(o.string())),priceId:o.optional(o.string()),allowPromotionCodes:o.optional(o.boolean())})),ht={name:o.string(),price:o.number(),currency:o.string(),priceId:o.optional(o.string()),tier:o.string(),duration:o.string(),description:o.optional(o.string()),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean())},cr=o.variant("mode",[o.object({mode:o.literal("manual"),taxRateIds:o.pipe(o.array(o.pipe(o.string(),o.minLength(1))),o.minLength(1))}),o.object({mode:o.literal("automatic")})]),vt=5,dr=o.object({allowedCountries:o.pipe(o.array(o.pipe(o.string(),o.regex(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),o.minLength(1)),shippingRateIds:o.optional(o.pipe(o.array(o.pipe(o.string(),o.minLength(1))),o.maxLength(vt,`shippingRateIds: at most ${vt} (Stripe limit)`)))}),pr=o.object({type:o.literal("StripeOrder"),name:o.string(),currency:o.pipe(o.string(),o.length(3)),description:o.optional(o.string()),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean()),tax:cr,taxIdCollection:o.picklist(["disabled","optional","required"]),billingAddressCollection:o.picklist(["auto","required"]),shipping:o.optional(dr),customerCreation:o.picklist(["always","if_required"]),invoiceCreation:o.boolean(),paymentMethodConfiguration:o.optional(o.pipe(o.string(),o.minLength(1)))}),mr=o.record(o.string(),o.variant("type",[o.object({type:o.literal("StripePayment"),...ht}),o.object({type:o.literal("StripeSubscription"),...ht}),pr]));function As(e){return o.parse(ur,e)}function Cs(e){return o.parse(mr,e)}function Is(){let e={createCheckoutSessionRequest:o.safeParse(bt,{}),createCheckoutSessionResponse:o.safeParse(Et,{}),subscriptionData:o.safeParse(St,{}),subscriptionClaims:o.safeParse(_,{}),webhookEvent:o.safeParse(xt,{}),checkoutSessionMetadata:o.safeParse(Tt,{})};return{success:Object.values(e).every(t=>t.success),results:e}}var _s={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},Us={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},Ms={CLIENT:"client",SERVER:"server",BUILD:"build"},Ls={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},Bs={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},Vs={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},$s={USER:"user",GLOBAL:"global",SESSION:"session"},js={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},qs={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},Ws={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var Hs={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},V={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"},Ke={create:"admin",read:"guest",update:"admin",delete:"admin"},U={draft:{read:"admin",saveIncomplete:!0,holdIncomplete:!0,isDefault:!1,isRemoved:!1},available:{read:"guest",saveIncomplete:!1,holdIncomplete:!1,isDefault:!0,isRemoved:!1},deleted:{read:"admin",saveIncomplete:!1,holdIncomplete:!0,isDefault:!1,isRemoved:!0}},Rt=U.available,Q=Object.keys(U);function kt(e){let t=Q.filter(n=>U[n][e]);if(t.length!==1)throw new Error(`[dndev] STATUS_MATRIX: exactly one status must have ${e}`);return t[0]}var Ee=kt("isDefault"),He=kt("isRemoved"),fr=Q.filter(e=>U[e].read!=="guest"),le=["id","createdAt","updatedAt","createdById","updatedById"],q={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},Gs={ASC:"asc",DESC:"desc"},Ys={LIST:"list",LIST_CARD:"listCard"},At=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var Qs={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},Zs={EQ:q.EQ,NEQ:q.NEQ,LT:q.LT,LTE:q.LTE,GT:q.GT,GTE:q.GTE};var Ct=class extends Error{constructor(n,r,i){super(n,{cause:i});T(this,"outcome");this.name="AtomicBulkError",this.outcome=r}},It=class extends Error{constructor(n,r){super(`BulkCollisionError: ${n.length} id(s) appear in both "${r.replace("-",'" and "')}" \u2014 ${n.join(", ")}`);T(this,"collidingIds");T(this,"where");this.name="BulkCollisionError",this.collidingIds=n,this.where=r}},wt=class extends Error{constructor(n){super(`[dndev] bulkAcross: circular dependency: ${n.join(" \u2192 ")}`);T(this,"cycle");this.name="BulkAcrossCycleError",this.cycle=n}},Ot=class extends Error{constructor(n){super(`BulkNotImplementedError: adapter "${n}" has not implemented bulk() yet`);T(this,"adapterName");this.name="BulkNotImplementedError",this.adapterName=n}};import*as f from"valibot";var sa=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),data:f.record(f.string(),f.unknown()),idempotencyKey:f.optional(f.string())}),aa=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),id:f.pipe(f.string(),f.minLength(1,"Entity ID is required"))}),la=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),id:f.pipe(f.string(),f.minLength(1,"Entity ID is required")),data:f.record(f.string(),f.unknown()),merge:f.optional(f.boolean(),!1)}),ua=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),id:f.pipe(f.string(),f.minLength(1,"Entity ID is required"))}),ca=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),limit:f.optional(f.pipe(f.number(),f.minValue(1),f.maxValue(1e3)),1e3),offset:f.optional(f.pipe(f.number(),f.minValue(0)),0),orderBy:f.optional(f.string()),orderDirection:f.optional(f.picklist(["asc","desc"]),"desc"),where:f.optional(f.array(f.object({field:f.string(),operator:f.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:f.unknown()})))});var xa={RESEND:"resend"},Ta={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_REQUEST:"invalid_request",PROVIDER_ERROR:"provider_error",TEMPLATE_NOT_FOUND:"template_not_found",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",MISSING_API_KEY:"missing_api_key"};import*as E from"valibot";var gr=E.object({templateId:E.pipe(E.string(),E.minLength(1)),to:E.pipe(E.string(),E.email()),data:E.record(E.string(),E.unknown()),locale:E.optional(E.pipe(E.string(),E.minLength(2),E.maxLength(5)),"fr"),from:E.optional(E.string()),replyTo:E.optional(E.string())}),yr=E.object({success:E.boolean(),messageId:E.optional(E.string()),error:E.optional(E.string())});function ka(e){return E.safeParse(gr,e)}function Aa(e){return E.safeParse(yr,e)}var ue={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"},Da={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},Se={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Ge={[ue.PERMISSION_DENIED]:{type:Se.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[ue.NOT_FOUND]:{type:Se.NOT_FOUND,message:"The requested resource was not found"},[ue.ALREADY_EXISTS]:{type:Se.ALREADY_EXISTS,message:"The resource already exists"},[ue.INVALID_ARGUMENT]:{type:Se.VALIDATION_ERROR,message:"Invalid argument provided"}},Pt=class extends Error{constructor(n,r,i){super(r);T(this,"type");T(this,"originalError");this.name="EntityHookError",this.type=n,this.originalError=i}},Fa={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"};function hr(e){return"captureStackTrace"in e&&typeof e.captureStackTrace=="function"}var S=class e extends Error{constructor(n,r=ue.INTERNAL,i){super(n);T(this,"code");T(this,"details");T(this,"source");T(this,"originalError");T(this,"context");T(this,"displayable");T(this,"userMessageProvided");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,hr(Error)&&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 La={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var Va={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var ja={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var Wa={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var Ha={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var Ye={mobile:0,tablet:768,laptop:1024,desktop:1440},vr={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function br(e){return e>=Ye.desktop?"desktop":e>=Ye.laptop?"laptop":e>=Ye.tablet?"tablet":"mobile"}function il(e,t){let n=vr[t];return e>=n.min&&e<=n.max}function sl(e,t){let n=br(e);return{current:n,width:e,height:t,isMobile:n==="mobile",isTablet:n==="tablet",isLaptop:n==="laptop",isDesktop:n==="desktop",isMobileOrTablet:n==="mobile"||n==="tablet",isLaptopOrDesktop:n==="laptop"||n==="desktop"}}var Er="landing",Sr={FIXED:"fixed",SCROLL:"scroll"},xr={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var Dt=["pull","push","admin","maintain","triage"];import"valibot";import*as m from"valibot";var ze=m.object({owner:m.pipe(m.string(),m.minLength(1,"Repository owner is required")),repo:m.pipe(m.string(),m.minLength(1,"Repository name is required"))}),Tr=m.picklist([...Dt]),bl=m.object({userId:m.pipe(m.string(),m.minLength(1,"User ID is required")),githubUsername:m.pipe(m.string(),m.minLength(1,"GitHub username is required")),repoConfig:ze,permission:m.optional(Tr,"push"),customClaims:m.optional(m.record(m.string(),m.any()))}),El=m.object({userId:m.pipe(m.string(),m.minLength(1,"User ID is required")),githubUsername:m.pipe(m.string(),m.minLength(1,"GitHub username is required")),repoConfig:ze}),Sl=m.object({userId:m.pipe(m.string(),m.minLength(1,"User ID is required")),githubUsername:m.pipe(m.string(),m.minLength(1,"GitHub username is required")),repoConfig:ze}),xl=m.object({provider:m.string(),purpose:m.picklist(["authentication","api-access"]),code:m.pipe(m.string(),m.minLength(1,"Authorization code is required")),redirectUri:m.pipe(m.string(),m.url("Valid redirect URI is required")),codeVerifier:m.optional(m.string()),state:m.optional(m.string()),instance:m.optional(m.pipe(m.string(),m.url()))}),Tl=m.object({provider:m.string(),refreshToken:m.pipe(m.string(),m.minLength(1,"Refresh token is required")),redirectUri:m.pipe(m.string(),m.url("Valid redirect URI is required"))}),Rl=m.object({provider:m.string()}),kl=m.object({userId:m.pipe(m.string(),m.minLength(1,"User ID is required"))});var Pl={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as y from"valibot";var Ft=y.object({name:y.string(),color:y.string(),icon:y.string(),customParameters:y.optional(y.record(y.string(),y.string())),button:y.object({backgroundColor:y.string(),textColor:y.string(),borderColor:y.string(),hoverBackgroundColor:y.string(),focusOutlineColor:y.string(),fontWeight:y.optional(y.string(),"500"),textKey:y.optional(y.string())})}),Rr=y.object({...Ft.entries,type:y.picklist(["auth","both"]),scopes:y.optional(y.array(y.string())),firebaseProviderId:y.optional(y.string())}),xe=y.union([y.literal(""),y.pipe(y.string(),y.url())]),kr=y.object({authUrl:xe,tokenUrl:xe,profileUrl:xe,revokeUrl:y.optional(xe)}),Ar=y.object({authentication:y.optional(y.array(y.string())),"api-access":y.array(y.string())}),Cr=y.optional(y.object({pkce:y.optional(y.boolean(),!1),codeChallengeMethod:y.optional(y.picklist(["S256","plain"]),"S256")})),Ir=y.object({...Ft.entries,type:y.picklist(["oauth","both"]),scopes:Ar,endpoints:kr,capabilities:Cr}),Nt={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},_t={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},wr=y.record(y.string(),Rr),Or=y.record(y.string(),Ir);function Fl(){return y.safeParse(wr,Nt)}function Nl(){return y.safeParse(Or,_t)}function _l(e){return e in Nt}function Ul(e){return e in _t}var Ut={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Hl={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Gl={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Ut.ANALYTICS},marketing:{requiresConsent:Ut.MARKETING}};function Tu(e,t){return Object.assign(e,{metadata:t})}import*as ne from"valibot";import*as u from"valibot";function Mt(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"}import*as Bt from"valibot";function M(e){return(t,n)=>{if(t instanceof S)return t;if(typeof t!="object"||t===null){let c=typeof t=="string"?t:e.defaultErrorMessage;return new S(n||c,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let r;e.extractErrorCode?r=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(r=t.code);let i=e.defaultErrorCode;r&&e.errorCodeMapping&&r in e.errorCodeMapping&&(i=e.errorCodeMapping[r]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),r&&e.friendlyMessageMapping&&r in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[r]),s||(s=e.defaultErrorMessage);let a;return e.processMetadata?a=e.processMetadata(t):(a={originalError:t},r&&(a.originalCode=r)),"originalError"in a||(a.originalError=t),new S(n||s,i,{details:a,source:e.errorSource})}}var Te={"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"};var Z={"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."},Pr={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"},Xe={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"};function Dr(e){return e in Xe}var $={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",...Te},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",...Te},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(Pr).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode: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()},processMetadata:e=>{let t={originalError:e};if(typeof e!="object"||e===null)return t;if("response"in e&&e.response){let n=e.response;"status"in n&&(t.statusCode=n.status),"data"in n&&(t.responseData=n.data)}else"status"in e&&(t.statusCode=e.status);return t}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:Te,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:Z.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:Z["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:Z.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},Fr=e=>e instanceof Bt.ValiError?new S(Z["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):M($.validation)(e),Nr=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&Dr(e.type)){let t=Xe[e.type]||"unknown";return new S(e.message||Z[t],t,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&Ge[e.code]){let t=Ge[e.code];if(t){let n=Xe[t.type]||"unknown";return new S(t.message||Z[n],n,{details:{originalCode:e.code,originalError:e},source:"entity"})}}return M($.entity)(e)},Lt={auth:M($.auth),oauth:M($.oauth),api:M($.api),firebase:M($.firebase),ui:M($.ui),validation:Fr,entity:Nr,unknown:M($.unknown)};function J(e,t,n){return e instanceof S?e:(Lt[t]||Lt.unknown)(e,n)}function Vt(e,t,n={}){let r=globalThis.Sentry;r&&r.withScope(i=>{i.setTag("errorSource",t),i.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,a])=>{if(typeof a!="function"&&s!=="originalError")try{i.setExtra(s,a)}catch{i.setExtra(s,`[${typeof a}]`)}}),Object.entries(n).forEach(([s,a])=>{if(typeof a!="function")try{i.setExtra(`context.${s}`,a)}catch{i.setExtra(`context.${s}`,`[${typeof a}]`)}}),(e.details?.userId||n.userId)&&i.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),r.captureException(e)})}function _r(){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?(process.env.NODE_ENV||"development").toLowerCase()!=="production":!1}function k(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:r,context:i={},log:s=!0,reportToSentry:a=!0,showNotification:c=!1,severity:p="error"}=n,h=Mt(e),v=e instanceof S?e:J(e,h,r);if(r&&!v.userMessageProvided&&(v.message.includes("Error")||v.message.includes("Failed")||v.message.length<10?v=new S(r,v.code,{details:{...v.details,originalMessage:v.message},source:h,userMessageProvided:!0}):v=new S(v.message,v.code,{details:{...v.details,userMessage:r},source:h,userMessageProvided:!0})),s){let x=_r()||typeof window<"u"&&window.__DNDEV_DEBUG,B={code:v.code,message:v.message,source:h};switch(p){case"warning":break;case"info":break;case"success":break;default:}}return a&&Vt(v,h,i),v}function Bu(e,t){return async(...n)=>{try{return await e(...n)}catch(r){throw k(r,t)}}}function Vu(e,t="info",n){let r=Date.now().toString();return r}function Xu(e,t,n,r,i){if(e instanceof S)return e;let{code:s}=J(e,"api");return new S("Request failed.",s,{source:"api",details:{context:`${t}.${n}(${r}${i?`, ${i}`:""})`,originalMessage:Qe(e),originalError:e}})}function Qu(e,t,n,r){let i=`${t}.${n}(${r})`;return J(e,"api",`${i}: ${Qe(e)}`)}function Zu(e,t,n,r){let i=r?` ${JSON.stringify(r)}`:"",s=`${t}.${n}(${i})`,a=J(e,"auth",`${s}: ${Qe(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&a.code==="unknown"&&e.code!=="unknown"?new S(a.message,a.code,{details:{...a.details,originalCode:e.code},source:a.source}):a}function Qe(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}import*as ce from"valibot";function tc(e,t,n){try{return ce.parse(e,t)}catch(r){throw r instanceof ce.ValiError?new S(`Validation failed in ${n}: ${r.message}`,"validation-failed",{details:{issues:r.issues,input:t},source:"validation"}):new S(`Unexpected validation error in ${n}: ${Ur(r)}`,"validation-failed",{originalError:r instanceof Error?r:new Error(String(r)),source:"validation"})}}function nc(e,t){try{return ce.parse(e,t)}catch{return null}}function rc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Ur(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function lc(e,t,n,r={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:a}=r;return Array.from({length:n},(c,p)=>{let h=`${t}.${p}`;return e(h)}).filter((c,p)=>{let h=`${t}.${p}`;return!(c===h||s&&c.trim()===""||c.length<i||a&&!a(c,p))})}function uc(e,t,n,r){return Array.from({length:n},(i,s)=>{let a=`${t}.${s}.${String(r[0])}`;if(e(a)===a)return null;let p={};for(let h of r){let v=`${t}.${s}.${String(h)}`;p[h]=e(v)}return p}).filter(i=>i!==null)}function cc(e,t,n,r,i={}){let{minLength:s=0,excludeEmpty:a=!0,customFilter:c}=i;return Array.from({length:r-n},(p,h)=>{let v=n+h,x=`${t}.${v}`;return e(x)}).filter((p,h)=>{let v=n+h,x=`${t}.${v}`;return!(p===x||a&&p.trim()===""||p.length<s||c&&!c(p,v))})}function dc(e,t,n,r={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:a}=r;return Array.from({length:n},(c,p)=>{let h=`${t}.${p}`;return{item:e(h),originalIndex:p}}).filter(({item:c,originalIndex:p})=>{let h=`${t}.${p}`;return!(c===h||s&&c.trim()===""||c.length<i||a&&!a(c,p))})}function mc(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}var $t={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function Mr(e){return $t[e]?.locale??"en-US"}function gc(e){return!e||typeof e!="string"?e??"":$t[e]?.symbol??e}function Re(e,t,n={}){if(e==null||isNaN(e))return"";let r=Mr(t);return new Intl.NumberFormat(r,{style:"currency",currency:t,minimumFractionDigits:0,maximumFractionDigits:2,currencyDisplay:"symbol",...n}).format(e)}function jt(e){let t=e.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!t||t.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${e}`);let n=t[1],r=t[2],i=t[3],s=t[4],a=t[5],c=new Date(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(s,10),parseInt(a,10));if(isNaN(c.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return c.toISOString()}function hc(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let n=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0"),s=String(t.getUTCHours()).padStart(2,"0"),a=String(t.getUTCMinutes()).padStart(2,"0");return`${n}${r}${i}:${s}${a}`}function qt(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function vc(e){if(!e)return new Date().toISOString();if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return e.toISOString()}if(typeof e=="string"){if(qt(e))return jt(e);let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string: ${e}`);return t.toISOString()}if(typeof e=="number"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp: ${e}`);return t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();throw new Error(`Unsupported date type: ${typeof e}`)}function bc(){return new Date().toISOString()}function Ec(e){return e.toISOString()}function Sc(e){return new Date(e).toISOString()}function xc(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let n=new Date(t.getFullYear(),0,1),r=Math.floor((t.getTime()-n.getTime())/(1440*60*1e3));return`Week ${Math.ceil((r+n.getDay()+1)/7)}, ${t.getFullYear()}`}var O={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function Tc(e,t="en",n={}){if(!e)return"";let{style:r="long",numeric:i="auto",fallbackThreshold:s=O.WEEK}=n,a;if(e instanceof Date)a=e;else if(typeof e=="string")a=new Date(e);else if(typeof e=="number")a=new Date(e);else if(typeof e=="object"&&"toDate"in e)a=e.toDate();else return"";if(isNaN(a.getTime()))return"";let c=new Date,p=a.getTime()-c.getTime(),h=Math.round(p/1e3),v=Math.abs(h);if(v>s)return Br(a.toISOString(),t);let x=new Intl.RelativeTimeFormat(t,{style:r,numeric:i});return v<O.MINUTE?x.format(h,"second"):v<O.HOUR?x.format(Math.round(h/O.MINUTE),"minute"):v<O.DAY?x.format(Math.round(h/O.HOUR),"hour"):v<O.WEEK?x.format(Math.round(h/O.DAY),"day"):v<O.MONTH?x.format(Math.round(h/O.WEEK),"week"):v<O.YEAR?x.format(Math.round(h/O.MONTH),"month"):x.format(Math.round(h/O.YEAR),"year")}function Lr(e){switch(e){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function Br(e,t="en",n="long"){if(!e)return"";let r;if(e instanceof Date)r=e;else if(typeof e=="string")r=new Date(e);else if(typeof e=="number")r=new Date(e);else if(typeof e=="object"&&"toDate"in e)r=e.toDate();else return"";if(isNaN(r.getTime()))return"";let i=typeof n=="string"?Lr(n):n;return new Intl.DateTimeFormat(t,i).format(r)}function Wt(e){if(e!=null){if(e instanceof Date)return isNaN(e.getTime())?void 0:e.toISOString();if(typeof e=="string"){let t=e.trim();if(!t)return;if(qt(t))try{return jt(t)}catch{return}let n=new Date(t);return isNaN(n.getTime())?void 0:n.toISOString()}if(typeof e=="number"){if(!Number.isFinite(e))return;let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")try{let t=e.toDate();return isNaN(t.getTime())?void 0:t.toISOString()}catch{return}if(typeof e=="object"&&e!==null&&"seconds"in e&&typeof e.seconds=="number"){let t=e,n=t.seconds*1e3+(t.nanoseconds||0)/1e6,r=new Date(n);return isNaN(r.getTime())?void 0:r.toISOString()}}}function Rc(e){let t=Wt(e);if(!t)return;let n=new Date(t);return n.setUTCHours(12,0,0,0),n.toISOString()}function kc(e){let t=Wt(e);return t&&t.split("T")[0]||""}function Yt(e){return e==null||e===""}function Ze(e,t){if(!e.includes(":"))return t(e);let[n,r=e]=e.split(":");if(r.startsWith("status.")){let i=t(r);if(i!==r&&i!==`${n}:${r}`)return i}return t(r,{ns:n})}function et(e){return e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function zt(e){let t=e.validation?.options;return Array.isArray(t)?t:void 0}function ke(e,t,n){let r=zt(t)?.find(i=>i.value===e)?.label;return r?Ze(r,n):String(e)}function Je(e){return e instanceof Date?e:new Date(e)}var Kt=(e,t,n,{locale:r})=>Je(e).toLocaleString(r),N=e=>String(e),Ht=e=>e?"Yes":"No",Gt=(e,t,n,{locale:r})=>typeof e=="number"?e.toLocaleString(r):String(e),Vr={timestamp:Kt,"datetime-local":Kt,date:(e,t,n,{locale:r})=>Je(e).toLocaleDateString(r),time:(e,t,n,{locale:r})=>Je(e).toLocaleTimeString(r),week:N,month:N,boolean:Ht,checkbox:Ht,switch:(e,t,n)=>{let r=t.options?.fieldSpecific;if(r){let i=r.uncheckedValue??!1,s=r.checkedValue??!0;if(e===s&&r.checkedLabel)return Ze(r.checkedLabel,n);if(e===i&&r.uncheckedLabel)return Ze(r.uncheckedLabel,n)}return e?"Yes":"No"},year:N,number:Gt,range:Gt,currency:(e,t)=>{if(Number.isNaN(Number(e)))return"";let n=t.options?.fieldSpecific;return Re(Number(e),n?.currency||"EUR")},price:(e,t,n)=>{let r=typeof e=="number"?{amount:e,currency:"EUR",vatIncluded:!0,discountPercent:0}:e;if(!r||typeof r!="object")return"";let i=r.amount;if(Yt(i)||Number.isNaN(Number(i)))return"";let s=r.currency||"EUR",a=r.discountPercent??0,c=r.vatIncluded??!0?` ${n("crud:price.vatIncluded",{defaultValue:"VAT Incl."})}`:"";if(a>0){let p=Number(i)*(1-a/100),h=` ${n("crud:price.discountPercent",{percent:Math.round(a),defaultValue:"-{{percent}}%"})}`;return`${Re(p,s)}${c}${h}`}return`${Re(Number(i),s)}${c}`},duration:(e,t,n)=>{let r=typeof e=="number"?e:parseInt(String(e),10);if(Number.isNaN(r))return"";if(r===0)return n("crud:duration.zero",{defaultValue:"\u2014"});if(r<60)return n("crud:duration.minutes",{count:r,defaultValue:`${r} min`});let i=Math.floor(r/60),s=r%60;return n("crud:duration.hoursMinutes",{hours:i,minutes:s,defaultValue:s===0?`${i}h`:`${i}h ${s}min`})},gdprConsent:(e,t,n,{locale:r})=>{if(!e||typeof e!="object")return"";let i=e;if(i.gdprConsent!==!0)return n("crud:gdprConsent.display.no",{defaultValue:"Not consented"});let s=[n("crud:gdprConsent.display.yes",{defaultValue:"Consented"})];return i.gdprConsentDate&&s.push(new Date(i.gdprConsentDate).toLocaleDateString(r)),i.gdprConsentVersion&&s.push(`v${i.gdprConsentVersion}`),s.join(" \xB7 ")},select:ke,radio:ke,combobox:ke,multiselect:(e,t,n)=>Array.isArray(e)&&zt(t)?e.map(r=>ke(r,t,n)).join(", "):String(e),reference:e=>{if(e&&typeof e=="object"){let t=e;return String(t.displayName||t.name||t.id||e)}return String(e)},geopoint:e=>{if(e&&typeof e=="object"&&"lat"in e&&"lng"in e){let{lat:t,lng:n}=e;return`${t.toFixed(6)}, ${n.toFixed(6)}`}return""},address:e=>e&&typeof e=="object"&&"formatted_address"in e?String(e.formatted_address):String(e),array:e=>Array.isArray(e)?e.join(", "):"","field-array":(e,t)=>{if(!Array.isArray(e))return"";let n=t.options?.fieldSpecific?.fields;return e.map(r=>{if(typeof r!="object"||r==null)return"";let i=r;return(n?n.map(a=>a.name):Object.keys(i)).map(a=>i[a]).filter(a=>a!=null&&a!=="").map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" \xB7 ")}).filter(Boolean).join(", ")},password:()=>"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",text:N,textarea:N,email:N,tel:N,url:N,color:N,iban:N,richtext:e=>et(String(e))};function Xt(e,t,n,r={}){let i=t.options?.displayValue;if(i&&r.item)return i(e,r.item,n);if(Yt(e))return null;let s=r.formatter??Vr[t.type],a=s?s(e,t,n,{locale:r.locale}):typeof e=="object"?null:String(e);if(a===null||a==="")return null;let c=t.options?.displayKey;if(!c)return a;let p=(Array.isArray(c)?c:[c]).map(h=>h.replace("{{value}}",a));return n(p,{value:a})}var $r=160,Qt="EUR",jr=new Set(["textarea","richtext"]),Jt=new Set(["image","images"]),qr=new Set(["price","currency"]),Wr=" \xB7 ",Kr={available:"InStock"};function W(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function Hr(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(" ");return`${(r>t/2?n.slice(0,r):n).trimEnd()}\u2026`}function Zt(e){return(Array.isArray(e)?e:[e]).map(n=>{if(typeof n=="string")return W(n);if(n&&typeof n=="object"&&"fullUrl"in n)return W(n.fullUrl)}).filter(n=>n!==void 0)}function en(e){let t=e.listCardFields,n=t?Array.isArray(t)?t:[...t.title??[],...t.subtitle??[],...t.content??[],...t.footer??[]]:[];return[...new Set([...n,...Object.keys(e.fields)])]}function Ae(e,t,n,r){return n.flatMap(i=>{let s=e.fields[i];if(!s||Jt.has(s.type))return[];let a=Xt(t[i],s,r.t,{item:t,locale:r.locale});return a?[a]:[]})}function Gr(e,t,n){let r=e.seo?.title;if(r)return W(r(t,n.t));let i=e.listCardFields;if(i&&!Array.isArray(i)&&i.title?.length){let a=Ae(e,t,i.title,n);return a.length>0?a.join(i.titleSeparator??" "):void 0}let s=en(e).find(a=>e.fields[a]?.type==="text");return s?W(Ae(e,t,[s],n)[0]):void 0}function Yr(e,t,n,r){let i=e.seo?.description;if(i)return W(i(t,r.t));let s=n.find(h=>jr.has(e.fields[h]?.type??"")&&W(t[h])!==void 0);if(s)return et(String(t[s]));let a=e.listCardFields;if(!a||Array.isArray(a))return;let p=[Ae(e,t,a.subtitle??[],r).join(" "),...Ae(e,t,a.content??[],r)].filter(Boolean);return p.length>0?p.join(Wr):void 0}function zr(e,t){if(typeof t.status!="string")return;let r={...Kr,...e.seo?.availability}[t.status];return r?`https://schema.org/${r}`:void 0}function Xr(e,t){if(e.type==="price"&&t&&typeof t=="object"){let{amount:i,currency:s}=t;return typeof i=="number"&&i>0?{amount:i,currency:W(s)??Qt}:void 0}let n=typeof t=="string"?Number(t):t;if(typeof n!="number"||!(n>0))return;let r=e.options?.fieldSpecific;return{amount:n,currency:r?.currency??Qt}}function Oc(e,t,n){let r=en(e),i=v=>e.fields[v],s=Yr(e,t,r,n),a=s?Hr(s,$r):void 0,c=r.find(v=>Jt.has(i(v)?.type??"")&&Zt(t[v]).length>0),p=c?Zt(t[c]):[],h;for(let v of r){let x=i(v);if(!(!x||!qr.has(x.type))&&(h=Xr(x,t[v]),h))break}return{title:Gr(e,t,n),description:a||void 0,image:p[0],images:p,price:h,availability:zr(e,t)}}function Pc(e,t){return e.title?{"@context":"https://schema.org","@type":"Product",name:e.title,...e.description&&{description:e.description},...e.images.length>0&&{image:e.images},url:t,...e.price&&{offers:{"@type":"Offer",price:e.price.amount,priceCurrency:e.price.currency,...e.availability&&{availability:e.availability},url:t}}}:null}function Qr(e){return typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:typeof e=="boolean"?e?"true":"false":String(e)}function Zr(e){let t=`resource.data.${e.field}`,n=Qr(e.value);return`${t} ${e.op} ${n}`}function Fc(e){let t=[];if(e.publicCondition&&e.publicCondition.length>0){let n=e.publicCondition.map(Zr).join(" && ");t.push(`(${n})`)}for(let n of e.ownerFields)t.push(`request.auth.uid == resource.data.${n}`);return t.length===0?"false":t.join(" || ")}function _c(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}function Jr(){let e=new Uint8Array(32);return crypto.getRandomValues(e),tn(e)}async function eo(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return tn(new Uint8Array(r))}async function Mc(){let e=Jr(),t=await eo(e);return{codeVerifier:e,codeChallenge:t}}function tn(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Lc(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function Bc(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function Vc(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}async function jc(e,t,n){try{return await e()}catch{return t(),!1}}var Ce=new Map;function Wc(e,t){if(Ce.has(t))return Ce.get(t);let n=e().catch(r=>{throw Ce.delete(t),r});return Ce.set(t,n),n}var nn={[w.GUEST]:0,[w.USER]:1,[w.ADMIN]:2,[w.SUPER]:3};function K(e,t){if(!e)return!1;let n=nn[e]??-1,r=nn[t]??1/0;return n>=r}function Gc(e){return e?e.role===w.SUPER||e.isSuper===!0?w.SUPER:e.role===w.ADMIN||e.isAdmin===!0?w.ADMIN:e.role===w.USER?w.USER:e.role||w.USER:w.USER}function Xc(e,t,n){if(!e)return!1;let r=n??je,i=r[e]?.level??-1,s=r[t]?.level??1/0;return i>=s}var rn="__DNDEV_SINGLETONS__";function on(){if(typeof globalThis<"u"){let e=globalThis,t=e[rn];if(t)return t;let n=new Map;return e[rn]=n,n}return new Map}function Ie(e,t){let n=on();return n.has(e)||n.set(e,t()),n.get(e)}function Zc(e){on().delete(e)}function Jc(e,...t){let n=null,r=!1;return function(){if(n!==null)return n;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{r=!1}}}function ed(e){let t=null,n=!1;return function(...i){if(t!==null)return t;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof e=="function"&&e.prototype?t=new e(...i):t=e(...i),t}finally{n=!1}}}function td(e){let t=null,n=!1,r=null;return async function(){if(t!==null)return t;if(n&&r)return r;if(n)throw new Error("Circular dependency detected in async singleton initialization");n=!0;try{return r=e(),t=await r,t}finally{n=!1,r=null}}}function nd(e,t){return new Proxy({},{get(n,r){if(t.includes(r)){let s=e(),a=s[r];return typeof a=="function"?a.bind(s):a}return e()[r]}})}var de=class{static async getOrCreate(t,n,r={}){if(this.instances.has(t))return this.instances.get(t);if(this.initialized.has(t))return this.instances.get(t);if(this.initializing.has(t))throw new Error(`Circular dependency detected for singleton: ${t}`);if(r.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u"&&process.env.NODE_ENV,r.fallbackFactory){let i=r.fallbackFactory();return this.instances.set(t,i),this.initialized.add(t),i}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let i=await n();return this.instances.set(t,i),this.initialized.add(t),i}catch(i){if(typeof process<"u"&&process.env.NODE_ENV,r.cacheFailures&&this.initialized.add(t),r.fallbackFactory){let s=r.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw i}finally{this.initializing.delete(t)}}static isInitialized(t){return this.initialized.has(t)}static clear(t){this.instances.delete(t),this.initialized.delete(t),this.initializing.delete(t)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};T(de,"instances",new Map),T(de,"initializing",new Set),T(de,"initialized",new Set);function we(){return Ie("providers",()=>({providers:null}))}function sd(e){let t=we();t.providers,t.providers=e}function ad(e){let{providers:t}=we();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let n=t[e];if(!n)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return n}function ld(e){return!!we().providers?.[e]}function ud(){we().providers=null}var tt=["text","textarea","richtext","field-array"];function pe(e){return`${e}I18n`}function dd(e){return Object.keys(e).filter(t=>e[t]?.i18n===!0)}function to(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function pd(e,t,n){let r=null;for(let i of t){let s=e[pe(i)];if(!s||typeof s!="object")continue;let a=s[n];to(a)&&(r??(r={...e}),r[i]=a)}return r??e}var fd="dndev-lang";function gd(e,t){if(!e)return null;for(let n of e.split(";")){let r=n.indexOf("=");if(r!==-1&&n.slice(0,r).trim()===t)try{return decodeURIComponent(n.slice(r+1).trim())}catch{return null}}return null}function yd(e){return e?e.split(",").map((t,n)=>{let[r="",...i]=t.trim().split(";"),s=i.find(c=>c.trim().startsWith("q=")),a=s?Number(s.trim().slice(2)):1;return{tag:r.trim(),quality:Number.isFinite(a)?a:0,index:n}}).filter(t=>t.tag!==""&&t.tag!=="*"&&t.quality>0).sort((t,n)=>n.quality-t.quality||t.index-n.index).map(t=>t.tag):[]}function sn({supported:e,fallback:t,stored:n,preferred:r}){if(n&&e.includes(n))return n;for(let i of r??[]){if(e.includes(i))return i;let s=i.split("-")[0];if(s&&e.includes(s))return s}return t}function nt(e){return e.length>1}var no="dndev-session";function bd(e){let t=e.split("/"),n=t.indexOf(no);return n!==1&&n!==2?e:(t.splice(n,1),t.join("/")||"/")}function an(e,t){let n={language:t.defaultLanguage,path:e,prefixed:!1};if(!nt(t.languages))return n;let r=e.indexOf("/",1),i=r===-1?e.slice(1):e.slice(1,r);return t.languages.includes(i)?{language:i,path:r===-1?"/":e.slice(r),prefixed:!0}:n}function ln(e,t,n){if(!e.startsWith("/")||e.startsWith("//")||!nt(n.languages))return e;let r=e.search(/[?#]/),i=r===-1?e:e.slice(0,r),s=r===-1?"":e.slice(r),a=an(i,n),c=a.prefixed?a.language:t;return c===n.defaultLanguage?`${a.path}${s}`:`/${c}${a.path==="/"?"":a.path}${s}`}function Ed(e,t,n){return Object.fromEntries(n.languages.map(r=>[r,`${t}${ln(e,r,n)}`]))}function Sd(e,t,n){let r=an(e,n);if(!nt(n.languages))return{type:"pass",language:r.language,path:r.path};if(r.prefixed)return r.language===n.defaultLanguage?{type:"redirect",language:r.language,path:r.path,location:r.path,permanent:!0}:{type:"pass",language:r.language,path:r.path};let i=sn({supported:n.languages,fallback:n.defaultLanguage,stored:t.stored,preferred:t.preferred});return i!==n.defaultLanguage?{type:"redirect",language:i,path:r.path,location:ln(r.path,i,n),permanent:!1}:{type:"rewrite",language:n.defaultLanguage,path:r.path,destination:`/${n.defaultLanguage}${r.path==="/"?"":r.path}`}}function Td(e){return{updatedAt:new Date().toISOString(),updatedById:e}}function ro(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function oo(e){if(ro(e))return e.visibility}function io(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?K(t,"admin"):n==="owner"?!1:K(t,n)}function so(e,t,n){for(let r of n.ownerFields)if(e[r]===t)return!0;return!1}function un(e,t,n){if(!e||typeof e!="object"||!("entries"in e)||!e.entries)return[];let r=e.entries,i=[],{documentData:s,uid:a,ownership:c}=n??{},p=c&&a!=null&&s&&so(s,a,c);for(let[h,v]of Object.entries(r)){let x=oo(v);if(x==="owner"){p&&i.push(h);continue}io(x,t)&&i.push(h)}return i}function Id(e,t,n,r){if(!e)return{};let i=r?.uid!=null&&r?.ownership!=null?{documentData:r.documentData??e,uid:r.uid,ownership:r.ownership}:void 0,s=un(t,n,i),a={};for(let c of s)Object.prototype.hasOwnProperty.call(e,c)&&(a[c]=e[c]);return a}function Oe(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,r=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(r)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}function cn(e){return typeof e=="object"&&e!==null}function Pe(e){if(cn(e)){if(cn(e.entries))return e.entries;if(Array.isArray(e.pipe))for(let t of e.pipe){let n=Pe(t);if(n)return n}if(e.wrapped)return Pe(e.wrapped);if(Array.isArray(e.options))for(let t of e.options){let n=Pe(t);if(n)return n}}}function Pd(e){let t=Pe(e);if(!t)return!1;for(let n of Object.values(t)){let r=n?.visibility;if(r!==void 0&&r!=="guest")return!0}return!1}import*as dn from"valibot";function ao(e,t){let n=dn.parse(_,t??ve);return{...n,userId:e,isActive:n.status===he.ACTIVE,features:n.features??[]}}var rt=class{constructor(t={}){T(this,"store",new Map);T(this,"maxAttempts");T(this,"lockoutMs");T(this,"sessionTimeoutMs");this.maxAttempts=t.maxAttempts??5,this.lockoutMs=t.lockoutMs??900*1e3,this.sessionTimeoutMs=t.sessionTimeoutMs??480*60*1e3}checkLockout(t){let n=this.store.get(t);if(n?.lockedUntil){if(Date.now()<n.lockedUntil){let r=Math.ceil((n.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${r} minute${r===1?"":"s"}.`)}this.store.delete(t)}}recordFailure(t){let n=Date.now();!this.store.has(t)&&this.store.size>=1e4&&this._evictExpired(n);let r=this.store.get(t)??{attempts:0,lastAttempt:0,lockedUntil:null};return r.attempts+=1,r.lastAttempt=n,r.attempts>=this.maxAttempts&&(r.lockedUntil=n+this.lockoutMs),this.store.set(t,r),{attempts:r.attempts,locked:r.lockedUntil!==null&&Date.now()<r.lockedUntil,lockedUntil:r.lockedUntil}}_evictExpired(t){for(let[n,r]of this.store)r.lockedUntil!==null&&t>r.lockedUntil?this.store.delete(n):r.lockedUntil===null&&t-r.lastAttempt>this.lockoutMs&&this.store.delete(n)}recordSuccess(t){this.store.delete(t)}isSessionExpired(t){return Date.now()-t>this.sessionTimeoutMs}getEntry(t){return this.store.get(t)}};function lo(e,t){if(t.includes(".")){let n=t.split("."),r=e;for(let i of n){if(r==null||typeof r!="object")return;r=r[i]}return r}return e[t]}function uo(e,t){let n=lo(t,e.field);switch(e.operator){case"equals":return n===e.value;case"notEquals":return n!==e.value;case"in":return Array.isArray(e.value)&&e.value.includes(n);case"notIn":return Array.isArray(e.value)&&!e.value.includes(n);case"greaterThan":return typeof n=="number"&&typeof e.value=="number"&&n>e.value;case"lessThan":return typeof n=="number"&&typeof e.value=="number"&&n<e.value;case"greaterThanOrEqual":return typeof n=="number"&&typeof e.value=="number"&&n>=e.value;case"lessThanOrEqual":return typeof n=="number"&&typeof e.value=="number"&&n<=e.value;case"exists":return n!=null&&n!==""&&n!==!1;case"notExists":return n==null||n===""||n===!1;case"contains":return typeof n=="string"&&typeof e.value=="string"||Array.isArray(n)?n.includes(e.value):!1;default:return!1}}function co(e){return e instanceof me||"expression"in e?e.expression:e}function ee(e,t){let n=co(e);if(n.type==="condition")return uo(n,t);let{logic:r,conditions:i}=n;return r==="and"?i.every(s=>ee(s,t)):i.some(s=>ee(s,t))}function Kd(e,t){return e?{visible:e.visible?ee(e.visible,t):!0,disabled:e.disabled?ee(e.disabled,t):!1,required:e.required?ee(e.required,t):!1,readonly:e.readonly?ee(e.readonly,t):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var me=class e{constructor(t){T(this,"expression");this.expression=t}get type(){return this.expression.type}or(t){let n=t instanceof e?t.expression:t,r=this.expression;return r.type==="group"&&r.logic==="or"?new e({type:"group",logic:"or",conditions:[...r.conditions,n]}):new e({type:"group",logic:"or",conditions:[r,n]})}and(t){let n=t instanceof e?t.expression:t,r=this.expression;return r.type==="group"&&r.logic==="and"?new e({type:"group",logic:"and",conditions:[...r.conditions,n]}):new e({type:"group",logic:"and",conditions:[r,n]})}};function Hd(e){function t(n,r){return new me({type:"condition",field:e,operator:n,value:r})}return{equals:n=>t("equals",n),notEquals:n=>t("notEquals",n),in:n=>t("in",n),notIn:n=>t("notIn",n),greaterThan:n=>t("greaterThan",n),lessThan:n=>t("lessThan",n),greaterThanOrEqual:n=>t("greaterThanOrEqual",n),lessThanOrEqual:n=>t("lessThanOrEqual",n),exists:()=>t("exists"),notExists:()=>t("notExists"),contains:n=>t("contains",n)}}function Gd(e){let t=e instanceof me?e.expression:e,n=new Set;function r(i){if(i.type==="condition")n.add(i.field);else for(let s of i.conditions)r(s)}return r(t),n}var po=new Set(["http:","https:","mailto:","tel:","blob:"]);function Xd(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(po.has(n.protocol))return t}catch{return t}return""}function Zd(){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var ep=3e4,tp=15e3;function np(e,t,n){if(n?.aborted)return Promise.reject(pn(n.reason));let r=t>0;return!r&&!n?e:new Promise((i,s)=>{let a=!1,c;function p(){a=!0,c!==void 0&&(clearTimeout(c),c=void 0),n&&n.removeEventListener("abort",h)}function h(){a||(p(),s(pn(n?.reason)))}n&&n.addEventListener("abort",h,{once:!0}),r&&(c=setTimeout(()=>{a||(p(),s(mo(t)))},t)),e.then(v=>{a||(p(),i(v))},v=>{a||(p(),s(v))})})}function mo(e){let t=new Error(`Operation timed out after ${e}ms`);return t.name="TimeoutError",t}function pn(e){if(e instanceof Error){let n=new Error(e.message);return n.name="AbortError",n}let t=new Error(typeof e=="string"?e:"Operation was aborted");return t.name="AbortError",t}var ot=Q.map(e=>({value:e,label:`crud:status.${e}`})),$p=Ee;var fo=[...le,"status"];function jp(e){return fo.some(t=>t===e)}function mn(e){return le.some(t=>t===e)}var C={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...ot]}},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:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}};var De=e=>{let t=[];return e.validation?.minLength!==void 0&&t.push(u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(u.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(u.regex(new RegExp(e.validation.pattern),"Invalid format")),t.length>0?u.pipe(u.string(),...t):u.string()},go=()=>u.pipe(u.string(),u.email("Invalid email address")),yo=e=>e.validation?.minLength!==void 0?u.pipe(u.string(),u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):u.string(),ho=()=>u.pipe(u.string(),u.url("Invalid URL")),te=e=>{let t=[];return e.validation?.min!==void 0&&t.push(u.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(u.maxValue(e.validation.max,`Must be at most ${e.validation.max}`)),t.length>0?u.pipe(u.number(),...t):u.number()},fn=()=>u.boolean(),it=()=>u.pipe(u.string(),u.check(e=>!isNaN(new Date(e).getTime()),"Invalid date format")),vo=/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/,bo=/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/,Eo=/^\d{4}-(?:0[1-9]|1[0-2])$/,So=()=>u.pipe(u.string(),u.regex(vo,"Invalid time format")),xo=()=>u.pipe(u.string(),u.regex(bo,"Invalid week format")),To=()=>u.pipe(u.string(),u.regex(Eo,"Invalid month format")),Tn=u.object({url:u.string(),filename:u.string(),size:u.number(),mimeType:u.nullish(u.string()),uploadedAt:u.nullish(u.string())}),gn=()=>Tn,yn=()=>u.array(Tn),Rn=u.object({fullUrl:u.string(),thumbUrl:u.string()}),Ro=()=>u.union([u.string(),Rn]),ko=()=>u.array(u.union([u.string(),Rn])),Ao=()=>u.object({lat:u.number(),lng:u.number()}),Co=()=>u.object({formatted_address:u.string(),latitude:u.number(),longitude:u.number(),street_number:u.nullish(u.string()),route:u.nullish(u.string()),locality:u.nullish(u.string()),administrative_area_level_1:u.nullish(u.string()),administrative_area_level_2:u.nullish(u.string()),country:u.nullish(u.string()),postal_code:u.nullish(u.string())}),Io=()=>u.record(u.string(),u.unknown()),wo=()=>u.array(u.unknown()),Oo=()=>u.array(u.record(u.string(),u.unknown())),st=e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?u.picklist(t.map(n=>n.value)):u.union([u.string(),u.number()])},Po=e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?u.array(u.picklist(t.map(n=>n.value))):u.array(u.string())},kn=()=>u.pipe(u.string(),u.minLength(1,"Invalid ID format")),at=()=>u.string(),Do=/^(?:\+[1-9](?:[ .-]?\d){7,14}|0[1-9](?:[ .-]?\d{2}){4})$/,Fo=e=>{let t=e.validation?.pattern?new RegExp(e.validation.pattern):Do;return u.pipe(u.string(),u.regex(t,"Invalid phone number"))},No=e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,r=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$";return u.pipe(u.string(),u.minLength(t,`IBAN must be at least ${t} characters`),u.maxLength(n,`IBAN must not exceed ${n} characters`),u.regex(new RegExp(r),"Invalid IBAN format"))},hn=()=>u.never();function An(e){let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue)return[t.checkedValue,t.uncheckedValue]}var _o=e=>{let t=An(e);return t?u.picklist(t):u.boolean()},vn=u.looseObject({gdprConsent:u.literal(!0),gdprConsentDate:u.optional(u.string()),gdprConsentVersion:u.optional(u.string())},"GDPR consent must be given"),Uo=e=>e.validation?.required?vn:u.union([u.literal(!1),vn]),Mo=()=>u.object({amount:u.number(),currency:u.optional(u.string()),vatIncluded:u.optional(u.boolean()),discountPercent:u.optional(u.pipe(u.number(),u.minValue(0),u.maxValue(100)))}),Cn={text:{schema:De,kind:"text"},textarea:{schema:De,kind:"text"},richtext:{schema:De,kind:"text"},color:{schema:De,kind:"text"},email:{schema:go,kind:"text"},password:{schema:yo,kind:"text"},url:{schema:ho,kind:"text"},tel:{schema:Fo,kind:"text"},iban:{schema:No,kind:"text"},number:{schema:te,kind:"number"},currency:{schema:te,kind:"number"},range:{schema:te,kind:"number"},year:{schema:te,kind:"number"},rating:{schema:te,kind:"number"},duration:{schema:te,kind:"number"},price:{schema:Mo,kind:"json"},boolean:{schema:fn,kind:"boolean"},checkbox:{schema:fn,kind:"boolean"},switch:{schema:_o,kind:e=>An(e)?"text":"boolean"},gdprConsent:{schema:Uo,kind:"json"},date:{schema:it,kind:"date"},"datetime-local":{schema:it,kind:"timestamp"},timestamp:{schema:it,kind:"timestamp"},time:{schema:So,kind:"time"},week:{schema:xo,kind:"text"},month:{schema:To,kind:"text"},file:{schema:gn,kind:"json"},files:{schema:yn,kind:"json"},document:{schema:gn,kind:"json"},documents:{schema:yn,kind:"json"},image:{schema:Ro,kind:"json"},images:{schema:ko,kind:"json"},geopoint:{schema:Ao,kind:"json"},address:{schema:Co,kind:"json"},map:{schema:Io,kind:"json"},array:{schema:wo,kind:"json"},"field-array":{schema:Oo,kind:"json"},select:{schema:st,kind:"text"},radio:{schema:st,kind:"text"},combobox:{schema:st,kind:"text"},multiselect:{schema:Po,kind:"json"},reference:{schema:kn,kind:"ref"},hidden:{schema:at,kind:"text"},avatar:{schema:at,kind:"text"},badge:{schema:at,kind:"text"},submit:{schema:hn,kind:"text"},reset:{schema:hn,kind:"text"}},Lo=new Set(At);function Bo(e){return Lo.has(e)}var Vo=new Set(["optional","exact_optional","nullable","nullish","undefinedable","non_nullable","non_nullish","non_optional"]),$o=new Set(["object","loose_object","strict_object","object_with_rest","record","array","tuple","loose_tuple","strict_tuple","tuple_with_rest","intersect"]),jo=new Set(["trim","trim_start","trim_end","to_lower_case","to_upper_case","to_min_value","to_max_value","normalize","brand","flavor","readonly"]),qo={iso_date:"date",iso_time:"time",iso_time_second:"time",iso_date_time:"timestamp",iso_timestamp:"timestamp"};function L(e,t){return t in e?Reflect.get(e,t):void 0}function bn(e){if(typeof e=="string")return"text";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}function En(e){if(e.length===0||e.some(n=>n===void 0))return;let t=new Set(e);return t.size===1?e[0]:t.has("json")?"json":void 0}function Fe(e){if(typeof e!="object"||e===null)return;let t=L(e,"type");if(typeof t!="string")return;let n=Wo(e,t),r=L(e,"pipe");if(Array.isArray(r))for(let i of r.slice(1)){if(typeof i!="object"||i===null)continue;let s=L(i,"kind"),a=L(i,"type");if(typeof a=="string"){if(s==="schema")n=Fe(i);else if(s==="transformation")jo.has(a)||(n=void 0);else if(s==="validation"){a==="integer"&&n==="number"&&(n="integer");let c=qo[a];c&&n==="text"&&(n=c)}}}return n}function Wo(e,t){if(Vo.has(t))return Fe(L(e,"wrapped"));if($o.has(t))return"json";switch(t){case"string":return"text";case"number":return"number";case"bigint":return"integer";case"boolean":return"boolean";case"date":return"timestamp";case"literal":return bn(L(e,"literal"));case"picklist":case"enum":{let n=L(e,"options");return Array.isArray(n)?En(n.map(bn)):void 0}case"union":case"variant":{let n=L(e,"options");if(!Array.isArray(n))return;let r=n.filter(i=>{let s=typeof i=="object"&&i!==null?L(i,"type"):void 0;return s!=="null"&&s!=="undefined"});return En(r.map(Fe))}default:return}}function Sn(e,t){let{kind:n}=Cn[e];return typeof n=="function"?n(t):n}function lt(e,t=e.name){let n=e.validation?.reference,r=n?{ref:n}:{},i=e.type,s=Bo(i)?i:void 0,a=e.validation?.schema;if(a){let c=(n?"ref":void 0)??Fe(a)??(s?Sn(s,e):void 0);if(!c)throw new Error(`Field '${t}' (custom type '${i}'): the storage kind of its validation.schema cannot be read. Root the schema on a Valibot string, number, boolean, picklist, object or array schema, or set validation.reference.`);return{schema:a,kind:c,...r}}if(n)return{schema:kn(),kind:"ref",...r};if(s)return{schema:Cn[s].schema(e),kind:Sn(s,e)};throw new Error(`Field '${t}' has custom type '${i}' and no value shape. Add validation.schema (a Valibot schema of the stored value) or validation.reference (the referenced collection) to the field, or use a built-in type.`)}function Ko(e){return e.validation?.required===!0?"always":e.conditions?.required!==void 0?"conditional":"never"}function Ho(e,t){return t.visibility==="hidden"||t.editable===V.GENERATED||mn(e)?"never":t.editable===V.FALSE?"program":t.editable===V.COMPUTED?"derived":"user"}function Go(e,t){return(n,r)=>{if(t!=="user")return!1;let i=e.editable;return i===void 0||i===V.TRUE?e.visibility!=="technical":i===V.CREATE_ONLY?r==="create":typeof i=="string"?K(n,i):!1}}function Yo(e,t,n){let r=Ho(e,t);return{value:lt(t,`${n}.${e}`),required:Ko(t),write:r,editableFor:Go(t,r),visibleAt:t.visibility,...t.i18n===!0&&{companion:pe(e)}}}var xn=new WeakMap;function Ne(e){let t=xn.get(e);if(t)return t;let n={};for(let[i,s]of Object.entries(e.fields))n[i]=Yo(i,s,e.name);let r={name:e.name,collection:e.collection,fields:n};return xn.set(e,r),r}function zo(e,t){return t?ne.pipe(e,ne.check(n=>n!=="","Required")):ne.nullish(e)}function H(e){return zo(lt(e).schema,e.validation?.required)}var In=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function wn(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function On(e){return typeof e=="object"&&e!==null}function _e(e,t=""){if(Array.isArray(e))e.forEach((n,r)=>{let i=`${t}[${r}]`;if(typeof n=="string"&&wn(n)){if(!In.test(n))throw k(new Error(`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`),{userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:i,value:n},severity:"error"})}else On(n)&&_e(n,i)});else if(typeof e=="object"&&e!==null)for(let[n,r]of Object.entries(e)){let i=t?`${t}.${n}`:n;if(typeof r=="string"&&wn(r)){if(!In.test(r))throw k(new Error(`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else On(r)&&_e(r,i)}}import*as Dn from"valibot";var ut={};function Jp(e){ut.uniqueConstraintValidator=e}async function Pn(e,t,n){let{uniqueFields:r=[],collection:i}=e.metadata;if(r.length!==0){if(!ut.uniqueConstraintValidator){process.env.NODE_ENV;return}await Promise.all(r.map(async({field:s,errorMessage:a})=>{let c=t[s];if(c==null)return;if(await ut.uniqueConstraintValidator.checkDuplicate(i,s,c,n))throw k(new Error(a||`${s} must be unique`),{userMessage:a||`${s} must be unique`,context:{field:s}})}))}}async function rm(e,t,n,r){Dn.parse(e,t),_e(t),await Pn(e,t,r),e.metadata.customValidate&&await e.metadata.customValidate(t,n)}function Xo(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function pm(e){if(!Xo(e)){let t=e,n=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw k(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:n}})}return e.metadata.collection}var Fn=()=>Ie("entity-registry",()=>new Map);function Nn(e){Fn().set(e.collection,e)}function Qo(e){return Fn().get(e)}var Zo=new Set(["__proto__","constructor","prototype"]);function Jo(e){for(let t of Object.keys(e.fields))if(Zo.has(t))throw k(new Error(`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`),{userMessage:`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`,context:{entityName:e.name,fieldName:t,operation:"defineEntity"},severity:"error"})}function ei(e){let t=e.field.endsWith("Id")?e.field.slice(0,-2):e.field,n=e.collection||(t.endsWith("y")?t.slice(0,-1)+"ies":t+"s");return{name:e.field,label:`crud:fields.${e.field}`,type:"reference",visibility:"technical",editable:V.CREATE_ONLY,validation:{required:!0,reference:n}}}function ti(e,t){if(!t||t.length===0)return e.map(i=>({value:i.value,label:i.label}));let n=e.map(i=>({value:i.value,label:i.label})),r=new Set(e.map(i=>i.value));for(let i of t)r.has(i.value)||n.push(i);return n}function ni(e,t){if(!(!e.uniqueKeys||e.uniqueKeys.length===0))for(let n=0;n<e.uniqueKeys.length;n++){let r=e.uniqueKeys[n];if(!r)continue;if(!r.fields||r.fields.length===0)throw k(new Error(`uniqueKeys[${n}] for entity '${e.name}' must have at least one field`),{userMessage:`uniqueKeys[${n}] for entity '${e.name}' must have at least one field`,context:{entityName:e.name,uniqueKeyIndex:n},severity:"error"});let i=r.fields.filter(s=>!t.has(s));if(i.length>0)throw k(new Error(`uniqueKeys[${n}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${n}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:e.name,uniqueKeyIndex:n,invalidFields:i},severity:"error"})}}function ri(e){let{form:t,fields:n}=e,r=Object.keys(n);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw k(new Error(`Multi-step form for entity '${e.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${e.name}' must have at least one step`,context:{entityName:e.name,operation:"validateFormConfig"},severity:"error"});let i=t.steps.flatMap(p=>p.fields),s=i.filter(p=>!r.includes(p));if(s.length>0)throw k(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`,context:{entityName:e.name,invalidFields:s,operation:"validateFormConfig"},severity:"error"});let a=new Set(i);r.filter(p=>!a.has(p)).length>0&&process.env.NODE_ENV}t.rules&&t.rules.forEach((i,s)=>{let c=(Array.isArray(i.condition)?i.condition.map(v=>v.field):[i.condition.field]).filter(v=>!r.includes(v));if(c.length>0)throw k(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${c.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${c.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:c,operation:"validateFormConfig"},severity:"error"});let h=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(v=>!r.includes(v));if(h.length>0)throw k(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:h,operation:"validateFormConfig"},severity:"error"})}),Object.entries(n).forEach(([i,s])=>{if(s.dependsOn&&!r.includes(s.dependsOn.field))throw k(new Error(`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`,context:{entityName:e.name,fieldName:i,dependsOnField:s.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function oi(e){return e.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...e.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function Sm(e){let t=e;try{Jo(t),ri(t);let n=oi(t),r={...t.fields,...C,...t.fields.createdAt&&{createdAt:{...C.createdAt,...t.fields.createdAt,type:C.createdAt.type,visibility:C.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...C.updatedAt,...t.fields.updatedAt,type:C.updatedAt.type,visibility:C.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...C.createdById,...t.fields.createdById,type:C.createdById.type,visibility:C.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...C.updatedById,...t.fields.updatedById,type:C.updatedById.type,visibility:C.updatedById.visibility}},...t.fields.status&&{status:{...C.status,...t.fields.status,validation:{...C.status.validation,...t.fields.status.validation,options:ti(ot,t.fields.status.validation?.options)}}},...t.scope&&{[t.scope.field]:ei(t.scope)}};if(t.listFields){let c=new Set(Object.keys(r)),p=t.listFields.filter(h=>!c.has(h));if(p.length>0)throw k(new Error(`Entity '${t.name}' defines listFields that do not exist: ${p.join(", ")}`),{userMessage:`Entity '${t.name}' defines listFields that do not exist: ${p.join(", ")}`,context:{entityName:t.name,invalidFields:p,operation:"defineEntity"},severity:"error"})}if(t.listCardFields){let c=new Set(Object.keys(r)),h=Oe(t).filter(v=>!c.has(v));if(h.length>0)throw k(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${h.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${h.join(", ")}`,context:{entityName:t.name,invalidFields:h,operation:"defineEntity"},severity:"error"})}if(t.uniqueKeys){let c=new Set(Object.keys(r));ni(t,c)}let i={...Ke,...t.access||{}},s=t.namespace||`entity-${t.name.toLowerCase()}`,a={...t,form:n,fields:r,access:i,namespace:s,...t.search&&{search:t.search},...t.defaultSort&&{defaultSort:t.defaultSort}};try{Ne(a)}catch(c){let p=c instanceof Error?c.message:String(c);throw k(new Error(p),{userMessage:p,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}return Nn(a),a}catch(n){throw k(n,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}import*as I from"valibot";function D(e){let t=e?.status;return typeof t=="string"?t:null}function Me({op:e,status:t,storedStatus:n}){return Ue(t??n,"saveIncomplete")?"draft":e==="create"?"create":"update"}function _n({op:e,status:t,storedStatus:n}){if(e!=="update")return!1;let r=t??n;return r==null||r===n?!1:Ue(n,"holdIncomplete")&&!Ue(r,"holdIncomplete")}function Un(e){return e!=null&&Object.hasOwn(U,e)?U[e]:Rt}function Ue(e,t){return Un(e)[t]}function Le(e,t){let n=Un(e).read;return n==="guest"||K(t,n)}function ct(e){return Object.keys(U).filter(t=>U[t][e])}function Y(e,t){return Object.assign(e,{visibility:t})}function G(e,t){return Object.assign(e,{metadata:{collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys},...t.security&&{security:t.security}}})}function ii(e){let t=H(e);return Y(t,e.visibility)}function si(e,t){if(!tt.includes(t.type))throw new Error(`Field '${e}' has i18n: true but type '${t.type}'. Translatable types: ${tt.join(", ")}.`);let n=H({...t,validation:{...t.validation,required:!1}});return Y(I.optional(I.nullable(I.record(I.string(),n))),t.visibility)}function re(e,t){for(let n of Object.keys(e)){let r=t[n];r?.i18n===!0&&(e[pe(n)]=si(n,r))}return e}function dt(e){let t=H({...e,validation:{...e.validation,required:!1}});return Y(t,e.visibility)}function ai(e){return e.validation?.required?Y(I.optional(H(e)),e.visibility):dt(e)}function Pm(e){let t=e.fields,n=Ne(e).fields,r=A=>n[A]?.write==="never",i={};for(let[A,P]of Object.entries(t))n[A]?.visibleAt!=="hidden"&&(i[A]=dt(P));let s=G(I.object(re({...i},t)),e),a={};for(let[A,P]of Object.entries(t))r(A)||(a[A]=ii(P));let c=G(I.object(re({...a},t)),e),p={};for(let[A,P]of Object.entries(t))if(!r(A))if(A==="status"){let j=I.picklist(ct("saveIncomplete"));p[A]=Y(j,P.visibility)}else p[A]=dt(P);let h=G(I.object(re({...p},t)),e),v={};for(let[A,P]of Object.entries(t))r(A)||(v[A]=ai(P));v.id=Y(H(C.id),"technical");let x=G(I.object(re({...v},t)),e),B;if(e.listFields&&e.listFields.length>0){let A=["id","status"],P=[...new Set([...A,...e.listFields])];B={};for(let j of P){let ie=i[j];ie&&(B[j]=ie)}}else B=i;let ge=G(I.object(re({...B},t)),e),R,X=Oe(e);if(X.length>0){let A=["id","status"],P=[...new Set([...A,...X])];R={};for(let j of P){let ie=i[j];ie&&(R[j]=ie)}}else R=i;let Wn=G(I.object(re({...R},t)),e),Kn=G(I.object({id:Y(H(C.id),"technical")}),e);return{create:c,draft:h,update:x,get:s,list:ge,listCard:Wn,delete:Kn}}function Fm(e,t,n=1,r=!1){let i=[];if(r)for(let s=t;s>=e;s-=n)i.push({value:String(s),label:String(s)});else for(let s=e;s<=t;s+=n)i.push({value:String(s),label:String(s)});return i}var z=new Map;function _m(e,t){z.has(e)&&process.env.NODE_ENV,z.set(e,t)}function Um(e){z.delete(e)}function Mm(e){let t=z.get(e);return t?t():(process.env.NODE_ENV,null)}function Lm(e){return z.has(e)}function Bm(){return Array.from(z.keys())}function Vm(){z.clear()}import*as g from"valibot";var li=g.record(g.string(),g.unknown()),ui=g.object({id:g.string(),patch:g.record(g.string(),g.unknown())}),ci=g.string(),jm=g.object({inserts:g.optional(g.array(li)),updates:g.optional(g.array(ui)),deletes:g.optional(g.array(ci))}),di=g.object({insertedIds:g.array(g.string()),updatedIds:g.array(g.string()),deletedIds:g.array(g.string())}),pi=g.variant("op",[g.object({op:g.literal("insert"),index:g.pipe(g.number(),g.integer(),g.minValue(0)),id:g.optional(g.string()),error:g.string()}),g.object({op:g.literal("update"),id:g.string(),index:g.optional(g.pipe(g.number(),g.integer(),g.minValue(0))),error:g.string()}),g.object({op:g.literal("delete"),id:g.string(),index:g.optional(g.pipe(g.number(),g.integer(),g.minValue(0))),error:g.string()})]),mi=g.object({...di.entries,failed:g.optional(g.array(pi),()=>[])});function qm(e,t){let n=g.parse(mi,t),r=c=>{throw new Error(`Invalid bulk acknowledgement: ${c}`)},i=e.inserts??[],s=new Set;for(let c of n.failed){if(c.op!=="insert")continue;(c.index>=i.length||s.has(c.index))&&r("unknown or duplicate insert index");let p=i[c.index];c.id!==void 0&&c.id!==p.id&&r("contradictory insert identity"),s.add(c.index)}n.insertedIds.length+s.size!==i.length&&r("missing or extra insert outcomes"),new Set(n.insertedIds).size!==n.insertedIds.length&&r("duplicate inserted ID");let a=new Set([...s].map(c=>i[c].id).filter(c=>typeof c=="string"));n.insertedIds.some(c=>a.has(c))&&r("insert ID both successful and failed");for(let c of["update","delete"]){let p=c==="update"?(e.updates??[]).map(({id:R})=>R):e.deletes??[],h=c==="update"?n.updatedIds:n.deletedIds,v=new Map;for(let R of p)v.set(R,(v.get(R)??0)+1);let x=new Map,B=new Set;for(let R of n.failed)R.op===c&&((!v.has(R.id)||R.index!==void 0&&p[R.index]!==R.id)&&r(`unknown or contradictory ${c} identity`),R.index!==void 0&&(B.has(R.index)&&r(`duplicate ${c} failure index`),B.add(R.index)),x.set(R.id,(x.get(R.id)??0)+1));let ge=p.filter(R=>!x.has(R));for(let[R,X]of x)X!==v.get(R)&&r(`duplicate or ambiguous ${c} failures`);(ge.length!==h.length||ge.some((R,X)=>h[X]!==R))&&r(`missing, duplicate, unknown or contradictory ${c} outcomes`)}return n}function Wm(e){let t=new Set((e.updates??[]).map(a=>a.id)),n=e.deletes??[],r=[];for(let a of n)t.has(a)&&r.push(a);if(r.length>0)return{collisions:r,where:"updates-deletes"};let i=e.inserts??[],s=[];for(let a of i)typeof a.id=="string"&&t.has(a.id)&&s.push(a.id);return s.length>0?{collisions:s,where:"inserts-updates"}:{collisions:[],where:null}}import*as Mn from"valibot";function fi(e,t){if(e.ok)return e.written;let n=e.issues.map(r=>`${r.path?.map(i=>String(i.key)).join(".")||"root"}: ${r.message}`).join("; ");throw new S(`Validation failed in ${t}: ${n}`,"validation-failed",{details:{issues:e.issues},source:"validation"})}function Ln(e){let t=e.entries;if(!t||typeof t!="object")throw new S("CRUD write rules: a write schema must be an object schema (createSchemas(entity))","internal");return Object.keys(t)}function Be(e,t){let n=[e.create,e.draft,e.update].filter(i=>i!==void 0);if(n.some(i=>i.type==="loose_object"))return[];let r=new Set([...n.flatMap(Ln),...le]);return Object.keys(t).filter(i=>!r.has(i))}function Bn(e,t){let n={};for(let r of Ln(t))n[r]=null;for(let[r,i]of Object.entries(e))i!==void 0&&(n[r]=i);return n}function fe(e,t,n,r,i){let s=Mn.safeParse(t,n);if(!s.success)return{ok:!1,schemaKey:e,issues:[...s.issues],unknownKeys:i};let a=s.output,c={};for(let p of Object.keys(r))p!=="id"&&Object.hasOwn(a,p)&&(c[p]=a[p]);return{ok:!0,schemaKey:e,written:c,unknownKeys:i}}function Vn(e){return D(e)??Ee}function gi(e,t){let n=Vn(t),r=Me({op:"create",status:n}),i={...t,status:n},s=fe(r,r==="draft"?e.draft:e.create,i,i,Be(e,t));return s.ok?{...s,written:{...s.written,status:n}}:s}function $n(e){return D(e)!==He}function jn(e,t){let n={op:"update",status:D(e),storedStatus:D(t)};return{schemaKey:Me(n)==="draft"?"draft":"update",whole:_n(n)}}function qn(e,{id:t,patch:n,stored:r}){let i=D(n);if(!r&&$n(n))throw new S(`CRUD update rules: row "${t}" needs its stored row (the row's status${i===null?"":" and the publish check"} come from it); read it before the update.`,"internal");let{schemaKey:s,whole:a}=jn(n,r),c=Be(e,n);if(r&&a)return fe(s,e.update,Bn({...r,...n,id:t},e.update),n,c);let p=s==="draft"?{...n,status:D(n)??D(r),id:t}:{...n,id:t};return fe(s,s==="draft"?e.draft:e.update,p,n,c)}function yi(e,t){return qn(e,{id:t,patch:{status:He}})}function hi(e){return Q.filter(t=>!Le(t,e))}function vi(e,t){return Le(D(e),t)}import*as b from"valibot";var mf=b.pipe(b.string(),b.check(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),bi=b.picklist(["ephemeral","session","persistent"]),Ei=b.object({title:b.optional(b.string()),pinnable:b.optional(b.boolean()),preferredHeight:b.optional(b.pipe(b.number(),b.minValue(0)))}),Si=b.object({id:b.pipe(b.string(),b.minLength(1)),kind:b.pipe(b.string(),b.minLength(1)),lifetime:b.optional(bi,"ephemeral"),metadata:b.optional(Ei),payload:b.unknown()}),xi=b.object({widgetId:b.pipe(b.string(),b.minLength(1)),action:b.pipe(b.string(),b.minLength(1)),payload:b.unknown()}),oe=new Map;function ff(e){if(oe.has(e.kind))throw new Error(`[canvas] Widget kind "${e.kind}" already registered.`);oe.set(e.kind,e)}function gf(e){return oe.get(e)}function yf(){return Array.from(oe.values())}function hf(e,t){let n=b.safeParse(Si,e);if(!n.success)return{ok:!1,reason:`Invalid canvas block envelope: ${Ve(n.issues)}`};let r=oe.get(n.output.kind);if(!r)return{ok:!1,reason:`Unknown widget kind: "${n.output.kind}"`};let i=b.safeParse(r.schema,n.output.payload);if(!i.success)return{ok:!1,reason:`Payload rejected by "${n.output.kind}" schema: ${Ve(i.issues)}`};if(t?.caller!==void 0){let a=t.caller.access;if(!Ti(r.surface,a))return{ok:!1,reason:`surface_forbidden: widget "${n.output.kind}" surface=${r.surface} not reachable by caller access=${a===null?"null":a}`}}return{ok:!0,value:{...n.output,payload:i.output},widget:r}}function Ti(e,t){return e==="meta"?!0:e==="household"||e==="private"?t==="admin"||t==="member":!1}function vf(e,t){let n=b.safeParse(xi,e);if(!n.success)return{ok:!1,reason:`Invalid canvas event envelope: ${Ve(n.issues)}`};let r=oe.get(t);if(!r)return{ok:!1,reason:`Unknown widget kind: "${t}"`};let i=r.actions[n.output.action];if(!i)return{ok:!1,reason:`Widget "${t}" has no action "${n.output.action}"`};let s=b.safeParse(i,n.output.payload);return s.success?{ok:!0,value:{...n.output,payload:s.output},widget:r}:{ok:!1,reason:`Payload rejected by "${t}.${n.output.action}" schema: ${Ve(s.issues)}`}}function Ve(e){return e.map(t=>{let n=t.path?.map(r=>String(r.key)).join(".")??"";return n?`${n}: ${t.message}`:t.message}).join("; ")}export{Zs as AGGREGATE_FILTER_OPERATORS,Qs as AGGREGATE_OPERATIONS,Xn as AIChatRequestSchema,Zn as AIChatResponseSchema,pt as AIMessageSchema,Fi as AIProviderConfigSchema,zn as AIToolCallSchema,Yn as AIToolDefinitionSchema,Qn as AIUsageSchema,Ci as AI_ERROR_CODES,ki as AI_MODELS,F as AI_PROVIDERS,ye as AI_ROLES,Ii as AI_TIERS,Oi as AI_TOKEN_PRICING,La as AUTH_EVENTS,Nt as AUTH_PARTNERS,ts as AUTH_PARTNER_STATE,Ct as AtomicBulkError,rt as AuthHardening,mt as AuthUserSchema,le as BACKEND_GENERATED_FIELD_NAMES,Va as BILLING_EVENTS,vr as BREAKPOINT_RANGES,Ye as BREAKPOINT_THRESHOLDS,Cn as BUILTIN_VALUES,Q as BUILT_IN_STATUSES,wt as BulkAcrossCycleError,It as BulkCollisionError,ci as BulkDeleteIdSchema,li as BulkInsertSchema,Ot as BulkNotImplementedError,pi as BulkOutcomeFailureSchema,mi as BulkOutcomeSchema,jm as BulkRequestSchema,di as BulkResponseSchema,ui as BulkUpdateSchema,je as COMMON_TIER_CONFIGS,Ls as CONFIDENCE_LEVELS,Ut as CONSENT_CATEGORY,Ms as CONTEXTS,q as CRUD_OPERATORS,$t as CURRENCY_MAP,Rt as CUSTOM_STATUS,Si as CanvasBlockSchema,xi as CanvasEventSchema,bi as CanvasLifetimeSchema,Ei as CanvasWidgetMetadataSchema,rr as CheckoutLineItemInputSchema,Tt as CheckoutSessionMetadataSchema,me as ConditionBuilder,bt as CreateCheckoutSessionRequestSchema,Et as CreateCheckoutSessionResponseSchema,gt as CustomClaimsSchema,Ai as DEFAULT_AI_CONFIG,wi as DEFAULT_AI_MARKUP,tp as DEFAULT_CRUD_TIMEOUT,Ke as DEFAULT_ENTITY_ACCESS,Z as DEFAULT_ERROR_MESSAGES,Er as DEFAULT_LAYOUT_PRESET,Ee as DEFAULT_STATUS,ot as DEFAULT_STATUS_OPTIONS,$p as DEFAULT_STATUS_VALUE,ve as DEFAULT_SUBSCRIPTION,ep as DEFAULT_UPLOAD_TIMEOUT,Hl as DENSITY,S as DoNotDevError,V as EDITABLE,Ta as EMAIL_ERROR_CODES,xa as EMAIL_PROVIDERS,es as EMAIL_VERIFICATION_STATUS,Se as ENTITY_HOOK_ERRORS,Us as ENVIRONMENTS,ue as ERROR_CODES,Da as ERROR_SEVERITY,Fa as ERROR_SOURCE,Pt as EntityHookError,qe as FEATURES,Gl as FEATURE_CONSENT_MATRIX,Bs as FEATURE_STATUS,Vr as FIELD_TEXT_FORMATTERS,At as FIELD_TYPES,Ge as FIREBASE_ERROR_MAP,Sr as FOOTER_MODE,Dt as GITHUB_PERMISSION_LEVELS,fr as HIDDEN_STATUSES,fd as LANGUAGE_COOKIE,xr as LAYOUT_PRESET,Ys as LIST_SCHEMA_TYPE,yt as MAX_CHECKOUT_LINE_ITEMS,vt as MAX_SHIPPING_RATE_IDS,ja as OAUTH_EVENTS,_t as OAUTH_PARTNERS,Gs as ORDER_DIRECTION,Pl as PARTNER_ICONS,Wa as PAYLOAD_EVENTS,We as PERMISSIONS,_s as PLATFORMS,qs as PWA_ASSET_TYPES,js as PWA_DISPLAY_MODES,lr as ProductDeclarationSchema,ks as ProductDeclarationsSchema,mf as ProxiedImageUrlSchema,He as REMOVED_STATUS,Ws as ROUTE_SOURCES,no as SESSION_RENDER_SEGMENT,U as STATUS_MATRIX,$s as STORAGE_SCOPES,Vs as STORAGE_TYPES,Ha as STRIPE_EVENTS,be as STRIPE_MODES,cs as SUBSCRIPTION_DURATIONS,he as SUBSCRIPTION_STATUS,tr as SUBSCRIPTION_TIERS,gr as SendEmailRequestSchema,yr as SendEmailResponseSchema,de as SingletonManager,mr as StripeBackConfigSchema,ur as StripeFrontConfigSchema,pr as StripeOrderBackSchema,dr as StripeOrderShippingSchema,cr as StripeOrderTaxSchema,sr as StripePaymentSchema,ar as StripeSubscriptionSchema,_ as SubscriptionClaimsSchema,St as SubscriptionDataSchema,fo as TECHNICAL_FIELD_NAMES,tt as TRANSLATABLE_FIELD_TYPES,w as USER_ROLES,ft as UserSubscriptionSchema,Hs as VISIBILITY,or as VerifyOrderCheckoutRequestSchema,ir as VerifyOrderCheckoutResultSchema,xt as WebhookEventSchema,fi as assertWrite,C as baseFields,Pc as buildProductJsonLd,Vt as captureErrorToSentry,Sl as checkGitHubAccessSchema,Zc as clearGlobalSingleton,Vm as clearScopeProviders,Te as commonErrorCodeMappings,jt as compactToISOString,sd as configureProviders,td as createAsyncSingleton,er as createDefaultSubscriptionClaims,ns as createDefaultUserProfile,sa as createEntitySchema,M as createErrorHandler,mc as createMetadata,nd as createMethodProxy,Pm as createSchemas,Jc as createSingleton,ed as createSingletonWithParams,Vn as createStatus,Sm as defineEntity,ua as deleteEntitySchema,Oc as deriveEntitySeo,Ne as describeEntity,Yo as describeField,Wm as detectBulkCollisions,Mt as detectErrorSource,Rl as disconnectOAuthSchema,Tu as enhanceSchema,rc as ensureSpreadable,ee as evaluateCondition,Kd as evaluateFieldConditions,xl as exchangeTokenSchema,Id as filterVisibleFields,Re as formatCurrency,Br as formatDate,Xt as formatFieldText,Tc as formatRelativeTime,eo as generateCodeChallenge,Jr as generateCodeVerifier,Fc as generateFirestoreRuleCondition,Mc as generatePKCEPair,Zd as generateUUID,br as getBreakpointFromWidth,sl as getBreakpointUtils,pm as getCollectionName,Gd as getConditionDependencies,kl as getConnectionsSchema,Mr as getCurrencyLocale,gc as getCurrencySymbol,bc as getCurrentTimestamp,Qo as getEntityByCollection,aa as getEntitySchema,Ie as getGlobalSingleton,Oe as getListCardFieldNames,ad as getProvider,Bm as getRegisteredScopeProviders,Gc as getRoleFromClaims,H as getSchemaType,Mm as getScopeValue,dd as getTranslatedFieldNames,un as getVisibleFields,xc as getWeekFromISOString,gf as getWidget,Tr as githubPermissionSchema,ze as githubRepoConfigSchema,bl as grantGitHubAccessSchema,k as handleError,Xo as hasMetadata,ld as hasProvider,Pd as hasRestrictedVisibility,K as hasRoleAccess,Lm as hasScopeProvider,Xc as hasTierAccess,hi as hiddenStatusesFor,pe as i18nFieldName,_l as isAuthPartnerId,mn as isBackendGeneratedField,il as isBreakpoint,qt as isCompactDateString,Yt as isEmptyFieldValue,io as isFieldVisible,jp as isFrameworkField,nt as isMultilingual,Ul as isOAuthPartnerId,Lc as isPKCESupported,vi as isReadableBy,hc as isoToCompactString,Ed as languageUrls,Wc as lazyImport,ca as listEntitiesSchema,yf as listWidgets,ln as localizePath,J as mapToDoNotDevError,_c as maybeTranslate,vc as normalizeToISOString,qi as overrideFeatures,us as overridePaymentModes,Wi as overridePermissions,Jn as overrideSubscriptionStatus,ji as overrideSubscriptionTiers,$i as overrideUserRoles,yd as parseAcceptLanguage,Wt as parseDate,Rc as parseDateToNoonUTC,gi as prepareCreate,yi as prepareRemove,qn as prepareUpdate,bd as publicPathname,Fm as rangeOptions,gd as readCookieValue,Tl as refreshTokenSchema,_m as registerScopeProvider,Jp as registerUniqueConstraintValidator,ff as registerWidget,ud as resetProviders,lt as resolveFieldValue,sn as resolveLanguage,Sd as resolveLanguageRoute,ao as resolveUserSubscription,El as revokeGitHubAccessSchema,nc as safeValidate,Xd as sanitizeHref,Vu as showNotification,an as splitLanguagePath,Ue as statusCan,D as statusOf,Le as statusReadableBy,ct as statusesThat,et as stripHtmlTags,Sc as timestampToISOString,kc as toDateOnly,Ec as toISOString,lc as translateArray,cc as translateArrayRange,dc as translateArrayWithIndices,Ze as translateEntityLabel,uc as translateObjectArray,pd as translateRow,Um as unregisterScopeProvider,jn as updateCheck,la as updateEntitySchema,Td as updateMetadata,$n as updateNeedsStored,Ni as validateAIChatRequest,_i as validateAIChatResponse,Fl as validateAuthPartners,Zi as validateAuthSchemas,zi as validateAuthUser,Is as validateBillingSchemas,hf as validateBlock,qm as validateBulkOutcome,Rs as validateCheckoutSessionMetadata,Vc as validateCodeChallenge,Bc as validateCodeVerifier,Es as validateCreateCheckoutSessionRequest,Ss as validateCreateCheckoutSessionResponse,Qi as validateCustomClaims,_e as validateDates,rm as validateDocument,vf as validateEvent,Nl as validateOAuthPartners,ka as validateSendEmailRequest,Aa as validateSendEmailResponse,Cs as validateStripeBackConfig,As as validateStripeFrontConfig,nr as validateSubscriptionClaims,xs as validateSubscriptionData,Pn as validateUniqueFields,Xi as validateUserSubscription,vs as validateVerifyOrderCheckoutRequest,bs as validateVerifyOrderCheckoutResult,Ts as validateWebhookEvent,tc as validateWithSchema,Hd as when,Bu as withErrorHandling,jc as withGracefulDegradation,np as withTimeout,Zu as wrapAuthError,Xu as wrapCrudError,Qu as wrapStorageError};
1
+ var nr=Object.defineProperty;var rr=(e,t,n)=>t in e?nr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var k=(e,t,n)=>rr(e,typeof t!="symbol"?t+"":t,n);var U={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},be={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},Go={[U.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[U.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[U.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},Yo={maxTokens:4096,temperature:.7,stream:!0},zo={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_API_KEY:"invalid_api_key",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",PROVIDER_ERROR:"provider_error",TOKEN_LIMIT_EXCEEDED:"token_limit_exceeded",STREAM_INTERRUPTED:"stream_interrupted"},Xo={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},Qo=4,Zo={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}};import*as p from"valibot";var yt=p.object({role:p.picklist([be.USER,be.ASSISTANT,be.SYSTEM]),content:p.pipe(p.string(),p.minLength(1)),id:p.optional(p.string()),createdAt:p.optional(p.string())}),He=p.lazy(()=>p.object({type:p.picklist(["string","number","boolean","array","object"]),description:p.optional(p.string()),enum:p.optional(p.array(p.string())),items:p.optional(He),properties:p.optional(p.record(p.string(),He)),required:p.optional(p.array(p.string()))})),ir=p.object({description:p.pipe(p.string(),p.minLength(1)),parameters:p.object({type:p.literal("object"),properties:p.record(p.string(),He),required:p.optional(p.array(p.string()))})}),or=p.object({id:p.string(),name:p.string(),args:p.record(p.string(),p.unknown())}),sr=p.object({messages:p.pipe(p.array(yt),p.minLength(1)),provider:p.optional(p.picklist([U.ANTHROPIC,U.OPENAI,U.GOOGLE])),model:p.optional(p.string()),maxTokens:p.optional(p.pipe(p.number(),p.integer(),p.minValue(1))),temperature:p.optional(p.pipe(p.number(),p.minValue(0),p.maxValue(2))),systemPrompt:p.optional(p.string()),stream:p.optional(p.boolean()),tools:p.optional(p.record(p.string(),ir))}),ar=p.object({promptTokens:p.number(),completionTokens:p.number(),totalTokens:p.number()}),lr=p.object({message:yt,usage:p.optional(ar),finishReason:p.optional(p.string()),toolCalls:p.optional(p.array(or))}),ts=p.object({provider:p.picklist([U.ANTHROPIC,U.OPENAI,U.GOOGLE]),model:p.optional(p.string()),maxTokens:p.optional(p.pipe(p.number(),p.integer(),p.minValue(1))),temperature:p.optional(p.pipe(p.number(),p.minValue(0),p.maxValue(2))),systemPrompt:p.optional(p.string())});function ns(e){return p.safeParse(sr,e)}function rs(e){return p.safeParse(lr,e)}var Ee={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function ur(e){Object.assign(Ee,e)}var Se={tier:"free",status:"active",subscriptionEnd:null,updatedAt:"1970-01-01T00:00:00.000Z",isDefault:!0,subscriptionId:null,customerId:null,cancelAtPeriodEnd:!1};function cr(e){return{...Se,updatedAt:new Date().toISOString()}}var Ke={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},O={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function us(e){Object.assign(O,e)}var dr={FREE:"free",PRO:"pro",PREMIUM:"premium"};function cs(e){Object.assign(dr,e)}var Ge={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function ds(e){Object.assign(Ge,e)}var Ye={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 ps(e){Object.assign(Ye,e)}import*as u from"valibot";function ue(e){let[t,...n]=Object.values(e);if(t===void 0)throw new Error("picklistOptions: constant map has no values");return[t,...n]}var vt=u.object({id:u.string(),email:u.optional(u.nullable(u.pipe(u.string(),u.email()))),displayName:u.optional(u.nullable(u.string())),photoURL:u.optional(u.nullable(u.pipe(u.string(),u.url()))),emailVerified:u.optional(u.boolean()),lastLoginAt:u.optional(u.string()),providerData:u.optional(u.array(u.object({providerId:u.string(),uid:u.string(),email:u.optional(u.nullable(u.pipe(u.string(),u.email()))),displayName:u.optional(u.nullable(u.string())),photoURL:u.optional(u.nullable(u.pipe(u.string(),u.url()))),phoneNumber:u.optional(u.nullable(u.string()))}))),role:u.optional(u.picklist(ue(O))),customClaims:u.optional(u.record(u.string(),u.any()))}),B=u.object({tier:u.string(),status:u.string(),subscriptionEnd:u.nullable(u.pipe(u.string(),u.isoTimestamp())),updatedAt:u.pipe(u.string(),u.isoTimestamp()),isDefault:u.optional(u.boolean()),features:u.optional(u.array(u.string())),subscriptionId:u.optional(u.nullable(u.string())),customerId:u.optional(u.nullable(u.string())),cancelAtPeriodEnd:u.optional(u.boolean())}),bt=u.object({...B.entries,userId:u.string(),isActive:u.optional(u.boolean())}),Et=u.object({role:u.optional(u.picklist(ue(O))),subscription:u.optional(B),features:u.optional(u.array(u.picklist(ue(Ge)))),permissions:u.optional(u.array(u.picklist(ue(Ye)))),githubAccess:u.optional(u.object({username:u.optional(u.string()),teamAccess:u.optional(u.array(u.string())),repoAccess:u.optional(u.array(u.string()))}))});function ys(e){return u.safeParse(vt,e)}function vs(e){return u.safeParse(bt,e)}function bs(e){return u.safeParse(Et,e)}function pr(e){return u.safeParse(B,e)}function Es(){let e={authUser:u.safeParse(vt,{}),userSubscription:u.safeParse(bt,{}),customClaims:u.safeParse(Et,{}),getUserAuthStatus:u.safeParse(u.object({userId:u.pipe(u.string(),u.minLength(1))}),{}),getCustomClaims:u.safeParse(u.object({userId:u.pipe(u.string(),u.minLength(1)),claimKeys:u.optional(u.array(u.string()))}),{}),setCustomClaims:u.safeParse(u.object({userId:u.pipe(u.string(),u.minLength(1)),claims:u.record(u.string(),u.any()),merge:u.optional(u.boolean(),!1)}),{}),removeCustomClaims:u.safeParse(u.object({userId:u.pipe(u.string(),u.minLength(1)),claimKeys:u.pipe(u.array(u.string()),u.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}var xs={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},Ts={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Rs(e){return{userId:e,role:"user",preferences:{},metadata:{}}}var xe={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function Ps(e){Object.assign(xe,e)}var Ds={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};import*as o from"valibot";var St=100,mr=o.object({productId:o.pipe(o.string(),o.minLength(1),o.maxLength(200)),quantity:o.pipe(o.number(),o.integer(),o.minValue(1),o.maxValue(1e4))}),Rt=o.pipe(o.object({billingConfigKey:o.optional(o.pipe(o.string(),o.minLength(1))),lineItems:o.optional(o.pipe(o.array(mr),o.minLength(1,"At least one line item is required"),o.maxLength(St,`At most ${St} line items`))),successUrl:o.pipe(o.string(),o.url()),cancelUrl:o.pipe(o.string(),o.url()),customerEmail:o.optional(o.pipe(o.string(),o.email())),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean()),userId:o.optional(o.string()),productId:o.optional(o.string()),priceId:o.optional(o.string()),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code"))),userEmail:o.optional(o.pipe(o.string(),o.email())),mode:o.optional(o.picklist([xe.PAYMENT,xe.SUBSCRIPTION]))}),o.rawTransform(({dataset:e,addIssue:t,NEVER:n})=>{let r=e.value,i=r.billingConfigKey||r.metadata?.billingConfigKey;return i?{...r,billingConfigKey:i,lineItems:r.lineItems??[{productId:i,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),kt=o.object({sessionId:o.string(),sessionUrl:o.nullable(o.pipe(o.string(),o.url()))}),ce=o.pipe(o.string(),o.minLength(1),o.regex(/\S/)),fr=o.object({sessionId:ce,billingConfigKey:ce}),gr=o.object({sessionId:ce,orderId:ce,billingConfigKey:ce,sessionStatus:o.picklist(["open","complete","expired"]),paymentStatus:o.picklist(["paid","unpaid","no_payment_required"])});function Vs(e){return o.safeParse(fr,e)}function $s(e){return o.safeParse(gr,e)}var At=o.object({...B.entries,userId:o.string(),subscriptionId:o.nullable(o.string()),customerId:o.string(),cancelAtPeriodEnd:o.boolean()}),Ct=o.object({id:o.string(),type:o.string(),data:o.object({object:o.any()}),created:o.pipe(o.string(),o.isoTimestamp())}),It=o.looseObject({userId:o.optional(o.string()),firebaseUid:o.optional(o.string()),productType:o.optional(o.string())});function js(e){return o.safeParse(Rt,e)}function qs(e){return o.safeParse(kt,e)}function Ws(e){return o.safeParse(At,e)}function Hs(e){return o.safeParse(Ct,e)}function Ks(e){return o.safeParse(It,e)}var hr=o.object({type:o.literal("StripePayment"),name:o.pipe(o.string(),o.minLength(1,"Product name is required")),description:o.optional(o.string()),price:o.string(),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:o.optional(o.pipe(o.string(),o.minLength(1,"Stripe price ID is required"))),tier:o.pipe(o.string(),o.minLength(1,"Tier is required")),duration:o.pipe(o.string(),o.minLength(1,"Duration is required")),allowPromotionCodes:o.optional(o.boolean()),metadata:o.optional(o.record(o.string(),o.string()))}),yr=o.object({type:o.literal("StripeSubscription"),name:o.pipe(o.string(),o.minLength(1,"Product name is required")),description:o.optional(o.string()),price:o.string(),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:o.pipe(o.string(),o.minLength(1,"Stripe price ID is required")),tier:o.pipe(o.string(),o.minLength(1,"Tier is required")),duration:o.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:o.optional(o.boolean()),metadata:o.optional(o.record(o.string(),o.string()))}),vr=o.variant("type",[hr,yr]),Gs=o.record(o.string(),vr),br=o.record(o.string(),o.object({name:o.string(),price:o.string(),currency:o.string(),description:o.optional(o.string()),features:o.optional(o.array(o.string())),priceId:o.optional(o.string()),allowPromotionCodes:o.optional(o.boolean())})),xt={name:o.string(),price:o.number(),currency:o.string(),priceId:o.optional(o.string()),tier:o.string(),duration:o.string(),description:o.optional(o.string()),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean())},Er=o.variant("mode",[o.object({mode:o.literal("manual"),taxRateIds:o.pipe(o.array(o.pipe(o.string(),o.minLength(1))),o.minLength(1))}),o.object({mode:o.literal("automatic")})]),Tt=5,Sr=o.object({allowedCountries:o.pipe(o.array(o.pipe(o.string(),o.regex(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),o.minLength(1)),shippingRateIds:o.optional(o.pipe(o.array(o.pipe(o.string(),o.minLength(1))),o.maxLength(Tt,`shippingRateIds: at most ${Tt} (Stripe limit)`)))}),xr=o.object({type:o.literal("StripeOrder"),name:o.string(),currency:o.pipe(o.string(),o.length(3)),description:o.optional(o.string()),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean()),tax:Er,taxIdCollection:o.picklist(["disabled","optional","required"]),billingAddressCollection:o.picklist(["auto","required"]),shipping:o.optional(Sr),customerCreation:o.picklist(["always","if_required"]),invoiceCreation:o.boolean(),paymentMethodConfiguration:o.optional(o.pipe(o.string(),o.minLength(1)))}),Tr=o.record(o.string(),o.variant("type",[o.object({type:o.literal("StripePayment"),...xt}),o.object({type:o.literal("StripeSubscription"),...xt}),xr]));function Ys(e){return o.parse(br,e)}function zs(e){return o.parse(Tr,e)}function Xs(){let e={createCheckoutSessionRequest:o.safeParse(Rt,{}),createCheckoutSessionResponse:o.safeParse(kt,{}),subscriptionData:o.safeParse(At,{}),subscriptionClaims:o.safeParse(B,{}),webhookEvent:o.safeParse(Ct,{}),checkoutSessionMetadata:o.safeParse(It,{})};return{success:Object.values(e).every(t=>t.success),results:e}}var ra={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},ia={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},oa={CLIENT:"client",SERVER:"server",BUILD:"build"},sa={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},aa={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},la={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},ua={USER:"user",GLOBAL:"global",SESSION:"session"},ca={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},da={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},pa={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var fa={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},q={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"},ze={create:"admin",read:"guest",update:"admin",delete:"admin"},V={draft:{read:"admin",saveIncomplete:!0,holdIncomplete:!0,isDefault:!1,isRemoved:!1},available:{read:"guest",saveIncomplete:!1,holdIncomplete:!1,isDefault:!0,isRemoved:!1},deleted:{read:"admin",saveIncomplete:!1,holdIncomplete:!0,isDefault:!1,isRemoved:!0}},wt=V.available,J=Object.keys(V);function Ot(e){let t=J.filter(n=>V[n][e]);if(t.length!==1)throw new Error(`[dndev] STATUS_MATRIX: exactly one status must have ${e}`);return t[0]}var Te=Ot("isDefault"),Xe=Ot("isRemoved"),Rr=J.filter(e=>V[e].read!=="guest"),de=["id","createdAt","updatedAt","createdById","updatedById"],K={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},ga={ASC:"asc",DESC:"desc"},ha={LIST:"list",LIST_CARD:"listCard"},Pt=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var ba={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},Ea={EQ:K.EQ,NEQ:K.NEQ,LT:K.LT,LTE:K.LTE,GT:K.GT,GTE:K.GTE};var Dt=class extends Error{constructor(n,r,i){super(n,{cause:i});k(this,"outcome");this.name="AtomicBulkError",this.outcome=r}},Ft=class extends Error{constructor(n,r){super(`BulkCollisionError: ${n.length} id(s) appear in both "${r.replace("-",'" and "')}" \u2014 ${n.join(", ")}`);k(this,"collidingIds");k(this,"where");this.name="BulkCollisionError",this.collidingIds=n,this.where=r}},Nt=class extends Error{constructor(n){super(`[dndev] bulkAcross: circular dependency: ${n.join(" \u2192 ")}`);k(this,"cycle");this.name="BulkAcrossCycleError",this.cycle=n}},_t=class extends Error{constructor(n){super(`BulkNotImplementedError: adapter "${n}" has not implemented bulk() yet`);k(this,"adapterName");this.name="BulkNotImplementedError",this.adapterName=n}};import*as h from"valibot";var Ia=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),data:h.record(h.string(),h.unknown()),idempotencyKey:h.optional(h.string())}),wa=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),Oa=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required")),data:h.record(h.string(),h.unknown()),merge:h.optional(h.boolean(),!1)}),Pa=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),id:h.pipe(h.string(),h.minLength(1,"Entity ID is required"))}),Da=h.object({collection:h.pipe(h.string(),h.minLength(1,"Collection name is required")),limit:h.optional(h.pipe(h.number(),h.minValue(1),h.maxValue(1e3)),1e3),offset:h.optional(h.pipe(h.number(),h.minValue(0)),0),orderBy:h.optional(h.string()),orderDirection:h.optional(h.picklist(["asc","desc"]),"desc"),where:h.optional(h.array(h.object({field:h.string(),operator:h.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:h.unknown()})))});var Wa={RESEND:"resend"},Ha={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_REQUEST:"invalid_request",PROVIDER_ERROR:"provider_error",TEMPLATE_NOT_FOUND:"template_not_found",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",MISSING_API_KEY:"missing_api_key"};import*as E from"valibot";var kr=E.object({templateId:E.pipe(E.string(),E.minLength(1)),to:E.pipe(E.string(),E.email()),data:E.record(E.string(),E.unknown()),locale:E.optional(E.pipe(E.string(),E.minLength(2),E.maxLength(5)),"fr"),from:E.optional(E.string()),replyTo:E.optional(E.string())}),Ar=E.object({success:E.boolean(),messageId:E.optional(E.string()),error:E.optional(E.string())});function Ga(e){return E.safeParse(kr,e)}function Ya(e){return E.safeParse(Ar,e)}var pe={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"},el={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},Re={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Qe={[pe.PERMISSION_DENIED]:{type:Re.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[pe.NOT_FOUND]:{type:Re.NOT_FOUND,message:"The requested resource was not found"},[pe.ALREADY_EXISTS]:{type:Re.ALREADY_EXISTS,message:"The resource already exists"},[pe.INVALID_ARGUMENT]:{type:Re.VALIDATION_ERROR,message:"Invalid argument provided"}},Ut=class extends Error{constructor(n,r,i){super(r);k(this,"type");k(this,"originalError");this.name="EntityHookError",this.type=n,this.originalError=i}},tl={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"};function Cr(e){return"captureStackTrace"in e&&typeof e.captureStackTrace=="function"}var R=class e extends Error{constructor(n,r=pe.INTERNAL,i){super(n);k(this,"code");k(this,"details");k(this,"source");k(this,"originalError");k(this,"context");k(this,"displayable");k(this,"userMessageProvided");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,Cr(Error)&&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 sl={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var ll={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var cl={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var pl={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var fl={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var Ze={mobile:0,tablet:768,laptop:1024,desktop:1440},Ir={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function wr(e){return e>=Ze.desktop?"desktop":e>=Ze.laptop?"laptop":e>=Ze.tablet?"tablet":"mobile"}function Cl(e,t){let n=Ir[t];return e>=n.min&&e<=n.max}function Il(e,t){let n=wr(e);return{current:n,width:e,height:t,isMobile:n==="mobile",isTablet:n==="tablet",isLaptop:n==="laptop",isDesktop:n==="desktop",isMobileOrTablet:n==="mobile"||n==="tablet",isLaptopOrDesktop:n==="laptop"||n==="desktop"}}var Or="landing",Pr="/og-image.png",Dr={FIXED:"fixed",SCROLL:"scroll"},Fr={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var Mt=["pull","push","admin","maintain","triage"];import"valibot";import*as g from"valibot";var Je=g.object({owner:g.pipe(g.string(),g.minLength(1,"Repository owner is required")),repo:g.pipe(g.string(),g.minLength(1,"Repository name is required"))}),Nr=g.picklist([...Mt]),$l=g.object({userId:g.pipe(g.string(),g.minLength(1,"User ID is required")),githubUsername:g.pipe(g.string(),g.minLength(1,"GitHub username is required")),repoConfig:Je,permission:g.optional(Nr,"push"),customClaims:g.optional(g.record(g.string(),g.any()))}),jl=g.object({userId:g.pipe(g.string(),g.minLength(1,"User ID is required")),githubUsername:g.pipe(g.string(),g.minLength(1,"GitHub username is required")),repoConfig:Je}),ql=g.object({userId:g.pipe(g.string(),g.minLength(1,"User ID is required")),githubUsername:g.pipe(g.string(),g.minLength(1,"GitHub username is required")),repoConfig:Je}),Wl=g.object({provider:g.string(),purpose:g.picklist(["authentication","api-access"]),code:g.pipe(g.string(),g.minLength(1,"Authorization code is required")),redirectUri:g.pipe(g.string(),g.url("Valid redirect URI is required")),codeVerifier:g.optional(g.string()),state:g.optional(g.string()),instance:g.optional(g.pipe(g.string(),g.url()))}),Hl=g.object({provider:g.string(),refreshToken:g.pipe(g.string(),g.minLength(1,"Refresh token is required")),redirectUri:g.pipe(g.string(),g.url("Valid redirect URI is required"))}),Kl=g.object({provider:g.string()}),Gl=g.object({userId:g.pipe(g.string(),g.minLength(1,"User ID is required"))});var Jl={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as v from"valibot";var Lt=v.object({name:v.string(),color:v.string(),icon:v.string(),customParameters:v.optional(v.record(v.string(),v.string())),button:v.object({backgroundColor:v.string(),textColor:v.string(),borderColor:v.string(),hoverBackgroundColor:v.string(),focusOutlineColor:v.string(),fontWeight:v.optional(v.string(),"500"),textKey:v.optional(v.string())})}),_r=v.object({...Lt.entries,type:v.picklist(["auth","both"]),scopes:v.optional(v.array(v.string())),firebaseProviderId:v.optional(v.string())}),ke=v.union([v.literal(""),v.pipe(v.string(),v.url())]),Ur=v.object({authUrl:ke,tokenUrl:ke,profileUrl:ke,revokeUrl:v.optional(ke)}),Mr=v.object({authentication:v.optional(v.array(v.string())),"api-access":v.array(v.string())}),Lr=v.optional(v.object({pkce:v.optional(v.boolean(),!1),codeChallengeMethod:v.optional(v.picklist(["S256","plain"]),"S256")})),Br=v.object({...Lt.entries,type:v.picklist(["oauth","both"]),scopes:Mr,endpoints:Ur,capabilities:Lr}),Bt={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},Vt={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},Vr=v.record(v.string(),_r),$r=v.record(v.string(),Br);function tu(){return v.safeParse(Vr,Bt)}function nu(){return v.safeParse($r,Vt)}function ru(e){return e in Bt}function iu(e){return e in Vt}var $t={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},fu={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},gu={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:$t.ANALYTICS},marketing:{requiresConsent:$t.MARKETING}};function Hu(e,t){return Object.assign(e,{metadata:t})}import*as oe from"valibot";import*as c from"valibot";function jt(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"}import*as Wt from"valibot";function $(e){return(t,n)=>{if(t instanceof R)return t;if(typeof t!="object"||t===null){let l=typeof t=="string"?t:e.defaultErrorMessage;return new R(n||l,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let r;e.extractErrorCode?r=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(r=t.code);let i=e.defaultErrorCode;r&&e.errorCodeMapping&&r in e.errorCodeMapping&&(i=e.errorCodeMapping[r]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),r&&e.friendlyMessageMapping&&r in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[r]),s||(s=e.defaultErrorMessage);let a;return e.processMetadata?a=e.processMetadata(t):(a={originalError:t},r&&(a.originalCode=r)),"originalError"in a||(a.originalError=t),new R(n||s,i,{details:a,source:e.errorSource})}}var Ae={"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"};var ee={"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."},jr={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"},et={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"};function qr(e){return e in et}var W={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",...Ae},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",...Ae},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(jr).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode: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()},processMetadata:e=>{let t={originalError:e};if(typeof e!="object"||e===null)return t;if("response"in e&&e.response){let n=e.response;"status"in n&&(t.statusCode=n.status),"data"in n&&(t.responseData=n.data)}else"status"in e&&(t.statusCode=e.status);return t}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:Ae,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ee.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:ee["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ee.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},Wr=e=>e instanceof Wt.ValiError?new R(ee["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):$(W.validation)(e),Hr=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&qr(e.type)){let t=et[e.type]||"unknown";return new R(e.message||ee[t],t,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&Qe[e.code]){let t=Qe[e.code];if(t){let n=et[t.type]||"unknown";return new R(t.message||ee[n],n,{details:{originalCode:e.code,originalError:e},source:"entity"})}}return $(W.entity)(e)},qt={auth:$(W.auth),oauth:$(W.oauth),api:$(W.api),firebase:$(W.firebase),ui:$(W.ui),validation:Wr,entity:Hr,unknown:$(W.unknown)};function te(e,t,n){return e instanceof R?e:(qt[t]||qt.unknown)(e,n)}function Ht(e,t,n={}){let r=globalThis.Sentry;r&&r.withScope(i=>{i.setTag("errorSource",t),i.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,a])=>{if(typeof a!="function"&&s!=="originalError")try{i.setExtra(s,a)}catch{i.setExtra(s,`[${typeof a}]`)}}),Object.entries(n).forEach(([s,a])=>{if(typeof a!="function")try{i.setExtra(`context.${s}`,a)}catch{i.setExtra(`context.${s}`,`[${typeof a}]`)}}),(e.details?.userId||n.userId)&&i.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),r.captureException(e)})}function Kr(){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?(process.env.NODE_ENV||"development").toLowerCase()!=="production":!1}function A(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:r,context:i={},log:s=!0,reportToSentry:a=!0,showNotification:l=!1,severity:d="error"}=n,m=jt(e),f=e instanceof R?e:te(e,m,r);if(r&&!f.userMessageProvided&&(f.message.includes("Error")||f.message.includes("Failed")||f.message.length<10?f=new R(r,f.code,{details:{...f.details,originalMessage:f.message},source:m,userMessageProvided:!0}):f=new R(f.message,f.code,{details:{...f.details,userMessage:r},source:m,userMessageProvided:!0})),s){let S=Kr()||typeof window<"u"&&window.__DNDEV_DEBUG,P={code:f.code,message:f.message,source:m};switch(d){case"warning":break;case"info":break;case"success":break;default:}}return a&&Ht(f,m,i),f}function ac(e,t){return async(...n)=>{try{return await e(...n)}catch(r){throw A(r,t)}}}function lc(e,t="info",n){let r=Date.now().toString();return r}function vc(e,t,n,r,i){if(e instanceof R)return e;let{code:s}=te(e,"api");return new R("Request failed.",s,{source:"api",details:{context:`${t}.${n}(${r}${i?`, ${i}`:""})`,originalMessage:tt(e),originalError:e}})}function bc(e,t,n,r){let i=`${t}.${n}(${r})`;return te(e,"api",`${i}: ${tt(e)}`)}function Ec(e,t,n,r){let i=r?` ${JSON.stringify(r)}`:"",s=`${t}.${n}(${i})`,a=te(e,"auth",`${s}: ${tt(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&a.code==="unknown"&&e.code!=="unknown"?new R(a.message,a.code,{details:{...a.details,originalCode:e.code},source:a.source}):a}function tt(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}import*as me from"valibot";function Tc(e,t,n){try{return me.parse(e,t)}catch(r){throw r instanceof me.ValiError?new R(`Validation failed in ${n}: ${r.message}`,"validation-failed",{details:{issues:r.issues,input:t},source:"validation"}):new R(`Unexpected validation error in ${n}: ${Gr(r)}`,"validation-failed",{originalError:r instanceof Error?r:new Error(String(r)),source:"validation"})}}function Rc(e,t){try{return me.parse(e,t)}catch{return null}}function kc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Gr(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function Kt(e,t,n,r={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:a}=r;return Array.from({length:n},(l,d)=>{let m=`${t}.${d}`;return e(m)}).filter((l,d)=>{let m=`${t}.${d}`;return!(l===m||s&&l.trim()===""||l.length<i||a&&!a(l,d))})}function Oc(e,t,n,r){return Array.from({length:n},(i,s)=>{let a=`${t}.${s}.${String(r[0])}`;if(e(a)===a)return null;let d={};for(let m of r){let f=`${t}.${s}.${String(m)}`;d[m]=e(f)}return d}).filter(i=>i!==null)}function Pc(e,t,n,r,i={}){let{minLength:s=0,excludeEmpty:a=!0,customFilter:l}=i;return Array.from({length:r-n},(d,m)=>{let f=n+m,S=`${t}.${f}`;return e(S)}).filter((d,m)=>{let f=n+m,S=`${t}.${f}`;return!(d===S||a&&d.trim()===""||d.length<s||l&&!l(d,f))})}function Dc(e,t,n,r={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:a}=r;return Array.from({length:n},(l,d)=>{let m=`${t}.${d}`;return{item:e(m),originalIndex:d}}).filter(({item:l,originalIndex:d})=>{let m=`${t}.${d}`;return!(l===m||s&&l.trim()===""||l.length<i||a&&!a(l,d))})}var Yr=/^---\r?\n([\s\S]*?)\r?\n---/,zr=/^\r?\n/;function Nc(e){let t=e.match(Yr);if(!t)return{meta:{},content:e};let n={};for(let r of(t[1]??"").split(`
2
+ `)){let i=r.indexOf(":");if(i===-1)continue;let s=r.slice(0,i).trim();if(!s)continue;let a=r.slice(i+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n[s]=a}return{meta:n,content:e.slice(t[0].length).replace(zr,"")}}function Uc(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}var Gt={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function Xr(e){return Gt[e]?.locale??"en-US"}function Lc(e){return!e||typeof e!="string"?e??"":Gt[e]?.symbol??e}function Ce(e,t,n={}){if(e==null||isNaN(e))return"";let r=Xr(t);return new Intl.NumberFormat(r,{style:"currency",currency:t,minimumFractionDigits:0,maximumFractionDigits:2,currencyDisplay:"symbol",...n}).format(e)}function Yt(e){let t=e.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!t||t.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${e}`);let n=t[1],r=t[2],i=t[3],s=t[4],a=t[5],l=new Date(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(s,10),parseInt(a,10));if(isNaN(l.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return l.toISOString()}function Vc(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let n=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0"),s=String(t.getUTCHours()).padStart(2,"0"),a=String(t.getUTCMinutes()).padStart(2,"0");return`${n}${r}${i}:${s}${a}`}function zt(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function $c(e){if(!e)return new Date().toISOString();if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return e.toISOString()}if(typeof e=="string"){if(zt(e))return Yt(e);let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string: ${e}`);return t.toISOString()}if(typeof e=="number"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp: ${e}`);return t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();throw new Error(`Unsupported date type: ${typeof e}`)}function jc(){return new Date().toISOString()}function qc(e){return e.toISOString()}function Wc(e){return new Date(e).toISOString()}function Hc(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let n=new Date(t.getFullYear(),0,1),r=Math.floor((t.getTime()-n.getTime())/(1440*60*1e3));return`Week ${Math.ceil((r+n.getDay()+1)/7)}, ${t.getFullYear()}`}var D={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function Kc(e,t="en",n={}){if(!e)return"";let{style:r="long",numeric:i="auto",fallbackThreshold:s=D.WEEK}=n,a;if(e instanceof Date)a=e;else if(typeof e=="string")a=new Date(e);else if(typeof e=="number")a=new Date(e);else if(typeof e=="object"&&"toDate"in e)a=e.toDate();else return"";if(isNaN(a.getTime()))return"";let l=new Date,d=a.getTime()-l.getTime(),m=Math.round(d/1e3),f=Math.abs(m);if(f>s)return Zr(a.toISOString(),t);let S=new Intl.RelativeTimeFormat(t,{style:r,numeric:i});return f<D.MINUTE?S.format(m,"second"):f<D.HOUR?S.format(Math.round(m/D.MINUTE),"minute"):f<D.DAY?S.format(Math.round(m/D.HOUR),"hour"):f<D.WEEK?S.format(Math.round(m/D.DAY),"day"):f<D.MONTH?S.format(Math.round(m/D.WEEK),"week"):f<D.YEAR?S.format(Math.round(m/D.MONTH),"month"):S.format(Math.round(m/D.YEAR),"year")}function Qr(e){switch(e){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function Zr(e,t="en",n="long"){if(!e)return"";let r;if(e instanceof Date)r=e;else if(typeof e=="string")r=new Date(e);else if(typeof e=="number")r=new Date(e);else if(typeof e=="object"&&"toDate"in e)r=e.toDate();else return"";if(isNaN(r.getTime()))return"";let i=typeof n=="string"?Qr(n):n;return new Intl.DateTimeFormat(t,i).format(r)}function Xt(e){if(e!=null){if(e instanceof Date)return isNaN(e.getTime())?void 0:e.toISOString();if(typeof e=="string"){let t=e.trim();if(!t)return;if(zt(t))try{return Yt(t)}catch{return}let n=new Date(t);return isNaN(n.getTime())?void 0:n.toISOString()}if(typeof e=="number"){if(!Number.isFinite(e))return;let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")try{let t=e.toDate();return isNaN(t.getTime())?void 0:t.toISOString()}catch{return}if(typeof e=="object"&&e!==null&&"seconds"in e&&typeof e.seconds=="number"){let t=e,n=t.seconds*1e3+(t.nanoseconds||0)/1e6,r=new Date(n);return isNaN(r.getTime())?void 0:r.toISOString()}}}function Gc(e){let t=Xt(e);if(!t)return;let n=new Date(t);return n.setUTCHours(12,0,0,0),n.toISOString()}function Yc(e){let t=Xt(e);return t&&t.split("T")[0]||""}function en(e){return e==null||e===""}function nt(e,t){if(!e.includes(":"))return t(e);let[n,r=e]=e.split(":");if(r.startsWith("status.")){let i=t(r);if(i!==r&&i!==`${n}:${r}`)return i}return t(r,{ns:n})}function it(e){return e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function tn(e){let t=e.validation?.options;return Array.isArray(t)?t:void 0}function Ie(e,t,n){let r=tn(t)?.find(i=>i.value===e)?.label;return r?nt(r,n):String(e)}function rt(e){return e instanceof Date?e:new Date(e)}var Qt=(e,t,n,{locale:r})=>rt(e).toLocaleString(r),M=e=>String(e),Zt=e=>e?"Yes":"No",Jt=(e,t,n,{locale:r})=>typeof e=="number"?e.toLocaleString(r):String(e),Jr={timestamp:Qt,"datetime-local":Qt,date:(e,t,n,{locale:r})=>rt(e).toLocaleDateString(r),time:(e,t,n,{locale:r})=>rt(e).toLocaleTimeString(r),week:M,month:M,boolean:Zt,checkbox:Zt,switch:(e,t,n)=>{let r=t.options?.fieldSpecific;if(r){let i=r.uncheckedValue??!1,s=r.checkedValue??!0;if(e===s&&r.checkedLabel)return nt(r.checkedLabel,n);if(e===i&&r.uncheckedLabel)return nt(r.uncheckedLabel,n)}return e?"Yes":"No"},year:M,number:Jt,range:Jt,currency:(e,t)=>{if(Number.isNaN(Number(e)))return"";let n=t.options?.fieldSpecific;return Ce(Number(e),n?.currency||"EUR")},price:(e,t,n)=>{let r=typeof e=="number"?{amount:e,currency:"EUR",vatIncluded:!0,discountPercent:0}:e;if(!r||typeof r!="object")return"";let i=r.amount;if(en(i)||Number.isNaN(Number(i)))return"";let s=r.currency||"EUR",a=r.discountPercent??0,l=r.vatIncluded??!0?` ${n("crud:price.vatIncluded",{defaultValue:"VAT Incl."})}`:"";if(a>0){let d=Number(i)*(1-a/100),m=` ${n("crud:price.discountPercent",{percent:Math.round(a),defaultValue:"-{{percent}}%"})}`;return`${Ce(d,s)}${l}${m}`}return`${Ce(Number(i),s)}${l}`},duration:(e,t,n)=>{let r=typeof e=="number"?e:parseInt(String(e),10);if(Number.isNaN(r))return"";if(r===0)return n("crud:duration.zero",{defaultValue:"\u2014"});if(r<60)return n("crud:duration.minutes",{count:r,defaultValue:`${r} min`});let i=Math.floor(r/60),s=r%60;return n("crud:duration.hoursMinutes",{hours:i,minutes:s,defaultValue:s===0?`${i}h`:`${i}h ${s}min`})},gdprConsent:(e,t,n,{locale:r})=>{if(!e||typeof e!="object")return"";let i=e;if(i.gdprConsent!==!0)return n("crud:gdprConsent.display.no",{defaultValue:"Not consented"});let s=[n("crud:gdprConsent.display.yes",{defaultValue:"Consented"})];return i.gdprConsentDate&&s.push(new Date(i.gdprConsentDate).toLocaleDateString(r)),i.gdprConsentVersion&&s.push(`v${i.gdprConsentVersion}`),s.join(" \xB7 ")},select:Ie,radio:Ie,combobox:Ie,multiselect:(e,t,n)=>Array.isArray(e)&&tn(t)?e.map(r=>Ie(r,t,n)).join(", "):String(e),reference:e=>{if(e&&typeof e=="object"){let t=e;return String(t.displayName||t.name||t.id||e)}return String(e)},geopoint:e=>{if(e&&typeof e=="object"&&"lat"in e&&"lng"in e){let{lat:t,lng:n}=e;return`${t.toFixed(6)}, ${n.toFixed(6)}`}return""},address:e=>e&&typeof e=="object"&&"formatted_address"in e?String(e.formatted_address):String(e),array:e=>Array.isArray(e)?e.join(", "):"","field-array":(e,t)=>{if(!Array.isArray(e))return"";let n=t.options?.fieldSpecific?.fields;return e.map(r=>{if(typeof r!="object"||r==null)return"";let i=r;return(n?n.map(a=>a.name):Object.keys(i)).map(a=>i[a]).filter(a=>a!=null&&a!=="").map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" \xB7 ")}).filter(Boolean).join(", ")},password:()=>"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",text:M,textarea:M,email:M,tel:M,url:M,color:M,iban:M,richtext:e=>it(String(e))};function nn(e,t,n,r={}){let i=t.options?.displayValue;if(i&&r.item)return i(e,r.item,n);if(en(e))return null;let s=r.formatter??Jr[t.type],a=s?s(e,t,n,{locale:r.locale}):typeof e=="object"?null:String(e);if(a===null||a==="")return null;let l=t.options?.displayKey;if(!l)return a;let d=(Array.isArray(l)?l:[l]).map(m=>m.replace("{{value}}",a));return n(d,{value:a})}var ei=160,rn="EUR",ti=new Set(["textarea","richtext"]),sn=new Set(["image","images"]),ni=new Set(["price","currency"]),ri=" \xB7 ",ii={available:"InStock"};function G(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function oi(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(" ");return`${(r>t/2?n.slice(0,r):n).trimEnd()}\u2026`}function on(e){return(Array.isArray(e)?e:[e]).map(n=>{if(typeof n=="string")return G(n);if(n&&typeof n=="object"&&"fullUrl"in n)return G(n.fullUrl)}).filter(n=>n!==void 0)}function an(e){let t=e.listCardFields,n=t?Array.isArray(t)?t:[...t.title??[],...t.subtitle??[],...t.content??[],...t.footer??[]]:[];return[...new Set([...n,...Object.keys(e.fields)])]}function we(e,t,n,r){return n.flatMap(i=>{let s=e.fields[i];if(!s||sn.has(s.type))return[];let a=nn(t[i],s,r.t,{item:t,locale:r.locale});return a?[a]:[]})}function si(e,t,n){let r=e.seo?.title;if(r)return G(r(t,n.t));let i=e.listCardFields;if(i&&!Array.isArray(i)&&i.title?.length){let a=we(e,t,i.title,n);return a.length>0?a.join(i.titleSeparator??" "):void 0}let s=an(e).find(a=>e.fields[a]?.type==="text");return s?G(we(e,t,[s],n)[0]):void 0}function ai(e,t,n,r){let i=e.seo?.description;if(i)return G(i(t,r.t));let s=n.find(m=>ti.has(e.fields[m]?.type??"")&&G(t[m])!==void 0);if(s)return it(String(t[s]));let a=e.listCardFields;if(!a||Array.isArray(a))return;let d=[we(e,t,a.subtitle??[],r).join(" "),...we(e,t,a.content??[],r)].filter(Boolean);return d.length>0?d.join(ri):void 0}function li(e,t){if(typeof t.status!="string")return;let r={...ii,...e.seo?.availability}[t.status];return r?`https://schema.org/${r}`:void 0}function ui(e,t){if(e.type==="price"&&t&&typeof t=="object"){let{amount:i,currency:s}=t;return typeof i=="number"&&i>0?{amount:i,currency:G(s)??rn}:void 0}let n=typeof t=="string"?Number(t):t;if(typeof n!="number"||!(n>0))return;let r=e.options?.fieldSpecific;return{amount:n,currency:r?.currency??rn}}function Jc(e,t,n){let r=an(e),i=f=>e.fields[f],s=ai(e,t,r,n),a=s?oi(s,ei):void 0,l=r.find(f=>sn.has(i(f)?.type??"")&&on(t[f]).length>0),d=l?on(t[l]):[],m;for(let f of r){let S=i(f);if(!(!S||!ni.has(S.type))&&(m=ui(S,t[f]),m))break}return{title:si(e,t,n),description:a||void 0,image:d[0],images:d,price:m,availability:li(e,t)}}function ed(e,t){return e.title?{"@context":"https://schema.org","@type":"Product",name:e.title,...e.description&&{description:e.description},...e.images.length>0&&{image:e.images},url:t,...e.price&&{offers:{"@type":"Offer",price:e.price.amount,priceCurrency:e.price.currency,...e.availability&&{availability:e.availability},url:t}}}:null}function ci(e){return typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:typeof e=="boolean"?e?"true":"false":String(e)}function di(e){let t=`resource.data.${e.field}`,n=ci(e.value);return`${t} ${e.op} ${n}`}function nd(e){let t=[];if(e.publicCondition&&e.publicCondition.length>0){let n=e.publicCondition.map(di).join(" && ");t.push(`(${n})`)}for(let n of e.ownerFields)t.push(`request.auth.uid == resource.data.${n}`);return t.length===0?"false":t.join(" || ")}function id(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}var ad="dndev-prerendered-head",pi="/logo.svg";function mi(e){return JSON.stringify(e).replace(/</g,"\\u003c")}var x=(e,t,n)=>({tag:"meta",attributes:{[e]:t,content:n}}),ot=e=>({tag:"script",attributes:{type:"application/ld+json"},text:mi(e)});function ld(e,t,n,r){let i=e.split("/").filter(Boolean),s=[{"@type":"ListItem",position:1,name:t,item:n("/")}],a="";return i.forEach((l,d)=>{a+=`/${l}`;let m=d===i.length-1;s.push({"@type":"ListItem",position:d+2,name:m&&r?r:l.split("-").map(f=>f.charAt(0).toUpperCase()+f.slice(1)).join(" "),item:n(a)})}),{"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s}}function ud(e){let{title:t,description:n,image:r,type:i,jsonLd:s,breadcrumb:a}=e,l=[{tag:"title",attributes:{},text:t}];return n&&l.push(x("name","description",n)),l.push(x("property","og:title",t)),n&&l.push(x("property","og:description",n)),l.push(x("property","og:type",i)),r&&l.push(x("property","og:image",r)),r&&l.push(x("name","twitter:card","summary_large_image")),l.push(x("name","twitter:title",t)),n&&l.push(x("name","twitter:description",n)),r&&l.push(x("name","twitter:image",r)),s&&l.push(ot(s)),a&&l.push(ot(a)),l}function cd(e){let t=[];if(e.url&&(t.push({tag:"link",attributes:{rel:"canonical",href:e.url}}),t.push(x("property","og:url",e.url))),t.push(x("property","og:site_name",e.siteName)),e.alternates){for(let[r,i]of Object.entries(e.alternates))t.push({tag:"link",attributes:{rel:"alternate",hreflang:r,href:i}});let n=e.alternates[e.defaultLanguage];n&&t.push({tag:"link",attributes:{rel:"alternate",hreflang:"x-default",href:n}})}return t}var fi=20,ln={defaultValue:""};function un(e,t,n){if(e!==null)return e!==void 0?e:n(t,ln)||void 0}function cn(e,t){let n=(s=>e(s,ln)),r=s=>n(`${t}:meta.${s}`)||void 0,i=Kt(n,`${t}:meta.keywords`,fi);return{fullTitle:r("fullTitle"),image:r("image"),type:r("type"),keywords:i.length>0?i:void 0,author:r("author")}}function gi(e,t){return e===!0?"noindex, nofollow":e===!1?null:t?"noindex":null}function hi(e){let{meta:t,ns:n,defaultNs:r,t:i,siteName:s}=e,a=t.seo;if(!n&&!r)return{title:a?.fullTitle||s};let l=n?un(a?.title,`${n}:title`,i):a?.title??void 0;return{title:a?.fullTitle||(n?cn(i,n).fullTitle:void 0)||(l?`${l} | ${s}`:s),...l&&{pageTitle:l}}}function dd(e){let{meta:t,ns:n,defaultNs:r,t:i,siteName:s,baseUrl:a,url:l,defaultImage:d}=e,m=t.seo,f=n??r,S=f?cn(i,f):null,{title:P}=hi({meta:t,ns:n,defaultNs:r,t:i,siteName:s}),_=f?un(m?.description,`${f}:description`,i):void 0,T=m?.image||S?.image||d||void 0,L=m?.keywords||S?.keywords,ve=t.author||S?.author;return{title:P,..._&&{description:_},...T&&{image:T.startsWith("http")?T:`${a}${T}`},url:l,type:m?.type||S?.type||"website",robots:gi(m?.noindex??t.noindex,e.authOnly),...L&&{keywords:L},...ve&&{author:ve},...t.publishDate&&{publishDate:t.publishDate},...t.modifiedDate&&{modifiedDate:t.modifiedDate}}}function pd(e,t){let{title:n,description:r,image:i,type:s,keywords:a,author:l}=e,d=[{tag:"title",attributes:{},text:n}];return r&&d.push(x("name","description",r)),a&&d.push(x("name","keywords",a.join(", "))),l&&d.push(x("name","author",l)),e.robots&&d.push(x("name","robots",e.robots)),d.push(x("property","og:title",n)),r&&d.push(x("property","og:description",r)),d.push(x("property","og:type",s)),i&&(d.push(x("property","og:image",i)),d.push(x("property","og:image:width","1200")),d.push(x("property","og:image:height","630"))),s==="article"&&(l&&d.push(x("property","article:author",l)),e.publishDate&&d.push(x("property","article:published_time",e.publishDate)),e.modifiedDate&&d.push(x("property","article:modified_time",e.modifiedDate))),d.push(x("name","twitter:card","summary_large_image")),d.push(x("name","twitter:title",n)),r&&d.push(x("name","twitter:description",r)),i&&d.push(x("name","twitter:image",i)),l&&d.push(x("name","twitter:creator",l)),i?.startsWith("http")&&d.push({tag:"link",attributes:{rel:"dns-prefetch",href:new URL(i).origin}}),e.url&&d.push(ot({"@context":"https://schema.org","@type":s==="article"?"Article":"WebPage",name:n,...r&&{description:r},url:e.url,...i&&{image:i},...s==="article"&&{...l&&{author:{"@type":"Person",name:l}},...e.publishDate&&{datePublished:e.publishDate},...e.modifiedDate&&{dateModified:e.modifiedDate}},publisher:{"@type":"Organization",name:t.siteName,logo:{"@type":"ImageObject",url:`${t.baseUrl}${pi}`}}})),d}var md={enabled:!0,themeColor:"#2563eb",backgroundColor:"#ffffff",includeManifestIcons:!0,includeMSIcons:!1};function fd(e){let t=n=>e(n)?n:void 0;return{svg:t("/favicon.svg"),ico:t("/favicon.ico"),png16:t("/favicon-16x16.png"),png32:t("/favicon-32x32.png"),apple180:t("/apple-touch-icon.png"),android192:t("/icon-192x192.png"),android512:t("/icon-512x512.png")}}var ne=(e,t,n)=>({tag:"link",attributes:{rel:"icon",type:t,...n&&{sizes:n},href:e}});function gd(e,t){let{enabled:n,appName:r,themeColor:i,includeManifestIcons:s,includeMSIcons:a}=t;if(n===!1)return[];let l=[];return e.svg&&l.push(ne(e.svg,"image/svg+xml")),e.ico&&l.push(ne(e.ico,"image/x-icon")),e.png16&&l.push(ne(e.png16,"image/png","16x16")),e.png32&&l.push(ne(e.png32,"image/png","32x32")),e.apple180&&(l.push({tag:"link",attributes:{rel:"apple-touch-icon",sizes:"180x180",href:e.apple180}}),r&&l.push(x("name","apple-mobile-web-app-title",r))),s&&(e.android192&&l.push(ne(e.android192,"image/png","192x192")),e.android512&&l.push(ne(e.android512,"image/png","512x512"))),a&&e.png32&&(l.push(x("name","msapplication-TileImage",e.png32)),i&&l.push(x("name","msapplication-TileColor",i))),i&&l.push(x("name","theme-color",i)),l.push(x("name","color-scheme","light dark")),l}var hd="dndev-fonts";function yd(e){return e.map(t=>({tag:"link",attributes:{rel:"preload",as:"font",type:"font/woff2",href:t,crossorigin:"anonymous"}}))}function yi(){let e=new Uint8Array(32);return crypto.getRandomValues(e),dn(e)}async function vi(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return dn(new Uint8Array(r))}async function bd(){let e=yi(),t=await vi(e);return{codeVerifier:e,codeChallenge:t}}function dn(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ed(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function Sd(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function xd(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}async function Rd(e,t,n){try{return await e()}catch{return t(),!1}}var Oe=new Map;function Ad(e,t){if(Oe.has(t))return Oe.get(t);let n=e().catch(r=>{throw Oe.delete(t),r});return Oe.set(t,n),n}var pn={[O.GUEST]:0,[O.USER]:1,[O.ADMIN]:2,[O.SUPER]:3};function Y(e,t){if(!e)return!1;let n=pn[e]??-1,r=pn[t]??1/0;return n>=r}function wd(e){return e?e.role===O.SUPER||e.isSuper===!0?O.SUPER:e.role===O.ADMIN||e.isAdmin===!0?O.ADMIN:e.role===O.USER?O.USER:e.role||O.USER:O.USER}function Dd(e,t,n){if(!e)return!1;let r=n??Ke,i=r[e]?.level??-1,s=r[t]?.level??1/0;return i>=s}var mn="__DNDEV_SINGLETONS__";function fn(){if(typeof globalThis<"u"){let e=globalThis,t=e[mn];if(t)return t;let n=new Map;return e[mn]=n,n}return new Map}function Pe(e,t){let n=fn();return n.has(e)||n.set(e,t()),n.get(e)}function Nd(e){fn().delete(e)}function _d(e,...t){let n=null,r=!1;return function(){if(n!==null)return n;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{r=!1}}}function Ud(e){let t=null,n=!1;return function(...i){if(t!==null)return t;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof e=="function"&&e.prototype?t=new e(...i):t=e(...i),t}finally{n=!1}}}function Md(e){let t=null,n=!1,r=null;return async function(){if(t!==null)return t;if(n&&r)return r;if(n)throw new Error("Circular dependency detected in async singleton initialization");n=!0;try{return r=e(),t=await r,t}finally{n=!1,r=null}}}function Ld(e,t){return new Proxy({},{get(n,r){if(t.includes(r)){let s=e(),a=s[r];return typeof a=="function"?a.bind(s):a}return e()[r]}})}var fe=class{static async getOrCreate(t,n,r={}){if(this.instances.has(t))return this.instances.get(t);if(this.initialized.has(t))return this.instances.get(t);if(this.initializing.has(t))throw new Error(`Circular dependency detected for singleton: ${t}`);if(r.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u"&&process.env.NODE_ENV,r.fallbackFactory){let i=r.fallbackFactory();return this.instances.set(t,i),this.initialized.add(t),i}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let i=await n();return this.instances.set(t,i),this.initialized.add(t),i}catch(i){if(typeof process<"u"&&process.env.NODE_ENV,r.cacheFailures&&this.initialized.add(t),r.fallbackFactory){let s=r.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw i}finally{this.initializing.delete(t)}}static isInitialized(t){return this.initialized.has(t)}static clear(t){this.instances.delete(t),this.initialized.delete(t),this.initializing.delete(t)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};k(fe,"instances",new Map),k(fe,"initializing",new Set),k(fe,"initialized",new Set);function De(){return Pe("providers",()=>({providers:null}))}function jd(e){let t=De();t.providers,t.providers=e}function qd(e){let{providers:t}=De();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let n=t[e];if(!n)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return n}function Wd(e){return!!De().providers?.[e]}function Hd(){De().providers=null}var st=["text","textarea","richtext","field-array"];function ge(e){return`${e}I18n`}function Gd(e){return Object.keys(e).filter(t=>e[t]?.i18n===!0)}function bi(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function Yd(e,t,n){let r=null;for(let i of t){let s=e[ge(i)];if(!s||typeof s!="object")continue;let a=s[n];bi(a)&&(r??(r={...e}),r[i]=a)}return r??e}var Xd="dndev-lang";function Qd(e,t){if(!e)return null;for(let n of e.split(";")){let r=n.indexOf("=");if(r!==-1&&n.slice(0,r).trim()===t)try{return decodeURIComponent(n.slice(r+1).trim())}catch{return null}}return null}function Zd(e){return e?e.split(",").map((t,n)=>{let[r="",...i]=t.trim().split(";"),s=i.find(l=>l.trim().startsWith("q=")),a=s?Number(s.trim().slice(2)):1;return{tag:r.trim(),quality:Number.isFinite(a)?a:0,index:n}}).filter(t=>t.tag!==""&&t.tag!=="*"&&t.quality>0).sort((t,n)=>n.quality-t.quality||t.index-n.index).map(t=>t.tag):[]}function gn({supported:e,fallback:t,stored:n,preferred:r}){if(n&&e.includes(n))return n;for(let i of r??[]){if(e.includes(i))return i;let s=i.split("-")[0];if(s&&e.includes(s))return s}return t}function at(e){return e.length>1}var Ei="dndev-session",Si="/index";function tp(e){let t=e.split("/"),n=t.indexOf(Ei);(n===1||n===2)&&t.splice(n,1);let r=t.join("/")||"/";return r===Si?"/":r}function np(e){return e.replace(/\/+$/,"")||"/"}function xi(e,t){if(!t)return e;let n=e.search(/[?#]/),r=n===-1?e:e.slice(0,n),i=n===-1?"":e.slice(n);return r.endsWith("/")||r.slice(r.lastIndexOf("/")+1).includes(".")?e:`${r}/${i}`}function hn(e,t){let n={language:t.defaultLanguage,path:e,prefixed:!1};if(!at(t.languages))return n;let r=e.indexOf("/",1),i=r===-1?e.slice(1):e.slice(1,r);return t.languages.includes(i)?{language:i,path:r===-1?"/":e.slice(r),prefixed:!0}:n}function yn(e,t,n){if(!e.startsWith("/")||e.startsWith("//")||!at(n.languages))return e;let r=e.search(/[?#]/),i=r===-1?e:e.slice(0,r),s=r===-1?"":e.slice(r),a=hn(i,n),l=a.prefixed?a.language:t;return l===n.defaultLanguage?`${a.path}${s}`:`/${l}${a.path==="/"?"":a.path}${s}`}function Ti(e,t,n,r,i){return`${n}${xi(yn(e,t,r),i)}`}function rp(e,t,n,r){return Object.fromEntries(n.languages.map(i=>[i,Ti(e,i,t,n,r)]))}function ip(e,t,n){let r=hn(e,n);if(!at(n.languages))return{type:"pass",language:r.language,path:r.path};if(r.prefixed)return r.language===n.defaultLanguage?{type:"redirect",language:r.language,path:r.path,location:r.path,permanent:!0}:{type:"pass",language:r.language,path:r.path};let i=gn({supported:n.languages,fallback:n.defaultLanguage,stored:t.stored,preferred:t.preferred});return i!==n.defaultLanguage?{type:"redirect",language:i,path:r.path,location:yn(r.path,i,n),permanent:!1}:{type:"rewrite",language:n.defaultLanguage,path:r.path,destination:`/${n.defaultLanguage}${r.path==="/"?"":r.path}`}}var Fe=e=>e.split("/").filter(Boolean);function vn(e){return e==="*"||e.endsWith("/*")}function Ri(e){try{return decodeURIComponent(e)}catch{return e}}function bn(e,t){let n={};return e.forEach((r,i)=>{r.startsWith(":")&&t[i]!==void 0&&(n[r.slice(1)]=Ri(t[i]))}),n}function sp(e,t){let n=Fe(t),r=n.join("/"),i=e.find(l=>typeof l.path=="string"&&Fe(l.path).join("/")===r);if(i)return{route:i,params:{}};let s=null;for(let l of e){if(typeof l.path!="string"||!l.path.includes(":")||vn(l.path))continue;let d=Fe(l.path);d.length===n.length&&d.every((m,f)=>m.startsWith(":")||m===n[f])&&(!s||l.path.length>s.route.path.length)&&(s={route:l,pattern:d})}if(s)return{route:s.route,params:bn(s.pattern,n)};let a=null;for(let l of e){if(typeof l.path!="string"||!vn(l.path))continue;let d=Fe(l.path).slice(0,-1);if(n.length<d.length)continue;let m=0,f=!0;for(let P=0;P<d.length;P++){let _=d[P];if(!_.startsWith(":")){if(_!==n[P]){f=!1;break}m++}}if(!f)continue;let S=[d.length,m];(!a||S[0]>a.score[0]||S[0]===a.score[0]&&S[1]>a.score[1])&&(a={route:l,prefix:d,score:S})}return a?{route:a.route,params:bn(a.prefix,n)}:null}function lp(e){return{updatedAt:new Date().toISOString(),updatedById:e}}function ki(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function Ai(e){if(ki(e))return e.visibility}function Ci(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?Y(t,"admin"):n==="owner"?!1:Y(t,n)}function Ii(e,t,n){for(let r of n.ownerFields)if(e[r]===t)return!0;return!1}function En(e,t,n){if(!e||typeof e!="object"||!("entries"in e)||!e.entries)return[];let r=e.entries,i=[],{documentData:s,uid:a,ownership:l}=n??{},d=l&&a!=null&&s&&Ii(s,a,l);for(let[m,f]of Object.entries(r)){let S=Ai(f);if(S==="owner"){d&&i.push(m);continue}Ci(S,t)&&i.push(m)}return i}function mp(e,t,n,r){if(!e)return{};let i=r?.uid!=null&&r?.ownership!=null?{documentData:r.documentData??e,uid:r.uid,ownership:r.ownership}:void 0,s=En(t,n,i),a={};for(let l of s)Object.prototype.hasOwnProperty.call(e,l)&&(a[l]=e[l]);return a}function Ne(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,r=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(r)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}function Sn(e){return typeof e=="object"&&e!==null}function _e(e){if(Sn(e)){if(Sn(e.entries))return e.entries;if(Array.isArray(e.pipe))for(let t of e.pipe){let n=_e(t);if(n)return n}if(e.wrapped)return _e(e.wrapped);if(Array.isArray(e.options))for(let t of e.options){let n=_e(t);if(n)return n}}}function hp(e){let t=_e(e);if(!t)return!1;for(let n of Object.values(t)){let r=n?.visibility;if(r!==void 0&&r!=="guest")return!0}return!1}import*as xn from"valibot";function wi(e,t){let n=xn.parse(B,t??Se);return{...n,userId:e,isActive:n.status===Ee.ACTIVE,features:n.features??[]}}var lt=class{constructor(t={}){k(this,"store",new Map);k(this,"maxAttempts");k(this,"lockoutMs");k(this,"sessionTimeoutMs");this.maxAttempts=t.maxAttempts??5,this.lockoutMs=t.lockoutMs??900*1e3,this.sessionTimeoutMs=t.sessionTimeoutMs??480*60*1e3}checkLockout(t){let n=this.store.get(t);if(n?.lockedUntil){if(Date.now()<n.lockedUntil){let r=Math.ceil((n.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${r} minute${r===1?"":"s"}.`)}this.store.delete(t)}}recordFailure(t){let n=Date.now();!this.store.has(t)&&this.store.size>=1e4&&this._evictExpired(n);let r=this.store.get(t)??{attempts:0,lastAttempt:0,lockedUntil:null};return r.attempts+=1,r.lastAttempt=n,r.attempts>=this.maxAttempts&&(r.lockedUntil=n+this.lockoutMs),this.store.set(t,r),{attempts:r.attempts,locked:r.lockedUntil!==null&&Date.now()<r.lockedUntil,lockedUntil:r.lockedUntil}}_evictExpired(t){for(let[n,r]of this.store)r.lockedUntil!==null&&t>r.lockedUntil?this.store.delete(n):r.lockedUntil===null&&t-r.lastAttempt>this.lockoutMs&&this.store.delete(n)}recordSuccess(t){this.store.delete(t)}isSessionExpired(t){return Date.now()-t>this.sessionTimeoutMs}getEntry(t){return this.store.get(t)}};function Oi(e,t){if(t.includes(".")){let n=t.split("."),r=e;for(let i of n){if(r==null||typeof r!="object")return;r=r[i]}return r}return e[t]}function Pi(e,t){let n=Oi(t,e.field);switch(e.operator){case"equals":return n===e.value;case"notEquals":return n!==e.value;case"in":return Array.isArray(e.value)&&e.value.includes(n);case"notIn":return Array.isArray(e.value)&&!e.value.includes(n);case"greaterThan":return typeof n=="number"&&typeof e.value=="number"&&n>e.value;case"lessThan":return typeof n=="number"&&typeof e.value=="number"&&n<e.value;case"greaterThanOrEqual":return typeof n=="number"&&typeof e.value=="number"&&n>=e.value;case"lessThanOrEqual":return typeof n=="number"&&typeof e.value=="number"&&n<=e.value;case"exists":return n!=null&&n!==""&&n!==!1;case"notExists":return n==null||n===""||n===!1;case"contains":return typeof n=="string"&&typeof e.value=="string"||Array.isArray(n)?n.includes(e.value):!1;default:return!1}}function Di(e){return e instanceof he||"expression"in e?e.expression:e}function re(e,t){let n=Di(e);if(n.type==="condition")return Pi(n,t);let{logic:r,conditions:i}=n;return r==="and"?i.every(s=>re(s,t)):i.some(s=>re(s,t))}function Op(e,t){return e?{visible:e.visible?re(e.visible,t):!0,disabled:e.disabled?re(e.disabled,t):!1,required:e.required?re(e.required,t):!1,readonly:e.readonly?re(e.readonly,t):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var he=class e{constructor(t){k(this,"expression");this.expression=t}get type(){return this.expression.type}or(t){let n=t instanceof e?t.expression:t,r=this.expression;return r.type==="group"&&r.logic==="or"?new e({type:"group",logic:"or",conditions:[...r.conditions,n]}):new e({type:"group",logic:"or",conditions:[r,n]})}and(t){let n=t instanceof e?t.expression:t,r=this.expression;return r.type==="group"&&r.logic==="and"?new e({type:"group",logic:"and",conditions:[...r.conditions,n]}):new e({type:"group",logic:"and",conditions:[r,n]})}};function Pp(e){function t(n,r){return new he({type:"condition",field:e,operator:n,value:r})}return{equals:n=>t("equals",n),notEquals:n=>t("notEquals",n),in:n=>t("in",n),notIn:n=>t("notIn",n),greaterThan:n=>t("greaterThan",n),lessThan:n=>t("lessThan",n),greaterThanOrEqual:n=>t("greaterThanOrEqual",n),lessThanOrEqual:n=>t("lessThanOrEqual",n),exists:()=>t("exists"),notExists:()=>t("notExists"),contains:n=>t("contains",n)}}function Dp(e){let t=e instanceof he?e.expression:e,n=new Set;function r(i){if(i.type==="condition")n.add(i.field);else for(let s of i.conditions)r(s)}return r(t),n}var Fi=new Set(["http:","https:","mailto:","tel:","blob:"]);function _p(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(Fi.has(n.protocol))return t}catch{return t}return""}function Mp(){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Bp=3e4,Vp=15e3;function $p(e,t,n){if(n?.aborted)return Promise.reject(Tn(n.reason));let r=t>0;return!r&&!n?e:new Promise((i,s)=>{let a=!1,l;function d(){a=!0,l!==void 0&&(clearTimeout(l),l=void 0),n&&n.removeEventListener("abort",m)}function m(){a||(d(),s(Tn(n?.reason)))}n&&n.addEventListener("abort",m,{once:!0}),r&&(l=setTimeout(()=>{a||(d(),s(Ni(t)))},t)),e.then(f=>{a||(d(),i(f))},f=>{a||(d(),s(f))})})}function Ni(e){let t=new Error(`Operation timed out after ${e}ms`);return t.name="TimeoutError",t}function Tn(e){if(e instanceof Error){let n=new Error(e.message);return n.name="AbortError",n}let t=new Error(typeof e=="string"?e:"Operation was aborted");return t.name="AbortError",t}var ut=J.map(e=>({value:e,label:`crud:status.${e}`})),wm=Te;var _i=[...de,"status"];function Om(e){return _i.some(t=>t===e)}function Rn(e){return de.some(t=>t===e)}var I={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...ut]}},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:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}};var Ue=e=>{let t=[];return e.validation?.minLength!==void 0&&t.push(c.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(c.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(c.regex(new RegExp(e.validation.pattern),"Invalid format")),t.length>0?c.pipe(c.string(),...t):c.string()},Ui=()=>c.pipe(c.string(),c.email("Invalid email address")),Mi=e=>e.validation?.minLength!==void 0?c.pipe(c.string(),c.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):c.string(),Li=()=>c.pipe(c.string(),c.url("Invalid URL")),ie=e=>{let t=[];return e.validation?.min!==void 0&&t.push(c.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(c.maxValue(e.validation.max,`Must be at most ${e.validation.max}`)),t.length>0?c.pipe(c.number(),...t):c.number()},kn=()=>c.boolean(),ct=()=>c.pipe(c.string(),c.check(e=>!isNaN(new Date(e).getTime()),"Invalid date format")),Bi=/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/,Vi=/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/,$i=/^\d{4}-(?:0[1-9]|1[0-2])$/,ji=()=>c.pipe(c.string(),c.regex(Bi,"Invalid time format")),qi=()=>c.pipe(c.string(),c.regex(Vi,"Invalid week format")),Wi=()=>c.pipe(c.string(),c.regex($i,"Invalid month format")),Nn=c.object({url:c.string(),filename:c.string(),size:c.number(),mimeType:c.nullish(c.string()),uploadedAt:c.nullish(c.string())}),An=()=>Nn,Cn=()=>c.array(Nn),_n=c.object({fullUrl:c.string(),thumbUrl:c.string()}),Hi=()=>c.union([c.string(),_n]),Ki=()=>c.array(c.union([c.string(),_n])),Gi=()=>c.object({lat:c.number(),lng:c.number()}),Yi=()=>c.object({formatted_address:c.string(),latitude:c.number(),longitude:c.number(),street_number:c.nullish(c.string()),route:c.nullish(c.string()),locality:c.nullish(c.string()),administrative_area_level_1:c.nullish(c.string()),administrative_area_level_2:c.nullish(c.string()),country:c.nullish(c.string()),postal_code:c.nullish(c.string())}),zi=()=>c.record(c.string(),c.unknown()),Xi=()=>c.array(c.unknown()),Qi=()=>c.array(c.record(c.string(),c.unknown())),dt=e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?c.picklist(t.map(n=>n.value)):c.union([c.string(),c.number()])},Zi=e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?c.array(c.picklist(t.map(n=>n.value))):c.array(c.string())},Un=()=>c.pipe(c.string(),c.minLength(1,"Invalid ID format")),pt=()=>c.string(),Ji=/^(?:\+[1-9](?:[ .-]?\d){7,14}|0[1-9](?:[ .-]?\d{2}){4})$/,eo=e=>{let t=e.validation?.pattern?new RegExp(e.validation.pattern):Ji;return c.pipe(c.string(),c.regex(t,"Invalid phone number"))},to=e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,r=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$";return c.pipe(c.string(),c.minLength(t,`IBAN must be at least ${t} characters`),c.maxLength(n,`IBAN must not exceed ${n} characters`),c.regex(new RegExp(r),"Invalid IBAN format"))},In=()=>c.never();function Mn(e){let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue)return[t.checkedValue,t.uncheckedValue]}var no=e=>{let t=Mn(e);return t?c.picklist(t):c.boolean()},wn=c.looseObject({gdprConsent:c.literal(!0),gdprConsentDate:c.optional(c.string()),gdprConsentVersion:c.optional(c.string())},"GDPR consent must be given"),ro=e=>e.validation?.required?wn:c.union([c.literal(!1),wn]),io=()=>c.object({amount:c.number(),currency:c.optional(c.string()),vatIncluded:c.optional(c.boolean()),discountPercent:c.optional(c.pipe(c.number(),c.minValue(0),c.maxValue(100)))}),Ln={text:{schema:Ue,kind:"text"},textarea:{schema:Ue,kind:"text"},richtext:{schema:Ue,kind:"text"},color:{schema:Ue,kind:"text"},email:{schema:Ui,kind:"text"},password:{schema:Mi,kind:"text"},url:{schema:Li,kind:"text"},tel:{schema:eo,kind:"text"},iban:{schema:to,kind:"text"},number:{schema:ie,kind:"number"},currency:{schema:ie,kind:"number"},range:{schema:ie,kind:"number"},year:{schema:ie,kind:"number"},rating:{schema:ie,kind:"number"},duration:{schema:ie,kind:"number"},price:{schema:io,kind:"json"},boolean:{schema:kn,kind:"boolean"},checkbox:{schema:kn,kind:"boolean"},switch:{schema:no,kind:e=>Mn(e)?"text":"boolean"},gdprConsent:{schema:ro,kind:"json"},date:{schema:ct,kind:"date"},"datetime-local":{schema:ct,kind:"timestamp"},timestamp:{schema:ct,kind:"timestamp"},time:{schema:ji,kind:"time"},week:{schema:qi,kind:"text"},month:{schema:Wi,kind:"text"},file:{schema:An,kind:"json"},files:{schema:Cn,kind:"json"},document:{schema:An,kind:"json"},documents:{schema:Cn,kind:"json"},image:{schema:Hi,kind:"json"},images:{schema:Ki,kind:"json"},geopoint:{schema:Gi,kind:"json"},address:{schema:Yi,kind:"json"},map:{schema:zi,kind:"json"},array:{schema:Xi,kind:"json"},"field-array":{schema:Qi,kind:"json"},select:{schema:dt,kind:"text"},radio:{schema:dt,kind:"text"},combobox:{schema:dt,kind:"text"},multiselect:{schema:Zi,kind:"json"},reference:{schema:Un,kind:"ref"},hidden:{schema:pt,kind:"text"},avatar:{schema:pt,kind:"text"},badge:{schema:pt,kind:"text"},submit:{schema:In,kind:"text"},reset:{schema:In,kind:"text"}},oo=new Set(Pt);function so(e){return oo.has(e)}var ao=new Set(["optional","exact_optional","nullable","nullish","undefinedable","non_nullable","non_nullish","non_optional"]),lo=new Set(["object","loose_object","strict_object","object_with_rest","record","array","tuple","loose_tuple","strict_tuple","tuple_with_rest","intersect"]),uo=new Set(["trim","trim_start","trim_end","to_lower_case","to_upper_case","to_min_value","to_max_value","normalize","brand","flavor","readonly"]),co={iso_date:"date",iso_time:"time",iso_time_second:"time",iso_date_time:"timestamp",iso_timestamp:"timestamp"};function j(e,t){return t in e?Reflect.get(e,t):void 0}function On(e){if(typeof e=="string")return"text";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}function Pn(e){if(e.length===0||e.some(n=>n===void 0))return;let t=new Set(e);return t.size===1?e[0]:t.has("json")?"json":void 0}function Me(e){if(typeof e!="object"||e===null)return;let t=j(e,"type");if(typeof t!="string")return;let n=po(e,t),r=j(e,"pipe");if(Array.isArray(r))for(let i of r.slice(1)){if(typeof i!="object"||i===null)continue;let s=j(i,"kind"),a=j(i,"type");if(typeof a=="string"){if(s==="schema")n=Me(i);else if(s==="transformation")uo.has(a)||(n=void 0);else if(s==="validation"){a==="integer"&&n==="number"&&(n="integer");let l=co[a];l&&n==="text"&&(n=l)}}}return n}function po(e,t){if(ao.has(t))return Me(j(e,"wrapped"));if(lo.has(t))return"json";switch(t){case"string":return"text";case"number":return"number";case"bigint":return"integer";case"boolean":return"boolean";case"date":return"timestamp";case"literal":return On(j(e,"literal"));case"picklist":case"enum":{let n=j(e,"options");return Array.isArray(n)?Pn(n.map(On)):void 0}case"union":case"variant":{let n=j(e,"options");if(!Array.isArray(n))return;let r=n.filter(i=>{let s=typeof i=="object"&&i!==null?j(i,"type"):void 0;return s!=="null"&&s!=="undefined"});return Pn(r.map(Me))}default:return}}function Dn(e,t){let{kind:n}=Ln[e];return typeof n=="function"?n(t):n}function mt(e,t=e.name){let n=e.validation?.reference,r=n?{ref:n}:{},i=e.type,s=so(i)?i:void 0,a=e.validation?.schema;if(a){let l=(n?"ref":void 0)??Me(a)??(s?Dn(s,e):void 0);if(!l)throw new Error(`Field '${t}' (custom type '${i}'): the storage kind of its validation.schema cannot be read. Root the schema on a Valibot string, number, boolean, picklist, object or array schema, or set validation.reference.`);return{schema:a,kind:l,...r}}if(n)return{schema:Un(),kind:"ref",...r};if(s)return{schema:Ln[s].schema(e),kind:Dn(s,e)};throw new Error(`Field '${t}' has custom type '${i}' and no value shape. Add validation.schema (a Valibot schema of the stored value) or validation.reference (the referenced collection) to the field, or use a built-in type.`)}function mo(e){return e.validation?.required===!0?"always":e.conditions?.required!==void 0?"conditional":"never"}function fo(e,t){return t.visibility==="hidden"||t.editable===q.GENERATED||Rn(e)?"never":t.editable===q.FALSE?"program":t.editable===q.COMPUTED?"derived":"user"}function go(e,t){return(n,r)=>{if(t!=="user")return!1;let i=e.editable;return i===void 0||i===q.TRUE?e.visibility!=="technical":i===q.CREATE_ONLY?r==="create":typeof i=="string"?Y(n,i):!1}}function ho(e,t,n){let r=fo(e,t);return{value:mt(t,`${n}.${e}`),required:mo(t),write:r,editableFor:go(t,r),visibleAt:t.visibility,...t.i18n===!0&&{companion:ge(e)}}}var Fn=new WeakMap;function Le(e){let t=Fn.get(e);if(t)return t;let n={};for(let[i,s]of Object.entries(e.fields))n[i]=ho(i,s,e.name);let r={name:e.name,collection:e.collection,fields:n};return Fn.set(e,r),r}function yo(e,t){return t?oe.pipe(e,oe.check(n=>n!=="","Required")):oe.nullish(e)}function z(e){return yo(mt(e).schema,e.validation?.required)}var Bn=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function Vn(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function $n(e){return typeof e=="object"&&e!==null}function Be(e,t=""){if(Array.isArray(e))e.forEach((n,r)=>{let i=`${t}[${r}]`;if(typeof n=="string"&&Vn(n)){if(!Bn.test(n))throw A(new Error(`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`),{userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:i,value:n},severity:"error"})}else $n(n)&&Be(n,i)});else if(typeof e=="object"&&e!==null)for(let[n,r]of Object.entries(e)){let i=t?`${t}.${n}`:n;if(typeof r=="string"&&Vn(r)){if(!Bn.test(r))throw A(new Error(`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else $n(r)&&Be(r,i)}}import*as qn from"valibot";var ft={};function $m(e){ft.uniqueConstraintValidator=e}async function jn(e,t,n){let{uniqueFields:r=[],collection:i}=e.metadata;if(r.length!==0){if(!ft.uniqueConstraintValidator){process.env.NODE_ENV;return}await Promise.all(r.map(async({field:s,errorMessage:a})=>{let l=t[s];if(l==null)return;if(await ft.uniqueConstraintValidator.checkDuplicate(i,s,l,n))throw A(new Error(a||`${s} must be unique`),{userMessage:a||`${s} must be unique`,context:{field:s}})}))}}async function Hm(e,t,n,r){qn.parse(e,t),Be(t),await jn(e,t,r),e.metadata.customValidate&&await e.metadata.customValidate(t,n)}function vo(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function ef(e){if(!vo(e)){let t=e,n=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw A(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:n}})}return e.metadata.collection}var Wn=()=>Pe("entity-registry",()=>new Map);function Hn(e){Wn().set(e.collection,e)}function bo(e){return Wn().get(e)}var Eo=new Set(["__proto__","constructor","prototype"]);function So(e){for(let t of Object.keys(e.fields))if(Eo.has(t))throw A(new Error(`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`),{userMessage:`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`,context:{entityName:e.name,fieldName:t,operation:"defineEntity"},severity:"error"})}function xo(e){let t=e.field.endsWith("Id")?e.field.slice(0,-2):e.field,n=e.collection||(t.endsWith("y")?t.slice(0,-1)+"ies":t+"s");return{name:e.field,label:`crud:fields.${e.field}`,type:"reference",visibility:"technical",editable:q.CREATE_ONLY,validation:{required:!0,reference:n}}}function To(e,t){if(!t||t.length===0)return e.map(i=>({value:i.value,label:i.label}));let n=e.map(i=>({value:i.value,label:i.label})),r=new Set(e.map(i=>i.value));for(let i of t)r.has(i.value)||n.push(i);return n}function Ro(e,t){if(!(!e.uniqueKeys||e.uniqueKeys.length===0))for(let n=0;n<e.uniqueKeys.length;n++){let r=e.uniqueKeys[n];if(!r)continue;if(!r.fields||r.fields.length===0)throw A(new Error(`uniqueKeys[${n}] for entity '${e.name}' must have at least one field`),{userMessage:`uniqueKeys[${n}] for entity '${e.name}' must have at least one field`,context:{entityName:e.name,uniqueKeyIndex:n},severity:"error"});let i=r.fields.filter(s=>!t.has(s));if(i.length>0)throw A(new Error(`uniqueKeys[${n}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${n}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:e.name,uniqueKeyIndex:n,invalidFields:i},severity:"error"})}}function ko(e){let{form:t,fields:n}=e,r=Object.keys(n);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw A(new Error(`Multi-step form for entity '${e.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${e.name}' must have at least one step`,context:{entityName:e.name,operation:"validateFormConfig"},severity:"error"});let i=t.steps.flatMap(d=>d.fields),s=i.filter(d=>!r.includes(d));if(s.length>0)throw A(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`,context:{entityName:e.name,invalidFields:s,operation:"validateFormConfig"},severity:"error"});let a=new Set(i);r.filter(d=>!a.has(d)).length>0&&process.env.NODE_ENV}t.rules&&t.rules.forEach((i,s)=>{let l=(Array.isArray(i.condition)?i.condition.map(f=>f.field):[i.condition.field]).filter(f=>!r.includes(f));if(l.length>0)throw A(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${l.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${l.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:l,operation:"validateFormConfig"},severity:"error"});let m=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(f=>!r.includes(f));if(m.length>0)throw A(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${m.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${m.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:m,operation:"validateFormConfig"},severity:"error"})}),Object.entries(n).forEach(([i,s])=>{if(s.dependsOn&&!r.includes(s.dependsOn.field))throw A(new Error(`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`,context:{entityName:e.name,fieldName:i,dependsOnField:s.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Ao(e){return e.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...e.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function cf(e){let t=e;try{So(t),ko(t);let n=Ao(t),r={...t.fields,...I,...t.fields.createdAt&&{createdAt:{...I.createdAt,...t.fields.createdAt,type:I.createdAt.type,visibility:I.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...I.updatedAt,...t.fields.updatedAt,type:I.updatedAt.type,visibility:I.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...I.createdById,...t.fields.createdById,type:I.createdById.type,visibility:I.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...I.updatedById,...t.fields.updatedById,type:I.updatedById.type,visibility:I.updatedById.visibility}},...t.fields.status&&{status:{...I.status,...t.fields.status,validation:{...I.status.validation,...t.fields.status.validation,options:To(ut,t.fields.status.validation?.options)}}},...t.scope&&{[t.scope.field]:xo(t.scope)}};if(t.listFields){let l=new Set(Object.keys(r)),d=t.listFields.filter(m=>!l.has(m));if(d.length>0)throw A(new Error(`Entity '${t.name}' defines listFields that do not exist: ${d.join(", ")}`),{userMessage:`Entity '${t.name}' defines listFields that do not exist: ${d.join(", ")}`,context:{entityName:t.name,invalidFields:d,operation:"defineEntity"},severity:"error"})}if(t.listCardFields){let l=new Set(Object.keys(r)),m=Ne(t).filter(f=>!l.has(f));if(m.length>0)throw A(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${m.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${m.join(", ")}`,context:{entityName:t.name,invalidFields:m,operation:"defineEntity"},severity:"error"})}if(t.uniqueKeys){let l=new Set(Object.keys(r));Ro(t,l)}let i={...ze,...t.access||{}},s=t.namespace||`entity-${t.name.toLowerCase()}`,a={...t,form:n,fields:r,access:i,namespace:s,...t.search&&{search:t.search},...t.defaultSort&&{defaultSort:t.defaultSort}};try{Le(a)}catch(l){let d=l instanceof Error?l.message:String(l);throw A(new Error(d),{userMessage:d,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}return Hn(a),a}catch(n){throw A(n,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}import*as w from"valibot";function N(e){let t=e?.status;return typeof t=="string"?t:null}function $e({op:e,status:t,storedStatus:n}){return Ve(t??n,"saveIncomplete")?"draft":e==="create"?"create":"update"}function Kn({op:e,status:t,storedStatus:n}){if(e!=="update")return!1;let r=t??n;return r==null||r===n?!1:Ve(n,"holdIncomplete")&&!Ve(r,"holdIncomplete")}function Gn(e){return e!=null&&Object.hasOwn(V,e)?V[e]:wt}function Ve(e,t){return Gn(e)[t]}function je(e,t){let n=Gn(e).read;return n==="guest"||Y(t,n)}function gt(e){return Object.keys(V).filter(t=>V[t][e])}function Q(e,t){return Object.assign(e,{visibility:t})}function X(e,t){return Object.assign(e,{metadata:{collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys},...t.security&&{security:t.security}}})}function Co(e){let t=z(e);return Q(t,e.visibility)}function Io(e,t){if(!st.includes(t.type))throw new Error(`Field '${e}' has i18n: true but type '${t.type}'. Translatable types: ${st.join(", ")}.`);let n=z({...t,validation:{...t.validation,required:!1}});return Q(w.optional(w.nullable(w.record(w.string(),n))),t.visibility)}function se(e,t){for(let n of Object.keys(e)){let r=t[n];r?.i18n===!0&&(e[ge(n)]=Io(n,r))}return e}function ht(e){let t=z({...e,validation:{...e.validation,required:!1}});return Q(t,e.visibility)}function wo(e){return e.validation?.required?Q(w.optional(z(e)),e.visibility):ht(e)}function Ef(e){let t=e.fields,n=Le(e).fields,r=C=>n[C]?.write==="never",i={};for(let[C,F]of Object.entries(t))n[C]?.visibleAt!=="hidden"&&(i[C]=ht(F));let s=X(w.object(se({...i},t)),e),a={};for(let[C,F]of Object.entries(t))r(C)||(a[C]=Co(F));let l=X(w.object(se({...a},t)),e),d={};for(let[C,F]of Object.entries(t))if(!r(C))if(C==="status"){let H=w.picklist(gt("saveIncomplete"));d[C]=Q(H,F.visibility)}else d[C]=ht(F);let m=X(w.object(se({...d},t)),e),f={};for(let[C,F]of Object.entries(t))r(C)||(f[C]=wo(F));f.id=Q(z(I.id),"technical");let S=X(w.object(se({...f},t)),e),P;if(e.listFields&&e.listFields.length>0){let C=["id","status"],F=[...new Set([...C,...e.listFields])];P={};for(let H of F){let le=i[H];le&&(P[H]=le)}}else P=i;let _=X(w.object(se({...P},t)),e),T,L=Ne(e);if(L.length>0){let C=["id","status"],F=[...new Set([...C,...L])];T={};for(let H of F){let le=i[H];le&&(T[H]=le)}}else T=i;let ve=X(w.object(se({...T},t)),e),tr=X(w.object({id:Q(z(I.id),"technical")}),e);return{create:l,draft:m,update:S,get:s,list:_,listCard:ve,delete:tr}}function xf(e,t,n=1,r=!1){let i=[];if(r)for(let s=t;s>=e;s-=n)i.push({value:String(s),label:String(s)});else for(let s=e;s<=t;s+=n)i.push({value:String(s),label:String(s)});return i}var Z=new Map;function Rf(e,t){Z.has(e)&&process.env.NODE_ENV,Z.set(e,t)}function kf(e){Z.delete(e)}function Af(e){let t=Z.get(e);return t?t():(process.env.NODE_ENV,null)}function Cf(e){return Z.has(e)}function If(){return Array.from(Z.keys())}function wf(){Z.clear()}import*as y from"valibot";var Oo=y.record(y.string(),y.unknown()),Po=y.object({id:y.string(),patch:y.record(y.string(),y.unknown())}),Do=y.string(),Pf=y.object({inserts:y.optional(y.array(Oo)),updates:y.optional(y.array(Po)),deletes:y.optional(y.array(Do))}),Fo=y.object({insertedIds:y.array(y.string()),updatedIds:y.array(y.string()),deletedIds:y.array(y.string())}),No=y.variant("op",[y.object({op:y.literal("insert"),index:y.pipe(y.number(),y.integer(),y.minValue(0)),id:y.optional(y.string()),error:y.string()}),y.object({op:y.literal("update"),id:y.string(),index:y.optional(y.pipe(y.number(),y.integer(),y.minValue(0))),error:y.string()}),y.object({op:y.literal("delete"),id:y.string(),index:y.optional(y.pipe(y.number(),y.integer(),y.minValue(0))),error:y.string()})]),_o=y.object({...Fo.entries,failed:y.optional(y.array(No),()=>[])});function Df(e,t){let n=y.parse(_o,t),r=l=>{throw new Error(`Invalid bulk acknowledgement: ${l}`)},i=e.inserts??[],s=new Set;for(let l of n.failed){if(l.op!=="insert")continue;(l.index>=i.length||s.has(l.index))&&r("unknown or duplicate insert index");let d=i[l.index];l.id!==void 0&&l.id!==d.id&&r("contradictory insert identity"),s.add(l.index)}n.insertedIds.length+s.size!==i.length&&r("missing or extra insert outcomes"),new Set(n.insertedIds).size!==n.insertedIds.length&&r("duplicate inserted ID");let a=new Set([...s].map(l=>i[l].id).filter(l=>typeof l=="string"));n.insertedIds.some(l=>a.has(l))&&r("insert ID both successful and failed");for(let l of["update","delete"]){let d=l==="update"?(e.updates??[]).map(({id:T})=>T):e.deletes??[],m=l==="update"?n.updatedIds:n.deletedIds,f=new Map;for(let T of d)f.set(T,(f.get(T)??0)+1);let S=new Map,P=new Set;for(let T of n.failed)T.op===l&&((!f.has(T.id)||T.index!==void 0&&d[T.index]!==T.id)&&r(`unknown or contradictory ${l} identity`),T.index!==void 0&&(P.has(T.index)&&r(`duplicate ${l} failure index`),P.add(T.index)),S.set(T.id,(S.get(T.id)??0)+1));let _=d.filter(T=>!S.has(T));for(let[T,L]of S)L!==f.get(T)&&r(`duplicate or ambiguous ${l} failures`);(_.length!==m.length||_.some((T,L)=>m[L]!==T))&&r(`missing, duplicate, unknown or contradictory ${l} outcomes`)}return n}function Ff(e){let t=new Set((e.updates??[]).map(a=>a.id)),n=e.deletes??[],r=[];for(let a of n)t.has(a)&&r.push(a);if(r.length>0)return{collisions:r,where:"updates-deletes"};let i=e.inserts??[],s=[];for(let a of i)typeof a.id=="string"&&t.has(a.id)&&s.push(a.id);return s.length>0?{collisions:s,where:"inserts-updates"}:{collisions:[],where:null}}import*as Yn from"valibot";function Uo(e,t){if(e.ok)return e.written;let n=e.issues.map(r=>`${r.path?.map(i=>String(i.key)).join(".")||"root"}: ${r.message}`).join("; ");throw new R(`Validation failed in ${t}: ${n}`,"validation-failed",{details:{issues:e.issues},source:"validation"})}function zn(e){let t=e.entries;if(!t||typeof t!="object")throw new R("CRUD write rules: a write schema must be an object schema (createSchemas(entity))","internal");return Object.keys(t)}function qe(e,t){let n=[e.create,e.draft,e.update].filter(i=>i!==void 0);if(n.some(i=>i.type==="loose_object"))return[];let r=new Set([...n.flatMap(zn),...de]);return Object.keys(t).filter(i=>!r.has(i))}function Xn(e,t){let n={};for(let r of zn(t))n[r]=null;for(let[r,i]of Object.entries(e))i!==void 0&&(n[r]=i);return n}function ye(e,t,n,r,i){let s=Yn.safeParse(t,n);if(!s.success)return{ok:!1,schemaKey:e,issues:[...s.issues],unknownKeys:i};let a=s.output,l={};for(let d of Object.keys(r))d!=="id"&&Object.hasOwn(a,d)&&(l[d]=a[d]);return{ok:!0,schemaKey:e,written:l,unknownKeys:i}}function Qn(e){return N(e)??Te}function Mo(e,t){let n=Qn(t),r=$e({op:"create",status:n}),i={...t,status:n},s=ye(r,r==="draft"?e.draft:e.create,i,i,qe(e,t));return s.ok?{...s,written:{...s.written,status:n}}:s}function Zn(e){return N(e)!==Xe}function Jn(e,t){let n={op:"update",status:N(e),storedStatus:N(t)};return{schemaKey:$e(n)==="draft"?"draft":"update",whole:Kn(n)}}function er(e,{id:t,patch:n,stored:r}){let i=N(n);if(!r&&Zn(n))throw new R(`CRUD update rules: row "${t}" needs its stored row (the row's status${i===null?"":" and the publish check"} come from it); read it before the update.`,"internal");let{schemaKey:s,whole:a}=Jn(n,r),l=qe(e,n);if(r&&a)return ye(s,e.update,Xn({...r,...n,id:t},e.update),n,l);let d=s==="draft"?{...n,status:N(n)??N(r),id:t}:{...n,id:t};return ye(s,s==="draft"?e.draft:e.update,d,n,l)}function Lo(e,t){return er(e,{id:t,patch:{status:Xe}})}function Bo(e){return J.filter(t=>!je(t,e))}function Vo(e,t){return je(N(e),t)}import*as b from"valibot";var tg=b.pipe(b.string(),b.check(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),$o=b.picklist(["ephemeral","session","persistent"]),jo=b.object({title:b.optional(b.string()),pinnable:b.optional(b.boolean()),preferredHeight:b.optional(b.pipe(b.number(),b.minValue(0)))}),qo=b.object({id:b.pipe(b.string(),b.minLength(1)),kind:b.pipe(b.string(),b.minLength(1)),lifetime:b.optional($o,"ephemeral"),metadata:b.optional(jo),payload:b.unknown()}),Wo=b.object({widgetId:b.pipe(b.string(),b.minLength(1)),action:b.pipe(b.string(),b.minLength(1)),payload:b.unknown()}),ae=new Map;function ng(e){if(ae.has(e.kind))throw new Error(`[canvas] Widget kind "${e.kind}" already registered.`);ae.set(e.kind,e)}function rg(e){return ae.get(e)}function ig(){return Array.from(ae.values())}function og(e,t){let n=b.safeParse(qo,e);if(!n.success)return{ok:!1,reason:`Invalid canvas block envelope: ${We(n.issues)}`};let r=ae.get(n.output.kind);if(!r)return{ok:!1,reason:`Unknown widget kind: "${n.output.kind}"`};let i=b.safeParse(r.schema,n.output.payload);if(!i.success)return{ok:!1,reason:`Payload rejected by "${n.output.kind}" schema: ${We(i.issues)}`};if(t?.caller!==void 0){let a=t.caller.access;if(!Ho(r.surface,a))return{ok:!1,reason:`surface_forbidden: widget "${n.output.kind}" surface=${r.surface} not reachable by caller access=${a===null?"null":a}`}}return{ok:!0,value:{...n.output,payload:i.output},widget:r}}function Ho(e,t){return e==="meta"?!0:e==="household"||e==="private"?t==="admin"||t==="member":!1}function sg(e,t){let n=b.safeParse(Wo,e);if(!n.success)return{ok:!1,reason:`Invalid canvas event envelope: ${We(n.issues)}`};let r=ae.get(t);if(!r)return{ok:!1,reason:`Unknown widget kind: "${t}"`};let i=r.actions[n.output.action];if(!i)return{ok:!1,reason:`Widget "${t}" has no action "${n.output.action}"`};let s=b.safeParse(i,n.output.payload);return s.success?{ok:!0,value:{...n.output,payload:s.output},widget:r}:{ok:!1,reason:`Payload rejected by "${t}.${n.output.action}" schema: ${We(s.issues)}`}}function We(e){return e.map(t=>{let n=t.path?.map(r=>String(r.key)).join(".")??"";return n?`${n}: ${t.message}`:t.message}).join("; ")}export{Ea as AGGREGATE_FILTER_OPERATORS,ba as AGGREGATE_OPERATIONS,sr as AIChatRequestSchema,lr as AIChatResponseSchema,yt as AIMessageSchema,ts as AIProviderConfigSchema,or as AIToolCallSchema,ir as AIToolDefinitionSchema,ar as AIUsageSchema,zo as AI_ERROR_CODES,Go as AI_MODELS,U as AI_PROVIDERS,be as AI_ROLES,Xo as AI_TIERS,Zo as AI_TOKEN_PRICING,sl as AUTH_EVENTS,Bt as AUTH_PARTNERS,Ts as AUTH_PARTNER_STATE,Dt as AtomicBulkError,lt as AuthHardening,vt as AuthUserSchema,de as BACKEND_GENERATED_FIELD_NAMES,ll as BILLING_EVENTS,Ir as BREAKPOINT_RANGES,Ze as BREAKPOINT_THRESHOLDS,Ln as BUILTIN_VALUES,J as BUILT_IN_STATUSES,Nt as BulkAcrossCycleError,Ft as BulkCollisionError,Do as BulkDeleteIdSchema,Oo as BulkInsertSchema,_t as BulkNotImplementedError,No as BulkOutcomeFailureSchema,_o as BulkOutcomeSchema,Pf as BulkRequestSchema,Fo as BulkResponseSchema,Po as BulkUpdateSchema,Ke as COMMON_TIER_CONFIGS,sa as CONFIDENCE_LEVELS,$t as CONSENT_CATEGORY,oa as CONTEXTS,K as CRUD_OPERATORS,Gt as CURRENCY_MAP,wt as CUSTOM_STATUS,qo as CanvasBlockSchema,Wo as CanvasEventSchema,$o as CanvasLifetimeSchema,jo as CanvasWidgetMetadataSchema,mr as CheckoutLineItemInputSchema,It as CheckoutSessionMetadataSchema,he as ConditionBuilder,Rt as CreateCheckoutSessionRequestSchema,kt as CreateCheckoutSessionResponseSchema,Et as CustomClaimsSchema,Yo as DEFAULT_AI_CONFIG,Qo as DEFAULT_AI_MARKUP,Vp as DEFAULT_CRUD_TIMEOUT,ze as DEFAULT_ENTITY_ACCESS,ee as DEFAULT_ERROR_MESSAGES,Or as DEFAULT_LAYOUT_PRESET,Pr as DEFAULT_OG_IMAGE,Te as DEFAULT_STATUS,ut as DEFAULT_STATUS_OPTIONS,wm as DEFAULT_STATUS_VALUE,Se as DEFAULT_SUBSCRIPTION,Bp as DEFAULT_UPLOAD_TIMEOUT,fu as DENSITY,R as DoNotDevError,q as EDITABLE,Ha as EMAIL_ERROR_CODES,Wa as EMAIL_PROVIDERS,xs as EMAIL_VERIFICATION_STATUS,Re as ENTITY_HOOK_ERRORS,ia as ENVIRONMENTS,pe as ERROR_CODES,el as ERROR_SEVERITY,tl as ERROR_SOURCE,Ut as EntityHookError,md as FAVICON_DEFAULTS,Ge as FEATURES,gu as FEATURE_CONSENT_MATRIX,aa as FEATURE_STATUS,Jr as FIELD_TEXT_FORMATTERS,Pt as FIELD_TYPES,Qe as FIREBASE_ERROR_MAP,hd as FONT_STYLE_ID,Dr as FOOTER_MODE,Mt as GITHUB_PERMISSION_LEVELS,Rr as HIDDEN_STATUSES,Xd as LANGUAGE_COOKIE,Fr as LAYOUT_PRESET,ha as LIST_SCHEMA_TYPE,St as MAX_CHECKOUT_LINE_ITEMS,Tt as MAX_SHIPPING_RATE_IDS,cl as OAUTH_EVENTS,Vt as OAUTH_PARTNERS,ga as ORDER_DIRECTION,Jl as PARTNER_ICONS,pl as PAYLOAD_EVENTS,Ye as PERMISSIONS,ra as PLATFORMS,ad as PRERENDERED_HEAD_ELEMENT_ID,da as PWA_ASSET_TYPES,ca as PWA_DISPLAY_MODES,vr as ProductDeclarationSchema,Gs as ProductDeclarationsSchema,tg as ProxiedImageUrlSchema,Xe as REMOVED_STATUS,pa as ROUTE_SOURCES,Ei as SESSION_RENDER_SEGMENT,pi as SITE_LOGO_PATH,V as STATUS_MATRIX,ua as STORAGE_SCOPES,la as STORAGE_TYPES,fl as STRIPE_EVENTS,xe as STRIPE_MODES,Ds as SUBSCRIPTION_DURATIONS,Ee as SUBSCRIPTION_STATUS,dr as SUBSCRIPTION_TIERS,kr as SendEmailRequestSchema,Ar as SendEmailResponseSchema,fe as SingletonManager,Tr as StripeBackConfigSchema,br as StripeFrontConfigSchema,xr as StripeOrderBackSchema,Sr as StripeOrderShippingSchema,Er as StripeOrderTaxSchema,hr as StripePaymentSchema,yr as StripeSubscriptionSchema,B as SubscriptionClaimsSchema,At as SubscriptionDataSchema,_i as TECHNICAL_FIELD_NAMES,st as TRANSLATABLE_FIELD_TYPES,O as USER_ROLES,bt as UserSubscriptionSchema,fa as VISIBILITY,fr as VerifyOrderCheckoutRequestSchema,gr as VerifyOrderCheckoutResultSchema,Ct as WebhookEventSchema,Uo as assertWrite,I as baseFields,ld as buildBreadcrumbJsonLd,ed as buildProductJsonLd,Ht as captureErrorToSentry,ql as checkGitHubAccessSchema,Nd as clearGlobalSingleton,wf as clearScopeProviders,Ae as commonErrorCodeMappings,Yt as compactToISOString,jd as configureProviders,Md as createAsyncSingleton,cr as createDefaultSubscriptionClaims,Rs as createDefaultUserProfile,Ia as createEntitySchema,$ as createErrorHandler,Uc as createMetadata,Ld as createMethodProxy,Ef as createSchemas,_d as createSingleton,Ud as createSingletonWithParams,Qn as createStatus,cf as defineEntity,Pa as deleteEntitySchema,Jc as deriveEntitySeo,Le as describeEntity,ho as describeField,Ff as detectBulkCollisions,jt as detectErrorSource,Kl as disconnectOAuthSchema,Hu as enhanceSchema,kc as ensureSpreadable,re as evaluateCondition,Op as evaluateFieldConditions,Wl as exchangeTokenSchema,gd as faviconHeadTags,mp as filterVisibleFields,yd as fontPreloadHeadTags,Ce as formatCurrency,Zr as formatDate,nn as formatFieldText,Kc as formatRelativeTime,xi as formatTrailingSlash,vi as generateCodeChallenge,yi as generateCodeVerifier,nd as generateFirestoreRuleCondition,bd as generatePKCEPair,Mp as generateUUID,wr as getBreakpointFromWidth,Il as getBreakpointUtils,ef as getCollectionName,Dp as getConditionDependencies,Gl as getConnectionsSchema,Xr as getCurrencyLocale,Lc as getCurrencySymbol,jc as getCurrentTimestamp,bo as getEntityByCollection,wa as getEntitySchema,Pe as getGlobalSingleton,Ne as getListCardFieldNames,qd as getProvider,If as getRegisteredScopeProviders,wd as getRoleFromClaims,z as getSchemaType,Af as getScopeValue,Gd as getTranslatedFieldNames,En as getVisibleFields,Hc as getWeekFromISOString,rg as getWidget,Nr as githubPermissionSchema,Je as githubRepoConfigSchema,$l as grantGitHubAccessSchema,A as handleError,vo as hasMetadata,Wd as hasProvider,hp as hasRestrictedVisibility,Y as hasRoleAccess,Cf as hasScopeProvider,Dd as hasTierAccess,Bo as hiddenStatusesFor,ge as i18nFieldName,ru as isAuthPartnerId,Rn as isBackendGeneratedField,Cl as isBreakpoint,zt as isCompactDateString,en as isEmptyFieldValue,Ci as isFieldVisible,Om as isFrameworkField,at as isMultilingual,iu as isOAuthPartnerId,Ed as isPKCESupported,Vo as isReadableBy,Vc as isoToCompactString,mi as jsonScriptText,Ti as languageUrl,rp as languageUrls,Ad as lazyImport,Da as listEntitiesSchema,ig as listWidgets,yn as localizePath,te as mapToDoNotDevError,sp as matchRoute,id as maybeTranslate,$c as normalizeToISOString,ds as overrideFeatures,Ps as overridePaymentModes,ps as overridePermissions,ur as overrideSubscriptionStatus,cs as overrideSubscriptionTiers,us as overrideUserRoles,Zd as parseAcceptLanguage,Nc as parseBlogFrontmatter,Xt as parseDate,Gc as parseDateToNoonUTC,Mo as prepareCreate,Lo as prepareRemove,er as prepareUpdate,tp as publicPathname,xf as rangeOptions,Qd as readCookieValue,cn as readI18nSeoMeta,ud as recordHeadTags,Hl as refreshTokenSchema,Rf as registerScopeProvider,$m as registerUniqueConstraintValidator,ng as registerWidget,Hd as resetProviders,fd as resolveFaviconFiles,mt as resolveFieldValue,gn as resolveLanguage,ip as resolveLanguageRoute,un as resolveSeoField,wi as resolveUserSubscription,jl as revokeGitHubAccessSchema,gi as robotsContent,pd as routeHeadTags,dd as routeSeo,hi as routeTitle,Rc as safeValidate,_p as sanitizeHref,lc as showNotification,cd as siteHeadTags,hn as splitLanguagePath,Ve as statusCan,N as statusOf,je as statusReadableBy,gt as statusesThat,it as stripHtmlTags,np as stripTrailingSlash,Wc as timestampToISOString,Yc as toDateOnly,qc as toISOString,Kt as translateArray,Pc as translateArrayRange,Dc as translateArrayWithIndices,nt as translateEntityLabel,Oc as translateObjectArray,Yd as translateRow,kf as unregisterScopeProvider,Jn as updateCheck,Oa as updateEntitySchema,lp as updateMetadata,Zn as updateNeedsStored,ns as validateAIChatRequest,rs as validateAIChatResponse,tu as validateAuthPartners,Es as validateAuthSchemas,ys as validateAuthUser,Xs as validateBillingSchemas,og as validateBlock,Df as validateBulkOutcome,Ks as validateCheckoutSessionMetadata,xd as validateCodeChallenge,Sd as validateCodeVerifier,js as validateCreateCheckoutSessionRequest,qs as validateCreateCheckoutSessionResponse,bs as validateCustomClaims,Be as validateDates,Hm as validateDocument,sg as validateEvent,nu as validateOAuthPartners,Ga as validateSendEmailRequest,Ya as validateSendEmailResponse,zs as validateStripeBackConfig,Ys as validateStripeFrontConfig,pr as validateSubscriptionClaims,Ws as validateSubscriptionData,jn as validateUniqueFields,vs as validateUserSubscription,Vs as validateVerifyOrderCheckoutRequest,$s as validateVerifyOrderCheckoutResult,Hs as validateWebhookEvent,Tc as validateWithSchema,Pp as when,ac as withErrorHandling,Rd as withGracefulDegradation,$p as withTimeout,Ec as wrapAuthError,vc as wrapCrudError,bc as wrapStorageError};