@velastack/patterns 0.4.0 → 0.4.2
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.
- package/dist/chunks/{_layout-kkgN0IF7.js → _layout-D-FzWqn0.js} +2 -2
- package/dist/chunks/_layout-D-FzWqn0.js.map +1 -0
- package/dist/chunks/_page-C7kGoW7_.js +6 -0
- package/dist/chunks/_page-C7kGoW7_.js.map +1 -0
- package/dist/chunks/_page-e_I-fdSR.js +6 -0
- package/dist/chunks/_page-e_I-fdSR.js.map +1 -0
- package/dist/chunks/auth-pages-B52ei-4z.js +291 -0
- package/dist/chunks/auth-pages-B52ei-4z.js.map +1 -0
- package/dist/chunks/{collections-Dz2fvKnz.js → collections-zzZ_HQxB.js} +2 -2
- package/dist/chunks/collections-zzZ_HQxB.js.map +1 -0
- package/dist/chunks/{compose-handle-D_Rz3Fzo.js → compose-handle-BDlZ7Pif.js} +2 -2
- package/dist/chunks/compose-handle-BDlZ7Pif.js.map +1 -0
- package/dist/chunks/{config-target-Dx3w6WSk.js → config-target-rHgjaA8u.js} +2 -2
- package/dist/chunks/config-target-rHgjaA8u.js.map +1 -0
- package/dist/chunks/{constants-BjyMU5s8.js → constants-Rq8SCXwH.js} +2 -2
- package/dist/chunks/constants-Rq8SCXwH.js.map +1 -0
- package/dist/chunks/dedent-Gq6Krl4n.js.map +1 -1
- package/dist/chunks/dispatch-D4TN9pdW.js +6 -0
- package/dist/chunks/dispatch-D4TN9pdW.js.map +1 -0
- package/dist/chunks/env-BPfk1VAw.js.map +1 -1
- package/dist/chunks/{env-vars-C1NUX-bf.js → env-vars-CcE6ODqC.js} +4 -4
- package/dist/chunks/env-vars-CcE6ODqC.js.map +1 -0
- package/dist/chunks/env-vars-Cr4lbMD_.js.map +1 -1
- package/dist/chunks/env-vars-De0Xs0L2.js.map +1 -1
- package/dist/chunks/env-vars-file-B_6esJW3.js.map +1 -1
- package/dist/chunks/env-vars-mnRA0hOe.js.map +1 -1
- package/dist/chunks/env.preview-uMRKT5Pc.js.map +1 -1
- package/dist/chunks/errors-DR3gF_7a.js.map +1 -1
- package/dist/chunks/{format-result-DZ8De8KY.js → format-result-BVoLVknk.js} +2 -2
- package/dist/chunks/format-result-BVoLVknk.js.map +1 -0
- package/dist/chunks/{generate-DeaBlnK6.js → generate-B6Odfk5f.js} +2 -2
- package/dist/chunks/generate-B6Odfk5f.js.map +1 -0
- package/dist/chunks/{generate-WMJo3QGZ.js → generate-Bg0E3eWm.js} +2 -2
- package/dist/chunks/generate-Bg0E3eWm.js.map +1 -0
- package/dist/chunks/{generate-Gcc8iRkZ.js → generate-CFqpRi9D.js} +3 -3
- package/dist/chunks/generate-CFqpRi9D.js.map +1 -0
- package/dist/chunks/{generate-BW3l5Fxw.js → generate-CZGHByV3.js} +2 -2
- package/dist/chunks/generate-CZGHByV3.js.map +1 -0
- package/dist/chunks/generate-DetW_gbr.js.map +1 -1
- package/dist/chunks/{generate.runtime-IlBCcXvv.js → generate.runtime-5rIc-RNL.js} +7 -7
- package/dist/chunks/generate.runtime-5rIc-RNL.js.map +1 -0
- package/dist/chunks/{generate.runtime-CA7Ofjlx.js → generate.runtime-BK3mR0Rj.js} +93 -141
- package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +1 -0
- package/dist/chunks/{generate.runtime-cwvAoKoH.js → generate.runtime-BpMN5Uq-.js} +3 -3
- package/dist/chunks/generate.runtime-BpMN5Uq-.js.map +1 -0
- package/dist/chunks/{generate.runtime-DD51OSuL.js → generate.runtime-CAn1qIQ_.js} +4 -4
- package/dist/chunks/generate.runtime-CAn1qIQ_.js.map +1 -0
- package/dist/chunks/{generate.runtime-CuNhY5hn.js → generate.runtime-CEqLgLT9.js} +16 -11
- package/dist/chunks/generate.runtime-CEqLgLT9.js.map +1 -0
- package/dist/chunks/{generate.runtime-B1jVAnDI.js → generate.runtime-CK10Mum5.js} +8 -8
- package/dist/chunks/generate.runtime-CK10Mum5.js.map +1 -0
- package/dist/chunks/{generate.runtime-DqD3PW-W.js → generate.runtime-CZ46nkSL.js} +3 -3
- package/dist/chunks/generate.runtime-CZ46nkSL.js.map +1 -0
- package/dist/chunks/{generate.runtime-CslAvllQ.js → generate.runtime-CbE9RHcf.js} +5 -5
- package/dist/chunks/generate.runtime-CbE9RHcf.js.map +1 -0
- package/dist/chunks/{generate.runtime-CCr1lvo4.js → generate.runtime-CpMKXBkn.js} +7 -7
- package/dist/chunks/generate.runtime-CpMKXBkn.js.map +1 -0
- package/dist/chunks/{generate.runtime-6FXJM8hT.js → generate.runtime-CqncBFNg.js} +5 -5
- package/dist/chunks/generate.runtime-CqncBFNg.js.map +1 -0
- package/dist/chunks/generate.runtime-DG2z6kqH.js +68 -0
- package/dist/chunks/generate.runtime-DG2z6kqH.js.map +1 -0
- package/dist/chunks/{generate.runtime-C6bSvGMb.js → generate.runtime-DHHlYfTD.js} +6 -6
- package/dist/chunks/generate.runtime-DHHlYfTD.js.map +1 -0
- package/dist/chunks/generate.runtime-DJ9MVVPC.js +325 -0
- package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +1 -0
- package/dist/chunks/{generate.runtime-CnPraLKv.js → generate.runtime-DVB7uuht.js} +4 -4
- package/dist/chunks/generate.runtime-DVB7uuht.js.map +1 -0
- package/dist/chunks/{generate.runtime-kvxmTlQb.js → generate.runtime-Db0HZyj3.js} +3 -3
- package/dist/chunks/{generate.runtime-kvxmTlQb.js.map → generate.runtime-Db0HZyj3.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D_sQOeQa.js → generate.runtime-Djas9UNy.js} +6 -6
- package/dist/chunks/generate.runtime-Djas9UNy.js.map +1 -0
- package/dist/chunks/{generate.runtime-Ce_rwzNa.js → generate.runtime-Dl6OQ7pe.js} +4 -4
- package/dist/chunks/generate.runtime-Dl6OQ7pe.js.map +1 -0
- package/dist/chunks/{generate.runtime-1-91UmM8.js → generate.runtime-DoZJHtZh.js} +4 -4
- package/dist/chunks/generate.runtime-DoZJHtZh.js.map +1 -0
- package/dist/chunks/generate.runtime-Dp7SsCQG.js +42 -0
- package/dist/chunks/generate.runtime-Dp7SsCQG.js.map +1 -0
- package/dist/chunks/{generate.runtime-C8zJRNYG.js → generate.runtime-E-zoeSKW.js} +5 -5
- package/dist/chunks/generate.runtime-E-zoeSKW.js.map +1 -0
- package/dist/chunks/{generate.runtime-pVLzzpUM.js → generate.runtime-EQnytCFL.js} +40 -40
- package/dist/chunks/generate.runtime-EQnytCFL.js.map +1 -0
- package/dist/chunks/generate.runtime-IWEhGhWY.js +218 -0
- package/dist/chunks/generate.runtime-IWEhGhWY.js.map +1 -0
- package/dist/chunks/{generate.runtime-CYagyR5c.js → generate.runtime-a3R4hqFy.js} +6 -6
- package/dist/chunks/generate.runtime-a3R4hqFy.js.map +1 -0
- package/dist/chunks/{generate.runtime-zJpEufTc.js → generate.runtime-aQnBmH8D.js} +9 -9
- package/dist/chunks/generate.runtime-aQnBmH8D.js.map +1 -0
- package/dist/chunks/{generate.runtime-Dtgw9IQO.js → generate.runtime-axm9wcQv.js} +5 -5
- package/dist/chunks/generate.runtime-axm9wcQv.js.map +1 -0
- package/dist/chunks/{generate.runtime-DHBRyMAq.js → generate.runtime-hTKzxH2M.js} +5 -5
- package/dist/chunks/generate.runtime-hTKzxH2M.js.map +1 -0
- package/dist/chunks/{generate.runtime-BA3tDKnn.js → generate.runtime-kciwaXxh.js} +5 -5
- package/dist/chunks/generate.runtime-kciwaXxh.js.map +1 -0
- package/dist/chunks/{generate.runtime-B_UVGa3q.js → generate.runtime-koQxLywh.js} +5 -5
- package/dist/chunks/generate.runtime-koQxLywh.js.map +1 -0
- package/dist/chunks/{generate.runtime-BXkZob1O.js → generate.runtime-rs1ZOIET.js} +6 -6
- package/dist/chunks/{generate.runtime-BXkZob1O.js.map → generate.runtime-rs1ZOIET.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DV3WmZtb.js → generate.runtime-uLUiPgqx.js} +6 -6
- package/dist/chunks/generate.runtime-uLUiPgqx.js.map +1 -0
- package/dist/chunks/lib-specifier-Cngo1zF_.js.map +1 -1
- package/dist/chunks/logger-CQONztPm.js.map +1 -1
- package/dist/chunks/{modify-file-BlDeeurK.js → modify-file-DK-tCH9k.js} +3 -3
- package/dist/chunks/modify-file-DK-tCH9k.js.map +1 -0
- package/dist/chunks/modify-nav-user-BLyrW2sK.js +71 -0
- package/dist/chunks/modify-nav-user-BLyrW2sK.js.map +1 -0
- package/dist/chunks/{modify-svelte-config-remote-p0TfVzxm.js → modify-svelte-config-remote-DhuRX4FI.js} +2 -2
- package/dist/chunks/modify-svelte-config-remote-DhuRX4FI.js.map +1 -0
- package/dist/chunks/modify-user-signup-BbqTiUuA.js +54 -0
- package/dist/chunks/modify-user-signup-BbqTiUuA.js.map +1 -0
- package/dist/chunks/modify-utils-Cw-on_cL.js.map +1 -1
- package/dist/chunks/package-imports-Bbw3iMPg.js.map +1 -1
- package/dist/chunks/pocketbase-C5GS-Dh5.js.map +1 -1
- package/dist/chunks/{pocketbase-Dry6ry17.js → pocketbase-CgwbH1gI.js} +2 -2
- package/dist/chunks/pocketbase-CgwbH1gI.js.map +1 -0
- package/dist/chunks/pocketbase-DpudAAmd.js.map +1 -1
- package/dist/chunks/providers-BHR6-XZ7.js.map +1 -1
- package/dist/chunks/{shared-CZC4d7Uj.js → shared-Cc_ns5-y.js} +2 -2
- package/dist/chunks/shared-Cc_ns5-y.js.map +1 -0
- package/dist/chunks/{site-BwCA18Sv.js → site-lj0CDdQ1.js} +2 -2
- package/dist/chunks/site-lj0CDdQ1.js.map +1 -0
- package/dist/chunks/svelte-file-B3RfgVdt.js.map +1 -1
- package/dist/chunks/{table-core-AjBpYi-y.js → table-core-DhDqT03G.js} +2 -2
- package/dist/chunks/table-core-DhDqT03G.js.map +1 -0
- package/dist/chunks/{taggedTemplateLiteral-Dx0fjWiw.js → taggedTemplateLiteral-CswN2AAa.js} +1 -1
- package/dist/chunks/{test-setup-DEmWd9Ul.js → test-setup-B9fQ5L_-.js} +5 -5
- package/dist/chunks/test-setup-B9fQ5L_-.js.map +1 -0
- package/dist/chunks/{ts-morph-helpers-CDW4lhox.js → ts-morph-helpers-Bepc-Es2.js} +27 -23
- package/dist/chunks/ts-morph-helpers-Bepc-Es2.js.map +1 -0
- package/dist/chunks/{ui-X698F10c.js → ui-CuCsupFq.js} +3 -3
- package/dist/chunks/ui-CuCsupFq.js.map +1 -0
- package/dist/chunks/ui-DD4NltyN.js.map +1 -1
- package/dist/chunks/{unmodify-load-CyGzC1Hu.js → unmodify-load-Bl5vXQiL.js} +2 -2
- package/dist/chunks/unmodify-load-Bl5vXQiL.js.map +1 -0
- package/dist/chunks/util-BLYliuUK.js.map +1 -1
- package/dist/chunks/whatsapp-CguKGTtw.js +105 -0
- package/dist/chunks/whatsapp-CguKGTtw.js.map +1 -0
- package/dist/chunks/{write-result-B68lvI57.js → write-result-DiZsCS_y.js} +5 -5
- package/dist/chunks/write-result-DiZsCS_y.js.map +1 -0
- package/dist/index.d.ts +133 -1
- package/dist/index.js +2240 -2005
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/_layout-kkgN0IF7.js.map +0 -1
- package/dist/chunks/collections-Dz2fvKnz.js.map +0 -1
- package/dist/chunks/compose-handle-D_Rz3Fzo.js.map +0 -1
- package/dist/chunks/config-target-Dx3w6WSk.js.map +0 -1
- package/dist/chunks/constants-BjyMU5s8.js.map +0 -1
- package/dist/chunks/dispatch-CXOXPLFk.js +0 -6
- package/dist/chunks/dispatch-CXOXPLFk.js.map +0 -1
- package/dist/chunks/env-vars-C1NUX-bf.js.map +0 -1
- package/dist/chunks/format-result-DZ8De8KY.js.map +0 -1
- package/dist/chunks/generate-BW3l5Fxw.js.map +0 -1
- package/dist/chunks/generate-DeaBlnK6.js.map +0 -1
- package/dist/chunks/generate-Gcc8iRkZ.js.map +0 -1
- package/dist/chunks/generate-WMJo3QGZ.js.map +0 -1
- package/dist/chunks/generate.runtime-1-91UmM8.js.map +0 -1
- package/dist/chunks/generate.runtime-6FXJM8hT.js.map +0 -1
- package/dist/chunks/generate.runtime-B1jVAnDI.js.map +0 -1
- package/dist/chunks/generate.runtime-BA3tDKnn.js.map +0 -1
- package/dist/chunks/generate.runtime-BO778G0r.js +0 -188
- package/dist/chunks/generate.runtime-BO778G0r.js.map +0 -1
- package/dist/chunks/generate.runtime-B_UVGa3q.js.map +0 -1
- package/dist/chunks/generate.runtime-C6bSvGMb.js.map +0 -1
- package/dist/chunks/generate.runtime-C8zJRNYG.js.map +0 -1
- package/dist/chunks/generate.runtime-CA7Ofjlx.js.map +0 -1
- package/dist/chunks/generate.runtime-CCr1lvo4.js.map +0 -1
- package/dist/chunks/generate.runtime-CYagyR5c.js.map +0 -1
- package/dist/chunks/generate.runtime-Ce_rwzNa.js.map +0 -1
- package/dist/chunks/generate.runtime-CexC1Oky.js +0 -269
- package/dist/chunks/generate.runtime-CexC1Oky.js.map +0 -1
- package/dist/chunks/generate.runtime-CnPraLKv.js.map +0 -1
- package/dist/chunks/generate.runtime-CslAvllQ.js.map +0 -1
- package/dist/chunks/generate.runtime-CuNhY5hn.js.map +0 -1
- package/dist/chunks/generate.runtime-DD51OSuL.js.map +0 -1
- package/dist/chunks/generate.runtime-DHBRyMAq.js.map +0 -1
- package/dist/chunks/generate.runtime-DV3WmZtb.js.map +0 -1
- package/dist/chunks/generate.runtime-D_sQOeQa.js.map +0 -1
- package/dist/chunks/generate.runtime-DqD3PW-W.js.map +0 -1
- package/dist/chunks/generate.runtime-Dtgw9IQO.js.map +0 -1
- package/dist/chunks/generate.runtime-IlBCcXvv.js.map +0 -1
- package/dist/chunks/generate.runtime-cwvAoKoH.js.map +0 -1
- package/dist/chunks/generate.runtime-pVLzzpUM.js.map +0 -1
- package/dist/chunks/generate.runtime-zJpEufTc.js.map +0 -1
- package/dist/chunks/modify-file-BlDeeurK.js.map +0 -1
- package/dist/chunks/modify-svelte-config-remote-p0TfVzxm.js.map +0 -1
- package/dist/chunks/nav-user-BRIHOOpG.js +0 -6
- package/dist/chunks/nav-user-BRIHOOpG.js.map +0 -1
- package/dist/chunks/pocketbase-Dry6ry17.js.map +0 -1
- package/dist/chunks/shared-CZC4d7Uj.js.map +0 -1
- package/dist/chunks/site-BwCA18Sv.js.map +0 -1
- package/dist/chunks/table-core-AjBpYi-y.js.map +0 -1
- package/dist/chunks/test-setup-DEmWd9Ul.js.map +0 -1
- package/dist/chunks/ts-morph-helpers-CDW4lhox.js.map +0 -1
- package/dist/chunks/ui-X698F10c.js.map +0 -1
- package/dist/chunks/unmodify-load-CyGzC1Hu.js.map +0 -1
- package/dist/chunks/write-result-B68lvI57.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-pages-B52ei-4z.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","__import_glob__0_7_","__import_glob__0_8_","__import_glob__0_9_","__import_glob__0_10_","__import_glob__0_11_","__import_glob__0_12_","__import_glob__0_13_","__import_glob__0_14_","__import_glob__0_15_","__import_glob__0_16_","__import_glob__0_18_","__import_glob__0_19_","__import_glob__0_20_","__import_glob__0_21_","__import_glob__0_22_","__import_glob__0_23_","__import_glob__0_24_","__import_glob__0_25_","__import_glob__0_26_","__import_glob__0_27_","__import_glob__0_28_","__import_glob__0_29_","__import_glob__0_30_","__import_glob__0_31_","__import_glob__0_32_","__import_glob__0_33_","__import_glob__0_34_","__import_glob__0_35_","__import_glob__0_36_","__import_glob__0_37_","__import_glob__0_38_","__import_glob__0_39_","__import_glob__0_40_","__import_glob__0_41_","__import_glob__0_42_","__import_glob__0_43_","__import_glob__0_44_","__import_glob__0_45_","__import_glob__0_46_","__import_glob__0_47_","__import_glob__0_48_","__import_glob__0_49_","__import_glob__0_50_","__import_glob__0_51_","__import_glob__0_52_","__import_glob__0_53_","__import_glob__0_54_","__import_glob__0_55_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__2_0_","__import_glob__2_1_","__import_glob__2_2_","__import_glob__2_3_","__import_glob__2_4_","__import_glob__2_5_","__import_glob__2_6_","__import_glob__2_7_","__import_glob__2_8_","__import_glob__2_9_","__import_glob__2_10_","__import_glob__2_11_","__import_glob__2_12_","__import_glob__2_13_","__import_glob__2_14_","__import_glob__2_15_","__import_glob__2_16_","__import_glob__2_18_","__import_glob__2_19_","__import_glob__2_20_","__import_glob__2_21_","__import_glob__2_22_","__import_glob__2_23_","__import_glob__2_24_","__import_glob__2_25_","__import_glob__2_26_","__import_glob__2_27_","__import_glob__2_28_","__import_glob__2_29_","__import_glob__2_30_","__import_glob__2_31_","__import_glob__2_32_","__import_glob__2_33_","__import_glob__2_34_","__import_glob__2_35_","__import_glob__2_36_","__import_glob__2_37_","__import_glob__2_38_","__import_glob__2_39_","__import_glob__2_40_","__import_glob__2_41_","__import_glob__2_42_","__import_glob__2_43_","__import_glob__2_44_","__import_glob__2_45_","__import_glob__2_46_","__import_glob__2_47_","__import_glob__2_48_","__import_glob__2_49_","__import_glob__2_50_","__import_glob__2_51_","__import_glob__2_52_","__import_glob__2_53_","__import_glob__2_54_","__import_glob__2_55_","__import_glob__2_56_","__import_glob__2_57_","__import_glob__2_58_","__import_glob__2_59_","__import_glob__2_60_","__import_glob__2_61_","__import_glob__2_62_","__import_glob__2_63_","__import_glob__2_64_","__import_glob__3_0_","__import_glob__3_1_","__import_glob__3_2_","__import_glob__3_3_","__import_glob__3_4_","__import_glob__3_5_","__import_glob__3_6_","__import_glob__4_0_","__import_glob__4_1_","__import_glob__4_2_","__import_glob__4_3_","__import_glob__4_4_","__import_glob__4_5_","__import_glob__4_6_","__import_glob__4_7_","__import_glob__4_8_","__import_glob__4_9_","__import_glob__4_10_","__import_glob__4_11_","__import_glob__4_12_","__import_glob__4_13_","__import_glob__4_14_","__import_glob__4_15_","_page_default$26","_page_server_default$3","server_test_default$14","_page_server_default$8","_page_default$31","_page_server_default$6","server_test_default$16","server_test_default$8","_page_server_default$15","server_test_default$7","_page_default$35","_page_server_default$9","server_test_default$13","server_test_default$5","_page_default$29","_page_default$12","server_test_default$11","_server_default","_server_default$2","_server_default$1","_page_default$28","_page_default$11","_page_server_default$12","_page_server_default$5","server_test_default$12","server_test_default$4","_page_default$34","_page_default$17","_page_default$33","_page_default$16","server_test_default$15","_page_default$19","_page_server_default$14","_page_server_default$7","server_test_default$10","_page_default$8","form_remote_default$5","_page_default$15","_page_server_default$16","_page_server_default$10","_page_default$36","_page_default$20","form_remote_default$4","server_test_default$2","_page_server_default$13","server_test_default$3","_page_default$30","_page_default$13","_page_server_default$11","_page_server_default$4","_page_default$27","_page_default$10","_layout_server_default$3","_page_default$9","_page_server_default$17","nav_user_default","_page_default$25","signup_default$5","user_default","reset_default$1","_page_default$38","_page_default$23","next_url_default","reset_default","login_default$2","_page_default$41","login_default$1","changePassword_default$1","_layout_server_default$1","_layout_default$1","_page_server_default$18","confirmReset_default","changeEmail_default$1","_page_default$39","user_avatar_default","app_sidebar_default$1","_page_default$40","changeEmail_default","nav_main_default$1","_page_server_default$19","_layout_server_default","signup_default$4","form_remote_default$6","server_test_default$6","_server_default$3","_page_default$18","form_remote_default$10","profile_default","confirmReset_default$1","form_remote_default$9","changePassword_default","nav_user_default$1","_page_server_default$20","_page_default$7","user_default$1","login_default$3","welcome_default","profile_default$1","server_test_default$18","confirmEmailChange_default","user_avatar_default$1","form_remote_default$3","server_test_default$1","_page_default$43","_layout_default","welcome_default$1","server_test_default$19","signup_default$3","otp_default$1","_page_default$44","server_test_default","_layout_server_default$2","_page_default$42","otp_default","confirmEmailChange_default$1","server_test_default$17","nav_main_default","form_remote_default$7","_page_default$21","_page_default$37","_page_default$22","form_remote_default$8","app_sidebar_default","server_test_default$9","_page_default$32","_page_default$14","modifyUserSignup","fs","path","prettier","sveltePlugin","signup_default$2","_page_server_default$2","_page_default$6","signup_default$1","_page_default$5","form_remote_default$2","_page_default$4","login_default","signup_default","_page_server_default$1","_page_default$3","form_remote_default$1","_page_server_default","_page_default$2","form_remote_default","_page_default$1","_page_default","normalize","content","filePath","planFile","current","marker","normalized","overlay","overlays","candidate","candidates","original","applyGroup","outcomes","blocked","planned","p","outcome","hint","others","raw","glob","key","prefix","STOCK","_page_default$24","LEGACY","TEMPLATES","WHATSAPP_CODE","AUTH","pageGroups","group","name","mode","detectMode","root","SHAPES","pick","files","shape","rel","stock","candidatesFor","seen","whatsapp","direction","PAYMENTS_SIGNUP","swapAuthPages"],"sources":["../../src/patterns/enable/whatsapp/modifies/modify-by-original.ts","../../src/patterns/enable/whatsapp/modifies/auth-pages.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport prettier from \"prettier\";\nimport sveltePlugin from \"prettier-plugin-svelte\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/** A stock version of a file, and what it becomes. */\nexport interface Candidate {\n original: string;\n template: string;\n}\n\n/**\n * Another pattern's edit to the file that the swap carries over: `strip`\n * takes it out of the normalized source to compare that against the\n * originals, `apply` puts it back into the written template.\n */\nexport interface Overlay {\n /** Whether the current file has the edit. */\n detect: (content: string) => boolean;\n /** Gets the normalized source (prettier defaults), returns it without the edit. */\n strip: (normalized: string) => string;\n apply: (filePath: string) => ModifyOutcome;\n}\n\n/** One file of a group, and the swap decided for it. */\nexport interface Planned {\n filePath: string;\n outcome:\n | { kind: \"write\"; template: string; overlay?: Overlay }\n | { kind: \"done\" }\n | { kind: \"missing\" }\n | { kind: \"customized\" };\n}\n\n/**\n * Reprints a source with fixed settings, so the project's own prettier\n * config (tabs, quotes, print width) does not count as a change. Content\n * prettier cannot parse is compared as is.\n */\nasync function normalize(content: string, filePath: string): Promise<string> {\n try {\n return await prettier.format(content, {\n filepath: filePath,\n plugins: [sveltePlugin],\n });\n } catch {\n return content;\n }\n}\n\n/**\n * Decides what to do with one file: `write` the template of the stock\n * original it still matches, `done` when it already has `marker`, else\n * `customized`. A file with an overlay's edit is compared without it.\n */\nexport async function planFile(\n filePath: string,\n candidates: Candidate[],\n marker: RegExp,\n overlays: Overlay[] = [],\n): Promise<Planned> {\n if (!fs.existsSync(filePath)) {\n return { filePath, outcome: { kind: \"missing\" } };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (marker.test(current)) {\n return { filePath, outcome: { kind: \"done\" } };\n }\n\n let normalized = await normalize(current, filePath);\n const overlay = overlays.find((candidate) => candidate.detect(current));\n if (overlay) normalized = overlay.strip(normalized);\n\n for (const { original, template } of candidates) {\n if ((await normalize(original, filePath)) === normalized) {\n return { filePath, outcome: { kind: \"write\", template, overlay } };\n }\n }\n return { filePath, outcome: { kind: \"customized\" } };\n}\n\n/**\n * Applies a group of planned swaps (a page with its server code and schema)\n * all or nothing: one customized or missing file leaves the whole group as\n * it is, since half a swap would not type-check.\n */\nexport function applyGroup(\n planned: Planned[],\n hint: (filePath: string) => string,\n): Map<string, ModifyOutcome> {\n const outcomes = new Map<string, ModifyOutcome>();\n const blocked = planned.filter(\n (p) => p.outcome.kind === \"customized\" || p.outcome.kind === \"missing\",\n );\n\n for (const { filePath, outcome } of planned) {\n if (outcome.kind === \"missing\") {\n outcomes.set(filePath, { status: \"not-found\", message: hint(filePath) });\n } else if (outcome.kind === \"customized\") {\n outcomes.set(filePath, { status: \"failed\", message: hint(filePath) });\n } else if (outcome.kind === \"done\") {\n outcomes.set(filePath, { status: \"success\", changed: false });\n } else if (blocked.length > 0) {\n const others = blocked\n .map(\n (p) =>\n path.basename(path.dirname(p.filePath)) +\n \"/\" +\n path.basename(p.filePath),\n )\n .join(\", \");\n outcomes.set(filePath, {\n status: \"failed\",\n message: `Left as is, along with ${others}, which has changes of its own.\\n${hint(filePath)}`,\n });\n } else {\n fs.writeFileSync(filePath, outcome.template, \"utf8\");\n outcome.overlay?.apply(filePath);\n outcomes.set(filePath, { status: \"success\", changed: true });\n }\n }\n return outcomes;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { modifyUserSignup } from \"../../payments/modifies/modify-user-signup\";\nimport {\n applyGroup,\n planFile,\n type Candidate,\n type Overlay,\n} from \"./modify-by-original\";\n\n/**\n * The login and signup pages as enable-auth writes them, and with WhatsApp.\n * The stock files come straight from the auth patterns, so a change there\n * that is not mirrored in `templates/` fails the tests instead of drifting.\n */\nconst raw = (glob: Record<string, string>, prefix: string) =>\n Object.fromEntries(\n Object.entries(glob).map(([key, content]) => [\n key.slice(prefix.length),\n content,\n ]),\n );\n\nconst STOCK = {\n base: raw(\n import.meta.glob<string>(\"../../auth/creates/src/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n }),\n \"../../auth/creates/\",\n ),\n split: raw(\n import.meta.glob<string>(\"../../auth/variants/split/src/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n }),\n \"../../auth/variants/split/\",\n ),\n remote: raw(\n import.meta.glob<string>(\"../../auth-remote/creates/src/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n }),\n \"../../auth-remote/creates/\",\n ),\n};\n\n/** The pages enable-auth 1.1 wrote, before signup had a one-time code. */\nconst LEGACY = raw(\n import.meta.glob<string>(\"../originals/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n }),\n \"../originals/auth-1.1/\",\n);\n\nconst TEMPLATES = raw(\n import.meta.glob<string>(\"../templates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n }),\n \"../templates/\",\n);\n\ntype Shape = \"base\" | \"split\" | \"remote\";\n\n/** In every file of the WhatsApp versions: the form type, or the helpers. */\nconst WHATSAPP_CODE = /[\"']whatsapp[\"']|whatsappAuthMethod|requestWhatsAppOTP/;\nexport type Mode = \"superforms\" | \"remote\";\n\nconst AUTH = \"src/routes/(public)/(auth)\";\n\n/** The files of each form, all swapped or none. */\nexport function pageGroups(mode: Mode): Record<\"login\" | \"signup\", string[]> {\n const group = (name: \"login\" | \"signup\") => [\n `${AUTH}/${name}/+page.svelte`,\n `${AUTH}/${name}/+page.server.ts`,\n ...(mode === \"remote\" ? [`${AUTH}/${name}/form.remote.ts`] : []),\n `src/lib/schemas/${name}.ts`,\n ];\n return { login: group(\"login\"), signup: group(\"signup\") };\n}\n\n/** A login form posts to a remote function in auth-remote projects. */\nexport function detectMode(root: string): Mode {\n return fs.existsSync(path.join(root, AUTH, \"login\", \"form.remote.ts\"))\n ? \"remote\"\n : \"superforms\";\n}\n\nconst SHAPES: Record<Mode, Shape[]> = {\n superforms: [\"base\", \"split\"],\n remote: [\"remote\"],\n};\n\n/** The split variant only has its own pages; the rest is the base one. */\nfunction pick(\n files: Record<string, string>,\n shape: Shape,\n rel: string,\n): string | undefined {\n return (\n files[`${shape}/${rel}`] ??\n (shape === \"split\" ? files[`base/${rel}`] : undefined)\n );\n}\n\nfunction stock(shape: Shape, rel: string): string | undefined {\n return STOCK[shape][rel] ?? (shape === \"split\" ? STOCK.base[rel] : undefined);\n}\n\n/**\n * Every stock version of `rel` paired with its WhatsApp version: the current\n * and the legacy original of each shape on `enable`, and the WhatsApp version\n * paired with the current stock one on `disable`.\n */\nexport function candidatesFor(\n mode: Mode,\n rel: string,\n direction: \"enable\" | \"disable\",\n): Candidate[] {\n const candidates: Candidate[] = [];\n const seen = new Set<string>();\n for (const shape of SHAPES[mode]) {\n const whatsapp = pick(TEMPLATES, shape, rel);\n const current = stock(shape, rel);\n if (!whatsapp || !current) continue;\n if (direction === \"disable\") {\n if (!seen.has(whatsapp))\n candidates.push({ original: whatsapp, template: current });\n seen.add(whatsapp);\n continue;\n }\n for (const original of [current, pick(LEGACY, shape, rel)]) {\n if (!original || seen.has(original)) continue;\n seen.add(original);\n candidates.push({ original, template: whatsapp });\n }\n }\n return candidates;\n}\n\n/**\n * enable-payments' signup hook, carried over the swap: its import and the\n * `linkStripeCustomer.run(...)` call (comment included) it adds before\n * `requestVerification`.\n */\nconst PAYMENTS_SIGNUP: Overlay = {\n detect: (content) => content.includes(\"linkStripeCustomer\"),\n strip: (normalized) =>\n normalized\n .replace(\n /^import \\{ linkStripeCustomer \\} from \"#lib\\/workflows\\/link-stripe-customer\\.js\";\\n/m,\n \"\",\n )\n .replace(\n /^[ \\t]*\\/\\/ Queued here, done in the background[^\\n]*\\n[ \\t]*\\/\\/ and the key means[^\\n]*\\n[ \\t]*await linkStripeCustomer\\.run\\([\\s\\S]*?\\n[ \\t]*\\);\\n\\n?/m,\n \"\",\n ),\n apply: modifyUserSignup,\n};\n\n/**\n * Swaps the login and signup pages between the stock and WhatsApp versions.\n * A form whose files all still match a known version is swapped; one with\n * changes of its own is left alone and reported with `hint`.\n */\nexport async function swapAuthPages(\n root: string,\n direction: \"enable\" | \"disable\",\n hint: (filePath: string) => string,\n): Promise<Map<string, ModifyOutcome>> {\n const mode = detectMode(root);\n // Code only the WhatsApp versions have (not a comment that mentions it):\n // enabling skips files with it, disabling files without it.\n const marker =\n direction === \"enable\"\n ? WHATSAPP_CODE\n : new RegExp(`^(?![\\\\s\\\\S]*(${WHATSAPP_CODE.source}))`);\n const outcomes = new Map<string, ModifyOutcome>();\n\n for (const files of Object.values(pageGroups(mode))) {\n const planned = await Promise.all(\n files.map((rel) =>\n planFile(\n path.join(root, rel),\n candidatesFor(mode, rel, direction),\n marker,\n rel.endsWith(\"signup/+page.server.ts\") ? [PAYMENTS_SIGNUP] : [],\n ),\n ),\n );\n for (const [filePath, outcome] of applyGroup(planned, hint)) {\n outcomes.set(filePath, outcome);\n }\n }\n return outcomes;\n}\n"],"mappings":";;;;;;;;;;AAwCA,eAAeoS,EAAU,GAAiB,GAAmC;CAC3E,IAAI;EACF,OAAO,MAAMnB,GAAS,OAAOoB,GAAS;GACpC,UAAUC;GACV,SAAS,CAACpB,EAAY;EACxB,CAAC;CACH,QAAQ;EACN,OAAOmB;CACT;AACF;AAOA,eAAsBE,GACpB,GACA,GACA,GACA,IAAsB,CAAC,GACL;CAClB,IAAI,CAACxB,EAAG,WAAWuB,CAAQ,GACzB,OAAO;EAAE;EAAU,SAAS,EAAE,MAAM,UAAU;CAAE;CAElD,IAAME,IAAUzB,EAAG,aAAauB,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+1,7 @@
|
|
|
1
1
|
import { t as e } from "./errors-DR3gF_7a.js";
|
|
2
2
|
import { a as t } from "./util-BLYliuUK.js";
|
|
3
3
|
import { n, t as r } from "./logger-CQONztPm.js";
|
|
4
|
-
import { i, n as a, t as o } from "./pocketbase-
|
|
4
|
+
import { i, n as a, t as o } from "./pocketbase-CgwbH1gI.js";
|
|
5
5
|
import { readFileSync as s } from "node:fs";
|
|
6
6
|
//#region src/runtime/collections.ts
|
|
7
7
|
function c(e) {
|
|
@@ -189,4 +189,4 @@ async function y(e, r) {
|
|
|
189
189
|
//#endregion
|
|
190
190
|
export { m as applyCollectionFieldsPatches, f as applyCollectionRulePatches, u as createCollectionIdempotent, y as createCollections, v as dropCollections, _ as planCollectionDrops };
|
|
191
191
|
|
|
192
|
-
//# sourceMappingURL=collections-
|
|
192
|
+
//# sourceMappingURL=collections-zzZ_HQxB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"collections-zzZ_HQxB.js","names":["InvalidArgumentError","languageFromPath","NOOP_LOGGER","migrationDelay","getMigrationFile","isCollectionAlreadyExistsError","error","message","resolveRelationTargets","fields","spec","relations","field","existing","pb","ids","c","byName","id","createCollectionIdempotent","name","logger","rulePayloadFromPatch","payload","patch","applyCollectionRulePatches","migrations","patches","escaped","col","options","migrationFile","readFileSync","applyFieldChanges","change","f","index","applyCollectionFieldsPatches","collection","newFields","dropCollectionIdempotent","getCollectionStats","planCollectionDrops","plans","names","stats","dropCollections","specs","getLogger","withPocketbase","dropped","createCollections","collections","created"],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\ninterface RelationFieldLike {\n type?: string;\n collectionId?: string;\n}\n\n/**\n * A spec may name the collection a relation points at (`stripe_customers`)\n * where PocketBase wants its id; specs read better by name, and the id is\n * only known once the target exists. Names are swapped for ids here, and a\n * value that already is an id (`_pb_users_auth_`) is left alone.\n */\nasync function resolveRelationTargets(\n pb: PocketBase,\n spec: CollectionCreateInput,\n): Promise<CollectionCreateInput> {\n const fields = (spec as { fields?: RelationFieldLike[] }).fields;\n const relations = (fields ?? []).filter(\n (field) => field.type === \"relation\" && field.collectionId,\n );\n if (relations.length === 0) return spec;\n\n const existing = await pb.collections.getFullList();\n const ids = new Set(existing.map((c) => c.id));\n const byName = new Map(existing.map((c) => [c.name, c.id]));\n if (relations.every((field) => ids.has(field.collectionId!))) return spec;\n\n return {\n ...spec,\n fields: fields!.map((field) => {\n if (field.type !== \"relation\" || !field.collectionId) return field;\n const id = byName.get(field.collectionId);\n return id && !ids.has(field.collectionId)\n ? { ...field, collectionId: id }\n : field;\n }),\n } as CollectionCreateInput;\n}\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(\n await resolveRelationTargets(pb, spec),\n );\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAASK,EACP,GACS;CACT,IACEC,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAMC,IAAUD,EAAM,SAAS,YAAY,KAAK;CAChD,OACEC,EAAQ,SAAS,gBAAgB,KAAKA,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAeC,EACb,GACA,GACgC;CAChC,IAAMC,IAAUC,EAA0C,QACpDC,KAAaF,KAAU,CAAC,EAAA,CAAG,QAC9B,MAAUG,EAAM,SAAS,cAAcA,EAAM,YAChD;CACA,IAAID,EAAU,WAAW,GAAG,OAAOD;CAEnC,IAAMG,IAAW,MAAMC,EAAG,YAAY,YAAY,GAC5CC,IAAM,IAAI,IAAIF,EAAS,KAAK,MAAMG,EAAE,EAAE,CAAC,GACvCC,IAAS,IAAI,IAAI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AAC,GACtBL,IAAS2B,EAAUlB,CAAO;CA+BhC,OA7BA,MAAMmB,EAAenB,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAMQ,KAAcc,GAAa;GACpC,EAAO,KAAK,wBAAwBd,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAMnB,EACxBL,GACAwB,GACAjB,CACF;GACA,IAAI,CAACgC,GAAS;GACd,MAAMlD,EAAe;GAErB,IAAM4B,IAAgB3B,EACpBkC,EAAW,MACX,WACAR,CACF;GACA,AAAKC,KAILL,EAAW,KAAK;IACd,MAAMK;IACN,UAAU9B,EAAiB8B,CAAa;IACxC,SAASC,EAAaD,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEML;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { d as e, l as t, m as n, n as r } from "./ts-morph-helpers-
|
|
1
|
+
import { d as e, l as t, m as n, n as r } from "./ts-morph-helpers-Bepc-Es2.js";
|
|
2
2
|
import { Node as i, SyntaxKind as a, ts as o } from "ts-morph";
|
|
3
3
|
//#region src/runtime/compose-handle.ts
|
|
4
4
|
var s = "@sveltejs/kit/hooks", c = "handleApp";
|
|
@@ -325,4 +325,4 @@ function R(e, n, r) {
|
|
|
325
325
|
//#endregion
|
|
326
326
|
export { L as n, R as r, F as t };
|
|
327
327
|
|
|
328
|
-
//# sourceMappingURL=compose-handle-
|
|
328
|
+
//# sourceMappingURL=compose-handle-BDlZ7Pif.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compose-handle-BDlZ7Pif.js","names":["removeNamedImportIfUnused","removeAttachedComments","removeStatementWithComments","ensureBlankLineAfterImports","KIT_HOOKS","EXTRACTED","locate","exportedBySpecifier","starExport","ed","sf","fromModule","spec","fn","f","statement","decl","nameNode","Node","SyntaxKind","el","kitSequence","found","namespace","named","isBound","name","d","sequenceCallee","kit","ensureSequenceImport","typeOnly","names","pruneSequenceImport","wasRemoved","isSequenceCall","node","callee","unwrap","isHandle","findInSequence","args","index","arg","inner","references","id","commentTexts","ranges","text","r","pieces","call","openParen","closeParen","result","leadingFrom","prevTrailing","ts","leading","comma","trailing","last","lastArg","from","sameLine","dangling","hasComments","list","p","renderCall","multiline","c","renderAlone","piece","isMultiline","i","rewriteSequence","handleStatement","site","currentStatement","located","changed","unchanged","unsupported","removeWholeHandle","viaSpecifier","s","extract","composed","restoreExtracted","init","variable","decls","target","inlineExport","addHandle","position","blank","extractChecked","core","existing","a","removeHandle","calls","outer","kept","comments","replaceHandle","newName"],"sources":["../../src/runtime/compose-handle.ts"],"sourcesContent":["import {\n Node,\n SyntaxKind,\n ts,\n type CallExpression,\n type Expression,\n type FunctionDeclaration,\n type SourceFile,\n type Statement,\n type VariableDeclaration,\n type VariableStatement,\n} from \"ts-morph\";\nimport {\n ensureBlankLineAfterImports,\n removeAttachedComments,\n removeNamedImportIfUnused,\n removeStatementWithComments,\n} from \"./ts-morph-helpers\";\n\n/**\n * Composes the server `handle` hook in `hooks.server.ts`.\n *\n * Patterns add and subtract handles in the exported `handle` without caring\n * what shape it is in: a lone expression becomes `sequence(new, old)`, a\n * `sequence(...)` gains or loses an argument, and a handle that is a function\n * is moved to a local `handleApp` so it can take part. Subtracting back to one\n * handle unwraps the `sequence` again, and puts a `handleApp` back the way it\n * was written, so enabling then disabling a pattern round-trips.\n *\n * Nothing here formats or saves: callers do, as they always have. A result of\n * `unsupported` means the file was left exactly as it was found.\n */\n\nconst KIT_HOOKS = \"@sveltejs/kit/hooks\";\nconst EXTRACTED = \"handleApp\";\n\nexport interface HandleSpec {\n /** Source text of the sequence argument: `handleWuchale`, `handlePocketbase({ ... })`. */\n expression: string;\n /** Identifier, or callee identifier, that marks this handle. Defaults to `expression`. */\n name?: string;\n /** Where it goes in the chain. */\n position?: \"first\" | \"last\";\n}\n\nexport type Unsupported =\n /** `export { handle } from '…'`, `export { x as handle }`, or `export *` with no local handle. */\n | \"re-export\"\n /** A local `handle` SvelteKit cannot see. */\n | \"not-exported\"\n /** `export const { handle } = …` */\n | \"destructured\"\n /** `export default function handle` */\n | \"default-export\"\n /** `export let handle;` */\n | \"no-initializer\"\n /** A `sequence` in scope that is not `@sveltejs/kit/hooks`'. */\n | \"foreign-sequence\"\n /** The handle has to move to `handleApp`, and the name is taken. */\n | \"name-collision\"\n /** The handle has to move to `handleApp`, and shares its statement with other declarations. */\n | \"multi-declarator\"\n /** The handle is referenced outside the composition (`dev ? a : handleX`, or inside a function handle). */\n | \"ambiguous-reference\";\n\nexport type ComposeResult =\n /** `statement` is the `handle` declaration, when there still is one. */\n | { status: \"changed\"; statement?: Statement }\n | { status: \"unchanged\"; statement?: Statement }\n | { status: \"unsupported\"; reason: Unsupported };\n\ntype Site =\n | {\n kind: \"variable\";\n decl: VariableDeclaration;\n statement: VariableStatement;\n inlineExport: boolean;\n }\n | { kind: \"function\"; fn: FunctionDeclaration; inlineExport: boolean };\n\ntype Located =\n { site: Site | null; starExport: boolean } | { unsupported: Unsupported };\n\n/** A `sequence(...)` argument with the comments that belong to it. */\ninterface Piece {\n leading: string[];\n text: string;\n trailing: string[];\n}\n\n/** How `sequence` from `@sveltejs/kit/hooks` is bound in this file, if at all. */\ninterface KitSequence {\n local: string | null;\n namespace: string | null;\n}\n\n/** Find the exported `handle`, or say why it cannot be composed. */\nfunction locate(sf: SourceFile): Located {\n let exportedBySpecifier = false;\n let starExport = false;\n\n for (const ed of sf.getExportDeclarations()) {\n const fromModule = ed.getModuleSpecifier() !== undefined;\n if (ed.isNamespaceExport()) {\n if (ed.getNamespaceExport()?.getName() === \"handle\") {\n return { unsupported: \"re-export\" };\n }\n if (fromModule) starExport = true;\n continue;\n }\n for (const spec of ed.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== \"handle\") continue;\n if (fromModule || spec.getName() !== \"handle\") {\n return { unsupported: \"re-export\" };\n }\n exportedBySpecifier = true;\n }\n }\n\n const fn = sf.getFunctions().find((f) => f.getName() === \"handle\");\n if (fn) {\n if (fn.isDefaultExport()) return { unsupported: \"default-export\" };\n if (!fn.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n return {\n site: { kind: \"function\", fn, inlineExport: fn.hasExportKeyword() },\n starExport,\n };\n }\n\n for (const statement of sf.getVariableStatements()) {\n for (const decl of statement.getDeclarations()) {\n const nameNode = decl.getNameNode();\n if (!Node.isIdentifier(nameNode)) {\n const bindsHandle = nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === \"handle\");\n if (bindsHandle) return { unsupported: \"destructured\" };\n continue;\n }\n if (nameNode.getText() !== \"handle\") continue;\n if (!statement.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n if (!decl.getInitializer()) return { unsupported: \"no-initializer\" };\n return {\n site: {\n kind: \"variable\",\n decl,\n statement,\n inlineExport: statement.hasExportKeyword(),\n },\n starExport,\n };\n }\n }\n\n // `export { handle }` naming something that is not a local variable or\n // function: an import passed straight through, or a class.\n if (exportedBySpecifier) return { unsupported: \"re-export\" };\n return { site: null, starExport };\n}\n\nfunction kitSequence(sf: SourceFile): KitSequence {\n const found: KitSequence = { local: null, namespace: null };\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getModuleSpecifierValue() !== KIT_HOOKS || decl.isTypeOnly()) {\n continue;\n }\n const namespace = decl.getNamespaceImport();\n if (namespace) found.namespace = namespace.getText();\n for (const named of decl.getNamedImports()) {\n if (named.getName() !== \"sequence\" || named.isTypeOnly()) continue;\n found.local = named.getAliasNode()?.getText() ?? \"sequence\";\n }\n }\n return found;\n}\n\n/** Whether `name` is declared at the top level or imported. */\nfunction isBound(sf: SourceFile, name: string): boolean {\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getDefaultImport()?.getText() === name) return true;\n if (decl.getNamespaceImport()?.getText() === name) return true;\n for (const named of decl.getNamedImports()) {\n if ((named.getAliasNode()?.getText() ?? named.getName()) === name) {\n return true;\n }\n }\n }\n if (sf.getFunction(name) || sf.getClass(name) || sf.getEnum(name)) {\n return true;\n }\n return sf.getVariableDeclarations().some((d) => {\n const nameNode = d.getNameNode();\n if (Node.isIdentifier(nameNode)) return nameNode.getText() === name;\n return nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === name);\n });\n}\n\n/** The callee to write for a new `sequence(...)`, or null when none can be had. */\nfunction sequenceCallee(sf: SourceFile, kit: KitSequence): string | null {\n if (kit.local) return kit.local;\n if (kit.namespace) return `${kit.namespace}.sequence`;\n return isBound(sf, \"sequence\") ? null : \"sequence\";\n}\n\nfunction ensureSequenceImport(sf: SourceFile, kit: KitSequence): void {\n if (kit.local || kit.namespace) return;\n const decl = sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === KIT_HOOKS &&\n !d.isTypeOnly() &&\n !d.getNamespaceImport(),\n );\n // `import type { Handle } from '@sveltejs/kit/hooks'` takes `sequence` in:\n // `import { sequence, type Handle }`.\n const typeOnly = decl\n ? undefined\n : sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === KIT_HOOKS &&\n d.isTypeOnly() &&\n !d.getDefaultImport() &&\n !d.getNamespaceImport(),\n );\n if (decl) decl.addNamedImport(\"sequence\");\n else if (typeOnly) {\n const names = typeOnly.getNamedImports();\n typeOnly.setIsTypeOnly(false);\n for (const named of names) named.setIsTypeOnly(true);\n typeOnly.insertNamedImport(0, \"sequence\");\n } else {\n sf.addImportDeclaration({\n namedImports: [\"sequence\"],\n moduleSpecifier: KIT_HOOKS,\n });\n }\n}\n\nfunction pruneSequenceImport(sf: SourceFile): void {\n // ts-morph takes the blank line after the imports with a removed import.\n const { wasRemoved } = removeNamedImportIfUnused(sf, KIT_HOOKS, \"sequence\");\n if (wasRemoved) ensureBlankLineAfterImports(sf);\n}\n\nfunction isSequenceCall(node: Node, kit: KitSequence): node is CallExpression {\n if (!Node.isCallExpression(node)) return false;\n const callee = node.getExpression();\n if (Node.isIdentifier(callee)) return callee.getText() === kit.local;\n if (Node.isPropertyAccessExpression(callee)) {\n return (\n kit.namespace !== null &&\n callee.getExpression().getText() === kit.namespace &&\n callee.getName() === \"sequence\"\n );\n }\n return false;\n}\n\n/** Strip `( )`, `satisfies T`, `as T`, `<T>` and `!` down to the composition. */\nfunction unwrap(node: Expression): Expression {\n for (;;) {\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isSatisfiesExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isTypeAssertion(node) ||\n Node.isNonNullExpression(node)\n ) {\n node = node.getExpression();\n } else {\n return node;\n }\n }\n}\n\n/** `name`, or a call of `name`: `handleWuchale`, `handlePocketbase({ ... })`. */\nfunction isHandle(node: Node, name: string): boolean {\n if (Node.isIdentifier(node)) return node.getText() === name;\n if (Node.isCallExpression(node)) {\n const callee = node.getExpression();\n return Node.isIdentifier(callee) && callee.getText() === name;\n }\n return false;\n}\n\n/** The chain of `sequence` calls down to the argument that is `name`. */\nfunction findInSequence(\n node: Node,\n name: string,\n kit: KitSequence,\n): { calls: CallExpression[]; index: number } | null {\n if (!isSequenceCall(node, kit)) return null;\n const args = node.getArguments();\n const index = args.findIndex((arg) => isHandle(arg, name));\n if (index >= 0) return { calls: [node], index };\n for (const arg of args) {\n const inner = findInSequence(arg, name, kit);\n if (inner) return { calls: [node, ...inner.calls], index: inner.index };\n }\n return null;\n}\n\nfunction references(node: Node, name: string): boolean {\n if (Node.isIdentifier(node) && node.getText() === name) return true;\n return node\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === name);\n}\n\nfunction commentTexts(text: string, ranges: ts.CommentRange[]): string[] {\n return ranges.map((r) => text.slice(r.pos, r.end));\n}\n\n/**\n * The arguments of a `sequence(...)` call, each with its comments. A comment\n * after an argument's comma on the same line is that argument's; comments on\n * the lines above an argument are its own too.\n */\nfunction pieces(call: CallExpression): Piece[] {\n const text = call.getSourceFile().getFullText();\n const args = call.getArguments();\n const openParen = call.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken);\n const closeParen = call.getLastChildByKindOrThrow(SyntaxKind.CloseParenToken);\n\n const result = args.map((arg, i): Piece => {\n let leadingFrom = openParen.getEnd();\n if (i > 0) {\n const prevComma = args[i - 1].getNextSiblingIfKind(SyntaxKind.CommaToken);\n leadingFrom = prevComma?.getEnd() ?? args[i - 1].getEnd();\n const prevTrailing = ts.getTrailingCommentRanges(text, leadingFrom);\n if (prevTrailing?.length) {\n leadingFrom = prevTrailing[prevTrailing.length - 1].end;\n }\n }\n const leading = (\n ts.getLeadingCommentRanges(text, leadingFrom) ?? []\n ).filter((r) => r.end <= arg.getStart());\n const comma = arg.getNextSiblingIfKind(SyntaxKind.CommaToken);\n const trailing =\n ts.getTrailingCommentRanges(text, comma?.getEnd() ?? arg.getEnd()) ?? [];\n return {\n leading: commentTexts(text, leading),\n text: arg.getText(),\n trailing: commentTexts(text, trailing),\n };\n });\n\n // Comments on their own lines just before `)` go with the last argument.\n const last = result[result.length - 1];\n if (last) {\n const lastArg = args[args.length - 1];\n let from =\n lastArg.getNextSiblingIfKind(SyntaxKind.CommaToken)?.getEnd() ??\n lastArg.getEnd();\n const sameLine = ts.getTrailingCommentRanges(text, from);\n if (sameLine?.length) from = sameLine[sameLine.length - 1].end;\n const dangling = (ts.getLeadingCommentRanges(text, from) ?? []).filter(\n (r) => r.end <= closeParen.getStart(),\n );\n last.trailing.push(...commentTexts(text, dangling));\n }\n return result;\n}\n\nfunction hasComments(list: Piece[]): boolean {\n return list.some((p) => p.leading.length > 0 || p.trailing.length > 0);\n}\n\nfunction renderCall(callee: string, list: Piece[], multiline: boolean): string {\n if (!multiline && !hasComments(list)) {\n return `${callee}(${list.map((p) => p.text).join(\", \")})`;\n }\n const lines = list.map((p) => {\n const leading = p.leading.map((c) => `${c}\\n`).join(\"\");\n const trailing = p.trailing.length ? ` ${p.trailing.join(\" \")}` : \"\";\n return `${leading}${p.text},${trailing}`;\n });\n return `${callee}(\\n${lines.join(\"\\n\")}\\n)`;\n}\n\n/** A lone argument taken out of a nested `sequence`: its comments go above it. */\nfunction renderAlone(piece: Piece): string {\n const comments = [...piece.leading, ...piece.trailing];\n return comments.map((c) => `${c}\\n`).join(\"\") + piece.text;\n}\n\nfunction isMultiline(call: CallExpression): boolean {\n return call\n .getArguments()\n .some((arg, i, args) =>\n i === 0\n ? false\n : arg.getStartLineNumber() !== args[i - 1].getEndLineNumber(),\n );\n}\n\nfunction rewriteSequence(call: CallExpression, list: Piece[]): Node {\n const multiline = isMultiline(call);\n return call.replaceWithText(\n renderCall(call.getExpression().getText(), list, multiline),\n );\n}\n\nfunction handleStatement(site: Site): Statement {\n return site.kind === \"function\" ? site.fn : site.statement;\n}\n\n/** The `handle` statement as it stands now; nodes go stale on every edit. */\nfunction currentStatement(sf: SourceFile): Statement | undefined {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return undefined;\n return handleStatement(located.site);\n}\n\nfunction changed(sf: SourceFile): ComposeResult {\n return { status: \"changed\", statement: currentStatement(sf) };\n}\n\nfunction unchanged(site: Site | null): ComposeResult {\n return {\n status: \"unchanged\",\n statement: site ? handleStatement(site) : undefined,\n };\n}\n\nfunction unsupported(reason: Unsupported): ComposeResult {\n return { status: \"unsupported\", reason };\n}\n\n/**\n * Take the whole `handle` out: its declarator, or its statement with the\n * comments above it, and an `export { handle }` naming it.\n */\nfunction removeWholeHandle(sf: SourceFile, site: Site): void {\n const viaSpecifier = !site.inlineExport;\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n site.decl.remove();\n } else {\n removeStatementWithComments(sf, handleStatement(site));\n }\n if (!viaSpecifier) return;\n for (const ed of sf.getExportDeclarations()) {\n if (ed.getModuleSpecifier() !== undefined) continue;\n const spec = ed.getNamedExports().find((s) => s.getName() === \"handle\");\n if (!spec) continue;\n if (ed.getNamedExports().length === 1) ed.remove();\n else spec.remove();\n }\n}\n\n/**\n * Move a handle that is a function out of the way: rename it `handleApp`,\n * un-export it, and export `sequence(...)` of it right after, so `handleApp`\n * is declared before anything reads it.\n */\nfunction extract(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n callee: string,\n kit: KitSequence,\n): ComposeResult {\n const position = spec.position ?? \"first\";\n const args =\n position === \"first\"\n ? [spec.expression, EXTRACTED]\n : [EXTRACTED, spec.expression];\n const exportKeyword = site.inlineExport ? \"export \" : \"\";\n const composed = `${exportKeyword}const handle = ${callee}(${args.join(\", \")});`;\n\n if (site.kind === \"function\") {\n if (site.inlineExport) site.fn.setIsExported(false);\n sf.getFunctionOrThrow(\"handle\").getNameNode()!.replaceWithText(EXTRACTED);\n const fn = sf.getFunctionOrThrow(EXTRACTED);\n sf.insertText(fn.getEnd(), `\\n\\n${composed}`);\n } else {\n if (site.inlineExport) site.statement.setIsExported(false);\n sf.getVariableDeclarationOrThrow(\"handle\")\n .getNameNode()\n .replaceWithText(EXTRACTED);\n const statement = sf.getVariableStatementOrThrow(EXTRACTED);\n sf.insertText(statement.getEnd(), `\\n\\n${composed}`);\n }\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\n/**\n * After a `sequence` unwraps to `handleApp` alone, put the function back the\n * way `extract` found it: `handleApp` renamed to `handle` and exported, and\n * the `handle = handleApp` statement gone.\n */\nfunction restoreExtracted(sf: SourceFile): void {\n const located = locate(sf);\n if (\"unsupported\" in located || located.site?.kind !== \"variable\") return;\n const { decl, statement, inlineExport } = located.site;\n const init = decl.getInitializer();\n if (\n !init ||\n !Node.isIdentifier(init) ||\n init.getText() !== EXTRACTED ||\n decl.getTypeNode() ||\n statement.getDeclarations().length > 1\n ) {\n return;\n }\n\n const uses = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .filter((id) => id.getText() === EXTRACTED);\n // Its declaration and the one use in `handle`.\n if (uses.length !== 2) return;\n\n const fn = sf.getFunction(EXTRACTED);\n const variable = sf.getVariableStatements().find((s) => {\n const decls = s.getDeclarations();\n return decls.length === 1 && decls[0].getName() === EXTRACTED;\n });\n const target = fn ?? variable;\n if (!target || target.hasExportKeyword()) return;\n\n statement.remove();\n if (fn) {\n const restored = sf.getFunctionOrThrow(EXTRACTED);\n restored.getNameNode()!.replaceWithText(\"handle\");\n if (inlineExport) sf.getFunctionOrThrow(\"handle\").setIsExported(true);\n } else {\n const restored = sf.getVariableDeclarationOrThrow(EXTRACTED);\n restored.getNameNode().replaceWithText(\"handle\");\n if (inlineExport) {\n sf.getVariableStatementOrThrow(\"handle\").setIsExported(true);\n }\n }\n}\n\n/**\n * Add a handle to the exported `handle`. Already present anywhere in the\n * composition: unchanged. No `handle` yet: `export const handle = <expression>`.\n */\nexport function addHandle(sf: SourceFile, spec: HandleSpec): ComposeResult {\n const name = spec.name ?? spec.expression;\n const position = spec.position ?? \"first\";\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n const kit = kitSequence(sf);\n\n if (!site) {\n if (located.starExport) return unsupported(\"re-export\");\n const blank = sf.getStatementsWithComments().length > 0 ? \"\\n\" : \"\";\n sf.addStatements(`${blank}export const handle = ${spec.expression};`);\n return changed(sf);\n }\n\n if (site.kind === \"function\") {\n if (references(site.fn, name)) return unsupported(\"ambiguous-reference\");\n return extractChecked(sf, site, spec, kit);\n }\n\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name) || findInSequence(core, name, kit)) {\n return unchanged(site);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n\n if (isSequenceCall(core, kit)) {\n const list = pieces(core);\n const piece: Piece = { leading: [], text: spec.expression, trailing: [] };\n if (position === \"first\") list.unshift(piece);\n else list.push(piece);\n rewriteSequence(core, list);\n return changed(sf);\n }\n\n if (Node.isArrowFunction(core) || Node.isFunctionExpression(core)) {\n return extractChecked(sf, site, spec, kit);\n }\n\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const existing = core.getText();\n const args =\n position === \"first\"\n ? [spec.expression, existing]\n : [existing, spec.expression];\n const multiline = args.some((a) => a.includes(\"\\n\"));\n core.replaceWithText(\n renderCall(\n callee,\n args.map((text) => ({ leading: [], text, trailing: [] })),\n multiline,\n ),\n );\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\nfunction extractChecked(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n kit: KitSequence,\n): ComposeResult {\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const taken = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === EXTRACTED);\n if (taken) return unsupported(\"name-collision\");\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n return unsupported(\"multi-declarator\");\n }\n return extract(sf, site, spec, callee, kit);\n}\n\n/**\n * Take a handle out of the exported `handle`. A `sequence` left with one\n * argument unwraps to it; the last handle takes the `handle` export with it.\n */\nexport function removeHandle(sf: SourceFile, name: string): ComposeResult {\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site) return unchanged(null);\n\n if (site.kind === \"function\") {\n return references(site.fn, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name)) {\n removeWholeHandle(sf, site);\n pruneSequenceImport(sf);\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (!found) {\n return references(core, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n // Innermost call first; a nested `sequence` emptied by the removal is in\n // turn removed from the one around it.\n const calls = [...found.calls];\n let index = found.index;\n for (;;) {\n const call = calls.pop()!;\n const list = pieces(call);\n list.splice(index, 1);\n const outer = calls[calls.length - 1];\n\n if (list.length === 0) {\n if (!outer) {\n removeWholeHandle(sf, site);\n break;\n }\n index = outer.getArguments().indexOf(call);\n continue;\n }\n if (list.length === 1 && outer) {\n call.replaceWithText(renderAlone(list[0]));\n break;\n }\n if (list.length === 1) {\n // `handle = sequence(x)` unwraps to `handle = x`, and x's comments move\n // above the statement rather than dangle after the `=`.\n const [kept] = list;\n const comments = [...kept.leading, ...kept.trailing];\n call.replaceWithText(kept.text);\n if (comments.length === 0) restoreExtracted(sf);\n else {\n const statement = currentStatement(sf)!;\n sf.insertText(\n statement.getStart(true),\n comments.map((c) => `${c}\\n`).join(\"\"),\n );\n }\n break;\n }\n rewriteSequence(call, list);\n break;\n }\n\n pruneSequenceImport(sf);\n return changed(sf);\n}\n\n/**\n * Swap handle `name` for `spec` in the same place in the chain. When `name`\n * was the whole `handle`, the comments above the statement go too: they\n * described the old handle. With `name` absent this is `addHandle`.\n */\nexport function replaceHandle(\n sf: SourceFile,\n name: string,\n spec: HandleSpec,\n): ComposeResult {\n const newName = spec.name ?? spec.expression;\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site || site.kind === \"function\") return addHandle(sf, spec);\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, newName) || findInSequence(core, newName, kit)) {\n const stale = isHandle(core, name) || findInSequence(core, name, kit);\n return stale ? removeHandle(sf, name) : unchanged(site);\n }\n\n if (isHandle(core, name)) {\n core.replaceWithText(spec.expression);\n removeAttachedComments(sf, sf.getVariableStatementOrThrow(\"handle\"));\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (found) {\n const call = found.calls[found.calls.length - 1];\n const list = pieces(call);\n list[found.index] = { ...list[found.index], text: spec.expression };\n rewriteSequence(call, list);\n return changed(sf);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n return addHandle(sf, spec);\n}\n\n/**\n * The handles in the exported `handle`, in order: each argument's identifier,\n * or its callee's, or its source text. A function handle is `handle` itself.\n * `null` when there is no `handle` to compose.\n */\nexport function listHandles(sf: SourceFile): string[] | null {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return null;\n if (located.site.kind === \"function\") return [\"handle\"];\n const kit = kitSequence(sf);\n\n const names = (node: Node): string[] => {\n if (isSequenceCall(node, kit)) return node.getArguments().flatMap(names);\n if (Node.isIdentifier(node)) return [node.getText()];\n if (\n Node.isCallExpression(node) &&\n Node.isIdentifier(node.getExpression())\n ) {\n return [node.getExpression().getText()];\n }\n return [node.getText()];\n };\n return names(unwrap(located.site.decl.getInitializerOrThrow()));\n}\n"],"mappings":";;;AAiCA,IAAMI,IAAY,uBACZC,IAAY;AA+DlB,SAASC,EAAO,GAAyB;CACvC,IAAIC,IAAsB,IACtBC,IAAa;CAEjB,KAAK,IAAMC,KAAMC,EAAG,sBAAsB,GAAG;EAC3C,IAAMC,IAAaF,EAAG,mBAAmB,MAAM,KAAA;EAC/C,IAAIA,EAAG,kBAAkB,GAAG;GAC1B,IAAIA,EAAG,mBAAmB,CAAC,EAAE,QAAQ,MAAM,UACzC,OAAO,EAAE,aAAa,YAAY;GAEpC,AAAIE,MAAY,IAAa;GAC7B;EACF;EACA,KAAK,IAAMC,KAAQH,EAAG,gBAAgB,GAEpC,KADiBG,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAK,QAAQ,OAC/C,UACjB;OAAID,KAAcC,EAAK,QAAQ,MAAM,UACnC,OAAO,EAAE,aAAa,YAAY;GAEpC,IAAsB;EAFc;CAIxC;CAEA,IAAMC,IAAKH,EAAG,aAAa,CAAC,CAAC,MAAM,MAAMI,EAAE,QAAQ,MAAM,QAAQ;CACjE,IAAID,GAKF,OAJIA,EAAG,gBAAgB,IAAU,EAAE,aAAa,iBAAiB,IAC7D,CAACA,EAAG,iBAAiB,KAAK,CAACN,IACtB,EAAE,aAAa,eAAe,IAEhC;EACL,MAAM;GAAE,MAAM;GAAY;GAAI,cAAcM,EAAG,iBAAiB;EAAE;EAClE;CACF;CAGF,KAAK,IAAME,KAAaL,EAAG,sBAAsB,GAC/C,KAAK,IAAMM,KAAQD,EAAU,gBAAgB,GAAG;EAC9C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AE,GACpB0F,IAAO9D,EAAOyC,EAAK,KAAK,sBAAsB,CAAC;CACrD,IAAIxC,EAAS6D,GAAMS,CAAO,KAAKrE,EAAe4D,GAAMS,GAAShF,CAAG,GAE9D,OADcU,EAAS6D,GAAM1E,CAAI,KAAKc,EAAe4D,GAAM1E,GAAMG,CAAG,IACrD0E,EAAa7F,GAAIgB,CAAI,IAAIyD,EAAUJ,CAAI;CAGxD,IAAIxC,EAAS6D,GAAM1E,CAAI,GAGrB,OAFA0E,EAAK,gBAAgBxF,EAAK,UAAU,GACpCX,EAAuBS,GAAIA,EAAG,4BAA4B,QAAQ,CAAC,GAC5DwE,EAAQxE,CAAE;CAGnB,IAAMY,IAAQkB,EAAe4D,GAAM1E,GAAMG,CAAG;CAC5C,IAAIP,GAAO;EACT,IAAM8B,IAAO9B,EAAM,MAAMA,EAAM,MAAM,SAAS,IACxC8C,IAAOjB,EAAOC,CAAI;EAGxB,OAFA,EAAK9B,EAAM,SAAS;GAAE,GAAG8C,EAAK9C,EAAM;GAAQ,MAAMV,EAAK;EAAW,GAClEiE,EAAgBzB,GAAMgB,CAAI,GACnBc,EAAQxE,CAAE;CACnB;CAEA,OADImC,EAAWuD,GAAM1E,CAAI,IAAU0D,EAAY,qBAAqB,IAC7DY,EAAUtF,GAAIE,CAAI;AAC3B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as e } from "./ts-morph-helpers-
|
|
1
|
+
import { o as e } from "./ts-morph-helpers-Bepc-Es2.js";
|
|
2
2
|
import t from "node:fs";
|
|
3
3
|
import n from "node:path";
|
|
4
4
|
import { Project as r, QuoteKind as i, SyntaxKind as a } from "ts-morph";
|
|
@@ -150,4 +150,4 @@ function _(e, t, n) {
|
|
|
150
150
|
//#endregion
|
|
151
151
|
export { u as a, _ as i, p as n, h as o, f as r, g as s, o as t };
|
|
152
152
|
|
|
153
|
-
//# sourceMappingURL=config-target-
|
|
153
|
+
//# sourceMappingURL=config-target-rHgjaA8u.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-target-rHgjaA8u.js","names":["formatLikeSource","fs","path","VITE_CONFIG_CANDIDATES","SVELTE_CONFIG_CANDIDATES","SVELTE_CONFIG_MESSAGE","KIT_NESTING_MESSAGE","probeFirstExisting","rel","candidates","abs","root","newProject","Project","QuoteKind","getOrCreateObjectLiteralProperty","prop","obj","name","added","SyntaxKind","init","initializer","init2","ensureBooleanTrue","existing","findSveltekitCall","sourceFile","ce","resolveConfigTarget","notFound","hints","failed","sveltePath","vitePath","originalText","call","arg","created","configObject","saveTarget","target","modifyConfig","res","mutate"],"sources":["../../src/runtime/config-target.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type CallExpression,\n type ObjectLiteralExpression,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../core/types\";\nimport { formatLikeSource } from \"./ts-morph-helpers\";\n\nexport const VITE_CONFIG_CANDIDATES = [\n \"vite.config.ts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n \"vite.config.cjs\",\n];\n\n/** SvelteKit 2's config files; SvelteKit 3 refuses to start with any of them. */\nexport const SVELTE_CONFIG_CANDIDATES = [\n \"svelte.config.ts\",\n \"svelte.config.js\",\n \"svelte.config.mjs\",\n \"svelte.config.cjs\",\n];\n\n/**\n * The message every pattern prints for a project still on SvelteKit 2's\n * `svelte.config.*`. SvelteKit 3 refuses to start with one, so editing it\n * would be pointless; the migration moves it into `vite.config.ts`.\n */\nexport const SVELTE_CONFIG_MESSAGE =\n \"SvelteKit 3 no longer reads svelte.config.* — run `npx vela@^0.15 migrate sveltekit-3` to move it into vite.config.ts.\";\n\n/** SvelteKit 3 fails on a leftover `kit: {...}` inside the `sveltekit()` arg. */\nexport const KIT_NESTING_MESSAGE =\n \"SvelteKit 3 reads its options at the top level of sveltekit({...}), not under `kit:` — run `npx vela@^0.15 migrate sveltekit-3` to move them.\";\n\n/**\n * Where SvelteKit 3 reads its configuration: the inline argument object of the\n * `sveltekit()` call in `vite.config.*`. The former `kit.*` options (adapter,\n * alias, experimental, paths, ...) sit at its top level, beside\n * `compilerOptions`, `preprocess` and `extensions`.\n */\nexport interface ConfigTarget {\n /** The file to add imports to and save. */\n sourceFile: SourceFile;\n /** Absolute path of the resolved file. */\n filePath: string;\n /** The `sveltekit()` arg object. */\n configObject: ObjectLiteralExpression;\n /** Full text captured before any mutation, for change detection. */\n originalText: string;\n /**\n * The `sveltekit()` call when resolving it added the `{}` arg; saving drops\n * that arg again while it is still empty.\n */\n addedArgTo?: CallExpression;\n}\n\n/** Why a config could not be resolved for editing. */\nexport type ConfigFailure =\n /** A `svelte.config.*` exists: a SvelteKit 2 project that needs migrating. */\n | \"svelte-config\"\n /** The `sveltekit()` arg still nests options under `kit:`. */\n | \"kit-nesting\"\n /** The `sveltekit()` arg is not an object literal (`sveltekit(config)`). */\n | \"non-object-arg\";\n\nexport type ResolveResult =\n | { status: \"resolved\"; target: ConfigTarget }\n | { status: \"not-found\"; message: string; filePath: string }\n | {\n status: \"failed\";\n reason: ConfigFailure;\n message: string;\n filePath: string;\n };\n\n/** Result shape returned by every config modifier so call sites can build a File. */\nexport interface ConfigModifyResult {\n filePath: string;\n outcome: ModifyOutcome;\n}\n\n/** First candidate that exists under `root`, or null. */\nexport function probeFirstExisting(\n root: string,\n candidates: string[],\n): string | null {\n for (const rel of candidates) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/**\n * Get the object-literal value of property `name` on `obj`, creating it as an\n * empty object if missing (or replacing a non-object initializer). Returns null\n * if the property can't be coerced to an object literal.\n */\nexport function getOrCreateObjectLiteralProperty(\n obj: ObjectLiteralExpression,\n name: string,\n initializer: string,\n): ObjectLiteralExpression | null {\n const prop = obj.getProperty(name);\n if (!prop) {\n obj.addPropertyAssignment({ name, initializer });\n const added = obj.getProperty(name);\n if (!added || added.getKind() !== SyntaxKind.PropertyAssignment)\n return null;\n const init = (\n added as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ObjectLiteralExpression)\n return null;\n return init as ObjectLiteralExpression;\n }\n\n if (prop.getKind() !== SyntaxKind.PropertyAssignment) return null;\n const init = (prop as import(\"ts-morph\").PropertyAssignment).getInitializer();\n if (!init) return null;\n if (init.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n (prop as import(\"ts-morph\").PropertyAssignment).setInitializer(initializer);\n const init2 = (\n prop as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n return init2 && init2.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (init2 as ObjectLiteralExpression)\n : null;\n }\n\n return init as ObjectLiteralExpression;\n}\n\n/** Ensure `obj[name] === true`. Returns whether a change was made. */\nexport function ensureBooleanTrue(\n obj: ObjectLiteralExpression,\n name: string,\n): boolean {\n const existing = obj.getProperty(name);\n if (!existing) {\n obj.addPropertyAssignment({ name, initializer: \"true\" });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (init?.getText() === \"true\") return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\"true\");\n return true;\n}\n\nfunction findSveltekitCall(sourceFile: SourceFile): CallExpression | null {\n return (\n sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"sveltekit\") ?? null\n );\n}\n\n/**\n * Resolve the `sveltekit()` arg in `vite.config.*` for editing:\n * - any `svelte.config.*` → failed (`svelte-config`), even when the inline\n * arg exists too: SvelteKit 3 refuses to start until it is gone;\n * - an object arg with a `kit:` property → failed (`kit-nesting`);\n * - an object arg → resolved;\n * - a bare `sveltekit()` → `{}` is added and resolved;\n * - any other arg → failed (`non-object-arg`);\n * - no vite config, or no `sveltekit()` call in it → not-found.\n *\n * `hints.failed` is the message for a shape that can't be edited; the\n * `svelte-config` and `kit-nesting` failures always carry the migrate message.\n */\nexport function resolveConfigTarget(\n root: string,\n hints?: { notFound?: string; failed?: string },\n): ResolveResult {\n const notFound = hints?.notFound ?? \"Could not find a Vite config to modify.\";\n const failed = hints?.failed ?? \"Could not modify the Vite config.\";\n\n const sveltePath = probeFirstExisting(root, SVELTE_CONFIG_CANDIDATES);\n if (sveltePath) {\n return {\n status: \"failed\",\n reason: \"svelte-config\",\n message: SVELTE_CONFIG_MESSAGE,\n filePath: sveltePath,\n };\n }\n\n const vitePath = probeFirstExisting(root, VITE_CONFIG_CANDIDATES);\n if (!vitePath) {\n return {\n status: \"not-found\",\n message: notFound,\n filePath: path.join(root, VITE_CONFIG_CANDIDATES[0]),\n };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(vitePath);\n const originalText = sourceFile.getFullText();\n const call = findSveltekitCall(sourceFile);\n if (!call) {\n return { status: \"not-found\", message: notFound, filePath: vitePath };\n }\n\n const arg = call.getArguments()[0];\n if (!arg) {\n const created = call\n .addArgument(\"{}\")\n .asKind(SyntaxKind.ObjectLiteralExpression);\n if (!created) {\n return {\n status: \"failed\",\n reason: \"non-object-arg\",\n message: failed,\n filePath: vitePath,\n };\n }\n return {\n status: \"resolved\",\n target: {\n sourceFile,\n filePath: vitePath,\n configObject: created,\n originalText,\n addedArgTo: call,\n },\n };\n }\n\n const configObject = arg.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!configObject) {\n return {\n status: \"failed\",\n reason: \"non-object-arg\",\n message: failed,\n filePath: vitePath,\n };\n }\n if (configObject.getProperty(\"kit\")) {\n return {\n status: \"failed\",\n reason: \"kit-nesting\",\n message: KIT_NESTING_MESSAGE,\n filePath: vitePath,\n };\n }\n return {\n status: \"resolved\",\n target: { sourceFile, filePath: vitePath, configObject, originalText },\n };\n}\n\n/**\n * Format, compare against the captured original, and save only if changed.\n * A `{}` that resolving added to a bare `sveltekit()` is taken out again when\n * nothing went into it, so a no-op edit reports unchanged.\n */\nexport function saveTarget(target: ConfigTarget): ModifyOutcome {\n if (target.addedArgTo && target.configObject.getProperties().length === 0) {\n target.addedArgTo.removeArgument(0);\n }\n formatLikeSource(target.sourceFile);\n const newText = target.sourceFile.getFullText();\n if (newText === target.originalText) {\n return { status: \"success\", changed: false };\n }\n target.sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n\n/**\n * Resolve a config target and run `mutate` against it. Handles the\n * not-found/failed branches and change detection uniformly. `mutate` returns\n * `false` when the config shape can't be safely edited (→ failed).\n */\nexport function modifyConfig(\n root: string,\n hints: { notFound: string; failed: string },\n mutate: (target: ConfigTarget) => boolean,\n): ConfigModifyResult {\n const res = resolveConfigTarget(root, hints);\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const ok = mutate(res.target);\n if (!ok) {\n return {\n filePath: res.target.filePath,\n outcome: { status: \"failed\", message: hints.failed },\n };\n }\n return { filePath: res.target.filePath, outcome: saveTarget(res.target) };\n}\n"],"mappings":";;;;;AAaA,IAAaG,IAAyB;CACpC;CACA;CACA;CACA;AACF,GAGaC,IAA2B;CACtC;CACA;CACA;CACA;AACF,GAOaC,IACX,0HAGWC,IACX;AAkDF,SAAgBC,EACd,GACA,GACe;CACf,KAAK,IAAMC,KAAOC,GAAY;EAC5B,IAAMC,IAAMR,EAAK,KAAKS,GAAMH,CAAG;EAC/B,IAAIP,EAAG,WAAWS,CAAG,GAAG,OAAOA;CACjC;CACA,OAAO;AACT;AAEA,SAASE,IAAsB;CAC7B,OAAO,IAAIC,EAAQ;EACjB,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAWC,EAAU,OAAO;CACtD,CAAC;AACH;AAOA,SAAgBC,EACd,GACA,GACA,GACgC;CAChC,IAAMC,IAAOC,EAAI,YAAYC,CAAI;CACjC,IAAI,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;CACpB,IAAMC,IAAMd,EAAoBlB,GAAMoB,CAAK;CAc3C,OAbIY,EAAI,WAAW,aAMRC,EAAOD,EAAI,MACjB,IAME;EAAE,UAAUA,EAAI,OAAO;EAAU,SAASH,EAAWG,EAAI,MAAM;CAAE,IAL/D;EACL,UAAUA,EAAI,OAAO;EACrB,SAAS;GAAE,QAAQ;GAAU,SAASZ,EAAM;EAAO;CACrD,IAVO;EACL,UAAUY,EAAI;EACd,SAAS;GAAE,QAAQA,EAAI;GAAQ,SAASA,EAAI;EAAQ;CACtD;AAUJ"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/core/constants.ts
|
|
2
|
-
var e = "data", t = "migrations", n = "(public)", r = "(app)", i = "@tanstack/table-core@^9.2.4", a = "formsnap@^2.0.1", o = "3.0.0-next.1", s = `sveltekit-superforms@${o}`, c = { formsnap: { "sveltekit-superforms": o } }, l = "sveltekit-flash-message@3.0.0-next.0", u = "@sveltejs/adapter-node@^6.0.0", d = "@sveltejs/adapter-static@^4.0.0", f = "@velastack/kit@^0.4.0", p = "@velastack/pocketbase@^0.4.
|
|
2
|
+
var e = "data", t = "migrations", n = "(public)", r = "(app)", i = "@tanstack/table-core@^9.2.4", a = "formsnap@^2.0.1", o = "3.0.0-next.1", s = `sveltekit-superforms@${o}`, c = { formsnap: { "sveltekit-superforms": o } }, l = "sveltekit-flash-message@3.0.0-next.0", u = "@sveltejs/adapter-node@^6.0.0", d = "@sveltejs/adapter-static@^4.0.0", f = "@velastack/kit@^0.4.0", p = "@velastack/pocketbase@^0.4.2", m = "@velastack/cms@^0.6.0", h = "sveltekit-negotiate@^0.3.0", g = "zod@^4.1.11", _ = "wuchale@^0.26.3", v = "@wuchale/svelte@^0.21.1";
|
|
3
3
|
//#endregion
|
|
4
4
|
export { _, l as a, t as c, s as d, o as f, p as g, f as h, e as i, h as l, m, d as n, a as o, i as p, r, c as s, u as t, n as u, v, g as y };
|
|
5
5
|
|
|
6
|
-
//# sourceMappingURL=constants-
|
|
6
|
+
//# sourceMappingURL=constants-Rq8SCXwH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants-Rq8SCXwH.js","names":["DATA_DIR","MIGRATIONS_DIR","PUBLIC_DIR","APP_DIR","TANSTACK_TABLE_CORE","FORMSNAP","SUPERFORMS_VERSION","SUPERFORMS","FORMSNAP_OVERRIDES","FLASH","ADAPTER_NODE","ADAPTER_STATIC","VELASTACK_KIT","VELASTACK_POCKETBASE","VELASTACK_CMS","NEGOTIATE","ZOD","WUCHALE","WUCHALE_SVELTE"],"sources":["../../src/core/constants.ts"],"sourcesContent":["export const DATA_DIR = \"data\";\nexport const MIGRATIONS_DIR = \"migrations\";\nexport const FIXTURE_PREFIX = \"vela\";\nexport const PUBLIC_DIR = \"(public)\";\nexport const APP_DIR = \"(app)\";\nexport const AUTHED_REDIRECT_PATH = \"/dashboard\";\nexport const API_URL = \"http://localhost:5173\";\n\n/**\n * The table helpers this repo ships (`data-table`, `column-header`,\n * `faceted-filter`, `pagination`) and the pages the scaffold generators emit\n * target TanStack Table v9, whose API and types are incompatible with v8; see\n * `assertTableCoreV9` for projects that still have the v8 helpers.\n */\nexport const TANSTACK_TABLE_CORE = \"@tanstack/table-core@^9.2.4\";\n\n/** The major `TANSTACK_TABLE_CORE` pins. */\nexport const TANSTACK_TABLE_CORE_MAJOR = 9;\n\n/** `file-form` and `multiselect` build on formsnap's field context. */\nexport const FORMSNAP = \"formsnap@^2.0.1\";\n\n/**\n * The superforms release that supports SvelteKit 3 (its `latest` accepts\n * only Kit 1 and 2). Installed exactly, not with a caret: a caret on a\n * prerelease would follow later `next` builds.\n */\nexport const SUPERFORMS_VERSION = \"3.0.0-next.1\";\n\n/**\n * What a generated superforms page needs. Vela's templates already carry\n * both; a project vela did not create may have neither.\n */\nexport const SUPERFORMS = `sveltekit-superforms@${SUPERFORMS_VERSION}`;\n\n/**\n * formsnap 2 peers `sveltekit-superforms ^2`, so every project that installs\n * it needs this npm override, or `npm install` fails with ERESOLVE. The value\n * is the literal version: `$sveltekit-superforms` breaks on npm 10.\n * `writeResult` adds it before any install that brings formsnap in.\n */\nexport const FORMSNAP_OVERRIDES = {\n formsnap: { \"sveltekit-superforms\": SUPERFORMS_VERSION },\n};\n\n/** The flash-message release that supports SvelteKit 3; installed exactly, like superforms. */\nexport const FLASH = \"sveltekit-flash-message@3.0.0-next.0\";\n\n/** The adapter `vela enable backend` moves a project to. */\nexport const ADAPTER_NODE = \"@sveltejs/adapter-node@^6.0.0\";\n\n/** The adapter a static project builds with (`vela disable backend`). */\nexport const ADAPTER_STATIC = \"@sveltejs/adapter-static@^4.0.0\";\n\n/** The VelaStack libraries' SvelteKit 3 releases. */\nexport const VELASTACK_KIT = \"@velastack/kit@^0.4.0\";\n/** 0.4.2 proxies plugin webhooks (pocketbase-whatsapp) to PocketBase. */\nexport const VELASTACK_POCKETBASE = \"@velastack/pocketbase@^0.4.2\";\nexport const VELASTACK_CMS = \"@velastack/cms@^0.6.0\";\nexport const NEGOTIATE = \"sveltekit-negotiate@^0.3.0\";\nexport const ZOD = \"zod@^4.1.11\";\n\n/** What `vela enable i18n` installs: wuchale and its Svelte adapter. */\nexport const WUCHALE = \"wuchale@^0.26.3\";\nexport const WUCHALE_SVELTE = \"@wuchale/svelte@^0.21.1\";\n"],"mappings":";AAAA,IAAaA,IAAW,QACXC,IAAiB,cAEjBC,IAAa,YACbC,IAAU,SAUVC,IAAsB,+BAMtBC,IAAW,mBAOXC,IAAqB,gBAMrBC,IAAa,wBAAwBD,KAQrCE,IAAqB,EAChC,UAAU,EAAE,wBAAwBF,EAAmB,EACzD,GAGaG,IAAQ,wCAGRC,IAAe,iCAGfC,IAAiB,mCAGjBC,IAAgB,yBAEhBC,IAAuB,gCACvBC,IAAgB,yBAChBC,IAAY,8BACZC,IAAM,eAGNC,IAAU,mBACVC,IAAiB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dedent-Gq6Krl4n.js","names":[],"sources":["../../node_modules/dedent/dist/dedent.mjs"],"sourcesContent":["function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nconst dedent = createDedent({});\nexport default dedent;\nfunction createDedent(options) {\n dedent.withOptions = newOptions => createDedent(_objectSpread(_objectSpread({}, options), newOptions));\n return dedent;\n function dedent(strings, ...values) {\n const raw = typeof strings === \"string\" ? [strings] : strings.raw;\n const {\n alignValues = false,\n escapeSpecialCharacters = Array.isArray(strings),\n trimWhitespace = true\n } = options;\n\n // first, perform interpolation\n let result = \"\";\n for (let i = 0; i < raw.length; i++) {\n let next = raw[i];\n if (escapeSpecialCharacters) {\n // handle escaped newlines, backticks, and interpolation characters\n next = next.replace(/\\\\\\n[ \\t]*/g, \"\").replace(/\\\\`/g, \"`\").replace(/\\\\\\$/g, \"$\").replace(/\\\\\\{/g, \"{\");\n }\n result += next;\n if (i < values.length) {\n const value = alignValues ? alignValue(values[i], result) : values[i];\n\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n result += value;\n }\n }\n\n // now strip indentation\n const lines = result.split(\"\\n\");\n let mindent = null;\n for (const l of lines) {\n const m = l.match(/^(\\s+)\\S+/);\n if (m) {\n const indent = m[1].length;\n if (!mindent) {\n // this is the first indented line\n mindent = indent;\n } else {\n mindent = Math.min(mindent, indent);\n }\n }\n }\n if (mindent !== null) {\n const m = mindent; // appease TypeScript\n result = lines\n // https://github.com/typescript-eslint/typescript-eslint/issues/7140\n // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with\n .map(l => l[0] === \" \" || l[0] === \"\\t\" ? l.slice(m) : l).join(\"\\n\");\n }\n\n // dedent eats leading and trailing whitespace too\n if (trimWhitespace) {\n result = result.trim();\n }\n\n // Unescape escapes after trimming so sequences like `\\n`, `\\t`,\n // `\\xHH` and `\\u{...}` are preserved (fixes #24)\n if (escapeSpecialCharacters) {\n result = result.replace(/\\\\n/g, \"\\n\").replace(/\\\\t/g, \"\\t\").replace(/\\\\r/g, \"\\r\").replace(/\\\\v/g, \"\\v\").replace(/\\\\b/g, \"\\b\").replace(/\\\\f/g, \"\\f\").replace(/\\\\0/g, \"\\0\").replace(/\\\\x([\\da-fA-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16))).replace(/\\\\u\\{([\\da-fA-F]{1,6})\\}/g, (_, h) => String.fromCodePoint(parseInt(h, 16))).replace(/\\\\u([\\da-fA-F]{4})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));\n }\n\n // Workaround for Bun issue with Unicode characters\n // https://github.com/oven-sh/bun/issues/8745\n if (typeof Bun !== \"undefined\") {\n result = result.replace(\n // Matches e.g. \\\\u{1f60a} or \\\\u5F1F\n /\\\\u(?:\\{([\\da-fA-F]{1,6})\\}|([\\da-fA-F]{4}))/g, (_, braced, unbraced) => {\n var _ref;\n const hex = (_ref = braced !== null && braced !== void 0 ? braced : unbraced) !== null && _ref !== void 0 ? _ref : \"\";\n return String.fromCodePoint(parseInt(hex, 16));\n });\n }\n return result;\n }\n}\n\n/**\n * Adjusts the indentation of a multi-line interpolated value to match the current line.\n */\nfunction alignValue(value, precedingText) {\n if (typeof value !== \"string\" || !value.includes(\"\\n\")) {\n return value;\n }\n const currentLine = precedingText.slice(precedingText.lastIndexOf(\"\\n\") + 1);\n const indentMatch = currentLine.match(/^(\\s+)/);\n if (indentMatch) {\n const indent = indentMatch[1];\n return value.replace(/\\n/g, `\\n${indent}`);\n }\n return value;\n}\n"],"x_google_ignoreList":[0],"mappings":";AAAA,
|
|
1
|
+
{"version":3,"file":"dedent-Gq6Krl4n.js","names":["ownKeys","keys","object","symbols","sym","_objectSpread","i","source","target","key","_defineProperty","_toPropertyKey","obj","value","_toPrimitive","arg","input","prim","res","hint","dedent","createDedent","options","newOptions","values","raw","strings","result","next","escapeSpecialCharacters","alignValues","alignValue","lines","mindent","l","m","indent","trimWhitespace","h","hex","braced","unbraced","indentMatch","precedingText"],"sources":["../../node_modules/dedent/dist/dedent.mjs"],"sourcesContent":["function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nconst dedent = createDedent({});\nexport default dedent;\nfunction createDedent(options) {\n dedent.withOptions = newOptions => createDedent(_objectSpread(_objectSpread({}, options), newOptions));\n return dedent;\n function dedent(strings, ...values) {\n const raw = typeof strings === \"string\" ? [strings] : strings.raw;\n const {\n alignValues = false,\n escapeSpecialCharacters = Array.isArray(strings),\n trimWhitespace = true\n } = options;\n\n // first, perform interpolation\n let result = \"\";\n for (let i = 0; i < raw.length; i++) {\n let next = raw[i];\n if (escapeSpecialCharacters) {\n // handle escaped newlines, backticks, and interpolation characters\n next = next.replace(/\\\\\\n[ \\t]*/g, \"\").replace(/\\\\`/g, \"`\").replace(/\\\\\\$/g, \"$\").replace(/\\\\\\{/g, \"{\");\n }\n result += next;\n if (i < values.length) {\n const value = alignValues ? alignValue(values[i], result) : values[i];\n\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n result += value;\n }\n }\n\n // now strip indentation\n const lines = result.split(\"\\n\");\n let mindent = null;\n for (const l of lines) {\n const m = l.match(/^(\\s+)\\S+/);\n if (m) {\n const indent = m[1].length;\n if (!mindent) {\n // this is the first indented line\n mindent = indent;\n } else {\n mindent = Math.min(mindent, indent);\n }\n }\n }\n if (mindent !== null) {\n const m = mindent; // appease TypeScript\n result = lines\n // https://github.com/typescript-eslint/typescript-eslint/issues/7140\n // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with\n .map(l => l[0] === \" \" || l[0] === \"\\t\" ? l.slice(m) : l).join(\"\\n\");\n }\n\n // dedent eats leading and trailing whitespace too\n if (trimWhitespace) {\n result = result.trim();\n }\n\n // Unescape escapes after trimming so sequences like `\\n`, `\\t`,\n // `\\xHH` and `\\u{...}` are preserved (fixes #24)\n if (escapeSpecialCharacters) {\n result = result.replace(/\\\\n/g, \"\\n\").replace(/\\\\t/g, \"\\t\").replace(/\\\\r/g, \"\\r\").replace(/\\\\v/g, \"\\v\").replace(/\\\\b/g, \"\\b\").replace(/\\\\f/g, \"\\f\").replace(/\\\\0/g, \"\\0\").replace(/\\\\x([\\da-fA-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16))).replace(/\\\\u\\{([\\da-fA-F]{1,6})\\}/g, (_, h) => String.fromCodePoint(parseInt(h, 16))).replace(/\\\\u([\\da-fA-F]{4})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));\n }\n\n // Workaround for Bun issue with Unicode characters\n // https://github.com/oven-sh/bun/issues/8745\n if (typeof Bun !== \"undefined\") {\n result = result.replace(\n // Matches e.g. \\\\u{1f60a} or \\\\u5F1F\n /\\\\u(?:\\{([\\da-fA-F]{1,6})\\}|([\\da-fA-F]{4}))/g, (_, braced, unbraced) => {\n var _ref;\n const hex = (_ref = braced !== null && braced !== void 0 ? braced : unbraced) !== null && _ref !== void 0 ? _ref : \"\";\n return String.fromCodePoint(parseInt(hex, 16));\n });\n }\n return result;\n }\n}\n\n/**\n * Adjusts the indentation of a multi-line interpolated value to match the current line.\n */\nfunction alignValue(value, precedingText) {\n if (typeof value !== \"string\" || !value.includes(\"\\n\")) {\n return value;\n }\n const currentLine = precedingText.slice(precedingText.lastIndexOf(\"\\n\") + 1);\n const indentMatch = currentLine.match(/^(\\s+)/);\n if (indentMatch) {\n const indent = indentMatch[1];\n return value.replace(/\\n/g, `\\n${indent}`);\n }\n return value;\n}\n"],"x_google_ignoreList":[0],"mappings":";AAAA,SAASA,EAAQ,GAAQ,GAAgB;CAAE,IAAIC,IAAO,OAA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ripe-customer.ts?raw
|
|
2
|
+
var e = "import { linkStripeCustomer } from '#lib/workflows/link-stripe-customer.js';\n\n/**\n * The user's Stripe customer id. Signup starts link-stripe-customer in the\n * background, so a user can get here before it finishes, or without it ever\n * starting (a one-time-code signup, an import). Either way this starts or\n * joins that same run (the user's id is its idempotency key, so there is still\n * one customer) and waits a little for it.\n *\n * Throws when the customer is not there in time; the caller decides whether to\n * say \"try again shortly\" or fail.\n */\nexport async function getStripeCustomerId(\n admin: App.Locals['admin'],\n user: { id: string; email?: string },\n timeoutMs = 10_000\n): Promise<string> {\n try {\n const customer = await admin\n .collection('stripe_customers')\n .getFirstListItem(admin.filter('user = {:user}', { user: user.id }));\n return customer.id;\n } catch {\n // Not linked yet.\n }\n\n const handle = await linkStripeCustomer.run(\n { userId: user.id, email: user.email || undefined },\n { idempotencyKey: user.id }\n );\n const { customerId } = await handle.result({ timeoutMs });\n return customerId;\n}\n", t = "<script lang=\"ts\" module>\n import HomeIcon from '@lucide/svelte/icons/home';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n<\/script>\n\n<script lang=\"ts\">\n import favicon from '#lib/assets/favicon.svg';\n import { site } from '#lib/site.js';\n\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n import * as Sidebar from '#lib/components/ui/sidebar/index.js';\n import type { ComponentProps } from 'svelte';\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src={favicon} alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{site.name}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} {subscription} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", n = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n import CreditCardIcon from '@lucide/svelte/icons/credit-card';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import UserAvatar from '#lib/components/user-avatar.svelte';\n import { displayName, type UserIdentity } from '#lib/user.js';\n import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';\n import * as Sidebar from '#lib/components/ui/sidebar/index.js';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n {\n title: 'Billing',\n url: '/billing',\n icon: CreditCardIcon\n }\n ]\n };\n\n let {\n user,\n // [!code highlight:1]\n subscription = null\n }: {\n user: UserIdentity & {\n id: string;\n avatar: string;\n };\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n\n // [!code highlight:1]\n const planLabel = $derived(subscription?.productName ?? 'Free');\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <UserAvatar {user} class=\"size-8 rounded-lg\" fallbackClass=\"rounded-lg\" />\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{displayName(user)}</span>\n <!-- [!code highlight:1] -->\n <span class=\"truncate text-xs text-muted-foreground\">{planLabel}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <UserAvatar {user} class=\"size-8 rounded-lg\" fallbackClass=\"rounded-lg\" />\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{displayName(user)}</span>\n <!-- [!code highlight:1] -->\n <span class=\"truncate text-xs\">{planLabel}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", r = "// [!code highlight:33]\nasync function loadActiveSubscription(locals: App.Locals, userId: string) {\n const subscriptions = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\n 'user = {:user} && (status = \"active\" || status = \"trialing\")',\n { user: userId },\n ),\n expand: \"price\",\n sort: \"-created\",\n })\n .catch(() => []);\n\n const sub = subscriptions[0];\n if (!sub) return null;\n\n const price = sub.expand?.price;\n let productName: string | null = null;\n if (price?.product) {\n const product = await locals.admin\n .collection(\"stripe_products\")\n .getOne(price.product)\n .catch(() => null);\n productName = product?.name ?? null;\n }\n\n return {\n id: sub.id,\n status: sub.status as string,\n productName,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n };\n}\n\nexport const load = async ({ locals }) => {\n const user = locals.pb.authStore.record!;\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n // [!code highlight:1]\n const subscription = await loadActiveSubscription(locals, user.id);\n\n // [!code highlight:1]\n return { user, breadcrumbs, subscription };\n};\n", i = "<script lang=\"ts\">\n import * as Sidebar from \"#lib/components/ui/sidebar/index.js\";\n import { Separator } from \"#lib/components/ui/separator/index.js\";\n import AppSidebar from \"#lib/components/app-sidebar.svelte\";\n import * as Breadcrumb from \"#lib/components/ui/breadcrumb/index.js\";\n import { page } from \"$app/state\";\n\n let breadcrumbs = $derived(page.data.breadcrumbs || []) as {\n title: string;\n url: string;\n }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:5] -->\n <AppSidebar\n user={data.user}\n \n subscription={data.subscription}\n />\n <Sidebar.Inset>\n <header class=\"flex h-16 shrink-0 items-center gap-2\">\n <div class=\"flex items-center gap-2 px-4\">\n <Sidebar.Trigger class=\"-ml-1\" />\n <Separator\n orientation=\"vertical\"\n class=\"mr-2 data-[orientation=vertical]:h-4\"\n />\n {#if breadcrumbs.length > 0}\n <Breadcrumb.Root>\n <Breadcrumb.List>\n {#if breadcrumbs.length > 1}\n {#each breadcrumbs.slice(0, -1) as breadcrumb}\n <Breadcrumb.Item>\n <Breadcrumb.Link href={breadcrumb.url}\n >{breadcrumb.title}</Breadcrumb.Link\n >\n </Breadcrumb.Item>\n <Breadcrumb.Separator />\n {/each}\n {/if}\n <Breadcrumb.Page>\n {breadcrumbs[breadcrumbs.length - 1].title}\n </Breadcrumb.Page>\n </Breadcrumb.List>\n </Breadcrumb.Root>\n {/if}\n </div>\n </header>\n <div class=\"flex flex-1 flex-col p-4 pt-0\">\n {@render children?.()}\n </div>\n </Sidebar.Inset>\n </Sidebar.Provider>\n</div>\n\n<style>\n :global(body:has(div.dashboard)) {\n background-color: var(--color-sidebar);\n }\n</style>\n", a = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"#lib/stripe.js\";\nimport { getStripeCustomerId } from \"#lib/server/stripe-customer.js\";\n\ntype RecurringInfo = {\n interval: string;\n interval_count: number;\n trial_period_days?: number | null;\n};\n\nfunction parseRecurring(value: unknown): RecurringInfo | null {\n if (!value) return null;\n if (typeof value === \"object\") return value as RecurringInfo;\n try {\n return JSON.parse(value as string) as RecurringInfo;\n } catch {\n return null;\n }\n}\n\nconst ACTIVE_SUBSCRIPTION_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n];\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n depends(\"app:billing\");\n\n let customer;\n try {\n const customerId = await getStripeCustomerId(locals.admin, user);\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(customerId);\n } catch {\n // The link-stripe-customer run has not finished yet.\n return {\n paymentMethods: [],\n user,\n billingReady: false,\n hasDefaultPaymentMethod: false,\n activeSubscription: null,\n availablePlans: [],\n };\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n const subscriptionRecords = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\"user = {:user}\", { user: user.id }),\n expand: \"price\",\n sort: \"-created\",\n });\n\n const recurringPrices = await locals.admin\n .collection(\"stripe_prices\")\n .getFullList({\n filter: locals.admin.filter(\"type = {:type} && active = true\", {\n type: \"recurring\",\n }),\n });\n\n const productIds: string[] = Array.from(\n new Set(\n recurringPrices\n .map((p) => p.product)\n .filter((id): id is string => Boolean(id)),\n ),\n );\n const productMap = new Map<string, string>();\n if (productIds.length > 0) {\n const products = await locals.admin\n .collection(\"stripe_products\")\n .getFullList({\n filter: productIds.map((id) => `id = \"${id}\"`).join(\" || \"),\n });\n for (const product of products) {\n productMap.set(product.id, product.name ?? product.id);\n }\n }\n\n const availablePlans = recurringPrices.map((price) => ({\n id: price.id,\n productName:\n (price.product && productMap.get(price.product)) ?? price.product ?? \"\",\n unitAmount: (price.unit_amount ?? 0) as number,\n currency: (price.currency ?? \"\") as string,\n recurring: parseRecurring(price.recurring),\n }));\n\n const subscriptions = subscriptionRecords.map((sub) => {\n const expanded = sub.expand?.price;\n return {\n id: sub.id,\n status: sub.status as string,\n currentPeriodStart: (sub.current_period_start as string | null) ?? null,\n currentPeriodEnd: (sub.current_period_end as string | null) ?? null,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n canceledAt: (sub.canceled_at as string | null) || null,\n priceId: sub.price as string,\n productName: expanded\n ? ((expanded.product && productMap.get(expanded.product)) ??\n expanded.product ??\n null)\n : null,\n unitAmount: expanded ? ((expanded.unit_amount ?? null) as number | null) : null,\n currency: expanded ? ((expanded.currency ?? null) as string | null) : null,\n recurring: expanded ? parseRecurring(expanded.recurring) : null,\n };\n });\n\n const activeSubscription =\n subscriptions.find((s) => ACTIVE_SUBSCRIPTION_STATUSES.includes(s.status)) ||\n null;\n\n // If the active plan isn't in the list (e.g., price was deactivated), include\n // it so it can still be shown as the current plan.\n if (\n activeSubscription &&\n !availablePlans.some((p) => p.id === activeSubscription.priceId)\n ) {\n availablePlans.push({\n id: activeSubscription.priceId,\n productName: activeSubscription.productName ?? \"\",\n unitAmount: activeSubscription.unitAmount ?? 0,\n currency: activeSubscription.currency ?? \"\",\n recurring: activeSubscription.recurring,\n });\n }\n\n availablePlans.sort((a, b) => a.unitAmount - b.unitAmount);\n\n return {\n billingReady: true,\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n hasDefaultPaymentMethod: Boolean(customer.default_payment_method),\n activeSubscription,\n availablePlans,\n };\n};\n\nasync function getUserCustomer(locals: App.Locals) {\n const user = locals.pb.authStore.record;\n if (!user) {\n return error(401, \"Unauthorized\");\n }\n let customerId: string;\n try {\n customerId = await getStripeCustomerId(locals.admin, user);\n } catch {\n return error(503, \"Billing is still being set up. Try again shortly.\");\n }\n return locals.admin.collection(\"stripe_customers\").getOne(customerId);\n}\n\n// A subscription can be updated in-place unless it has fully terminated.\nconst UPDATABLE_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n \"paused\",\n];\n\nasync function findUpdatableSubscription(\n locals: App.Locals,\n userId: string,\n) {\n const filterClause = UPDATABLE_STATUSES.map(\n (s) => `status = \"${s}\"`,\n ).join(\" || \");\n const subs = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(`user = {:user} && (${filterClause})`, {\n user: userId,\n }),\n sort: \"-created\",\n });\n return subs[0] ?? null;\n}\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n selectPlan: async ({ locals, request }) => {\n const formData = await request.formData();\n const priceId = formData.get(\"priceId\") as string;\n if (!priceId) return error(400, \"Price ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // If an updatable subscription already exists, change its price in place\n // rather than creating a duplicate. Covers switch, resume-to-different-plan,\n // and races where the webhook hasn't delivered the existing sub yet.\n const existing = await findUpdatableSubscription(locals, userId);\n if (existing) {\n const stripeSub = await stripe.subscriptions.retrieve(existing.id);\n const item = stripeSub.items.data[0];\n if (!item) return error(500, \"Subscription has no items\");\n\n await stripe.subscriptions.update(existing.id, {\n items: [{ id: item.id, price: priceId }],\n proration_behavior: \"create_prorations\",\n cancel_at_period_end: false,\n });\n return;\n }\n\n const customer = await getUserCustomer(locals);\n if (!customer.default_payment_method) {\n return error(400, \"Add a default payment method before subscribing\");\n }\n\n await stripe.subscriptions.create({\n customer: customer.id,\n items: [{ price: priceId }],\n default_payment_method: customer.default_payment_method,\n payment_behavior: \"error_if_incomplete\",\n off_session: true,\n });\n },\n cancelSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // Verify the subscription belongs to this user before touching Stripe.\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n },\n resumeSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n },\n};\n", o = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import * as Card from '#lib/components/ui/card/index.js';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import * as AlertDialog from '#lib/components/ui/alert-dialog/index.js';\n import SetupButton from '#lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check, Package } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate, refreshAll } from '$app/navigation';\n import { untrack } from 'svelte';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let availablePlans = $derived(data.availablePlans);\n let hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\n\n // Local, mutable mirror of the server-side subscription. We optimistically\n // update it on user actions so the UI reflects the change immediately; the\n // $effect re-syncs from the server after the webhook has had a chance to\n // fire (refreshAll runs on a short delay below).\n let activeSubscription = $state(untrack(() => data.activeSubscription));\n $effect(() => {\n activeSubscription = data.activeSubscription;\n });\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n let showCancelDialog = $state(false);\n let isSubscribing = $state<string | null>(null);\n let isCanceling = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n\n function formatAmount(amount: number | null, currency: string | null) {\n if (amount === null || !currency) return '—';\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currency.toUpperCase()\n }).format(amount / 100);\n }\n\n function formatInterval(recurring: { interval: string; interval_count: number } | null) {\n if (!recurring) return '';\n if (recurring.interval_count === 1) return `/ ${recurring.interval}`;\n return `every ${recurring.interval_count} ${recurring.interval}s`;\n }\n\n function formatDate(iso: string | null) {\n if (!iso) return '—';\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n });\n }\n\n async function selectPlan(priceId: string, successMessage: string) {\n if (!hasDefaultPaymentMethod) {\n toast.error('Add a default payment method first');\n return;\n }\n const previous = activeSubscription;\n const plan = availablePlans.find((p) => p.id === priceId);\n if (plan) {\n activeSubscription = previous\n ? {\n ...previous,\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false\n }\n : {\n id: 'pending',\n status: 'active',\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false,\n currentPeriodStart: null,\n currentPeriodEnd: null,\n canceledAt: null\n };\n }\n\n isSubscribing = priceId;\n try {\n const formData = new FormData();\n formData.append('priceId', priceId);\n\n const res = await fetch('?/selectPlan', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`selectPlan failed: ${res.status}`);\n }\n\n toast.success(successMessage);\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error selecting plan:', err);\n toast.error('Failed to update plan');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function subscribe(priceId: string) {\n await selectPlan(priceId, 'Subscription started');\n }\n\n async function switchPlan(priceId: string) {\n await selectPlan(priceId, 'Subscription updated');\n }\n\n async function resumeSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isSubscribing = activeSubscription.priceId;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/resumeSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Resume failed: ${res.status}`);\n }\n\n toast.success('Subscription resumed');\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error resuming subscription:', err);\n toast.error('Failed to resume subscription');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function handleCancelSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isCanceling = true;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/cancelSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Cancel failed: ${res.status}`);\n }\n\n toast.success('Subscription will cancel at period end');\n showCancelDialog = false;\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error canceling subscription:', err);\n toast.error('Failed to cancel subscription');\n activeSubscription = previous;\n } finally {\n isCanceling = false;\n }\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if !data.billingReady}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">Setting up billing</p>\n <p class=\"text-sm\">This takes a moment after signing up. Refresh to check again.</p>\n </div>\n {:else if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n {#if data.billingReady}\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n {/if}\n </Card.Root>\n </div>\n </div>\n\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Plan</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">Manage your subscription.</p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if availablePlans.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <Package class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No plans available</p>\n <p class=\"text-sm\">Check back soon.</p>\n </div>\n {:else}\n {#if !hasDefaultPaymentMethod}\n <p class=\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\">\n Add a default payment method above to subscribe.\n </p>\n {/if}\n <div class=\"space-y-4\">\n {#each availablePlans as plan (plan.id)}\n {@const isCurrent = activeSubscription?.priceId === plan.id}\n <div\n class=\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\n ? 'border-primary ring-primary ring-1'\n : 'border-border hover:bg-accent/50'}\"\n >\n <div class=\"flex items-center gap-4\">\n <div class=\"bg-muted flex size-12 items-center justify-center rounded-lg\">\n <Package class=\"size-5\" />\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">{plan.productName}</p>\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Badge variant=\"outline\">Pending cancellation</Badge>\n {:else if activeSubscription.status === 'trialing'}\n <Badge variant=\"secondary\">Trial</Badge>\n {:else if activeSubscription.status === 'past_due'}\n <Badge variant=\"destructive\">Past due</Badge>\n {:else}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Current\n </Badge>\n {/if}\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(plan.unitAmount, plan.currency)}\n {formatInterval(plan.recurring)}\n {#if isCurrent && activeSubscription?.currentPeriodEnd}\n <span>\n •\n {activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\n {formatDate(activeSubscription.currentPeriodEnd)}\n </span>\n {/if}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={isSubscribing === plan.id}\n onclick={resumeSubscription}\n >\n {isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => (showCancelDialog = true)}\n >\n Cancel subscription\n </Button>\n {/if}\n {:else if activeSubscription}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => switchPlan(plan.id)}\n >\n {isSubscribing === plan.id ? 'Switching...' : 'Switch'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => subscribe(plan.id)}\n >\n {isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\n </Button>\n {/if}\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Cancel Subscription Dialog -->\n<AlertDialog.Root bind:open={showCancelDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\n <AlertDialog.Description>\n Your subscription will remain active until the end of the current billing period, then\n cancel automatically.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\n Keep Subscription\n </AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\n {isCanceling ? 'Canceling...' : 'Cancel at Period End'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", s = "import type Stripe from 'stripe';\nimport { handlePaymentIntentSucceeded } from './payment-intent/succeeded';\nimport { handlePaymentMethodAttached } from './payment-method/attached';\nimport { handleSubscriptionCreated } from './subscription/created';\nimport { handleSubscriptionUpdated } from './subscription/updated';\nimport { handleSubscriptionDeleted } from './subscription/deleted';\n\n/**\n * Routes a verified Stripe event to its handler. Runs inside the stripe-event\n * workflow, so a handler that throws is retried with backoff rather than lost.\n */\nexport async function dispatchStripeEvent(event: Stripe.Event, locals: App.Locals) {\n switch (event.type) {\n case 'payment_intent.succeeded':\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n case 'payment_method.attached':\n await handlePaymentMethodAttached(event.data.object, locals);\n break;\n\n case 'customer.subscription.created':\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case 'customer.subscription.updated':\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case 'customer.subscription.deleted':\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n}\n";
|
|
3
|
+
//#endregion
|
|
4
|
+
export { r as a, e as c, i, o as n, n as o, a as r, t as s, s as t };
|
|
5
|
+
|
|
6
|
+
//# sourceMappingURL=dispatch-D4TN9pdW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dispatch-D4TN9pdW.js","names":["stripe_customer_default","app_sidebar_default","nav_user_default","_layout_server_default","_layout_default","_page_server_default","_page_default","dispatch_default"],"sources":[],"mappings":""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env-BPfk1VAw.js","names":[],"sources":["../../src/runtime/env.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../core/types\";\n\nexport interface EnvEdit {\n type: \"comment\" | \"var\";\n /** For \"comment\": the text after `# `. For \"var\": the KEY. */\n key: string;\n /** Only for \"var\" entries. */\n value?: string;\n}\n\nfunction appendEnvContent(existing: string, content: string): string {\n const withNewLine =\n !existing.length || existing.endsWith(\"\\n\") ? existing : existing + \"\\n\";\n return withNewLine + content + \"\\n\";\n}\n\nexport function applyEnvEdits(source: string, edits: EnvEdit[]): string {\n let next = source;\n for (const edit of edits) {\n if (edit.type === \"comment\") {\n const commented = `# ${edit.key}`;\n if (!next.includes(commented)) {\n next = appendEnvContent(next, commented);\n }\n continue;\n }\n if (!next.includes(`${edit.key}=`)) {\n next = appendEnvContent(next, `${edit.key}=${edit.value ?? \"\"}`);\n }\n }\n return next;\n}\n\nexport function modifyEnv(envPath: string, edits: EnvEdit[]): ModifyOutcome {\n const existing = fs.existsSync(envPath)\n ? fs.readFileSync(envPath, \"utf8\")\n : \"\";\n const next = applyEnvEdits(existing, edits);\n if (next === existing) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(envPath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/**\n * Remove lines matching the given edits from env source. Var edits remove the\n * exact `KEY=...` line (anchored, so `FOO` does not match `FOO_BAR`). Comment\n * edits remove the `# key` line only when it has become orphaned — i.e. the\n * next non-blank line is another comment, another orphaned block, or EOF.\n */\nexport function removeEnvEdits(source: string, edits: EnvEdit[]): string {\n const lines = source.split(\"\\n\");\n const keep: boolean[] = lines.map(() => true);\n\n for (const edit of edits) {\n if (edit.type !== \"var\") continue;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i]) continue;\n const line = lines[i];\n if (\n line === `${edit.key}=${edit.value ?? \"\"}` ||\n line.startsWith(`${edit.key}=`)\n ) {\n keep[i] = false;\n }\n }\n }\n\n for (const edit of edits) {\n if (edit.type !== \"comment\") continue;\n const target = `# ${edit.key}`;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i] || lines[i] !== target) continue;\n let j = i + 1;\n while (j < lines.length && (!keep[j] || lines[j].trim() === \"\")) j++;\n const nextIsComment = j >= lines.length || lines[j].startsWith(\"#\");\n if (nextIsComment) {\n keep[i] = false;\n }\n }\n }\n\n const result: string[] = [];\n let lastWasBlank = false;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i]) continue;\n const isBlank = lines[i].trim() === \"\";\n if (isBlank && lastWasBlank) continue;\n result.push(lines[i]);\n lastWasBlank = isBlank;\n }\n\n while (result.length > 0 && result[result.length - 1].trim() === \"\") {\n result.pop();\n }\n\n return result.length === 0 ? \"\" : result.join(\"\\n\") + \"\\n\";\n}\n\nexport function modifyEnvRemove(\n envPath: string,\n edits: EnvEdit[],\n): ModifyOutcome {\n const existing = fs.existsSync(envPath)\n ? fs.readFileSync(envPath, \"utf8\")\n : \"\";\n const next = removeEnvEdits(existing, edits);\n if (next === existing) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(envPath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;AAWA,
|
|
1
|
+
{"version":3,"file":"env-BPfk1VAw.js","names":["fs","appendEnvContent","existing","content","applyEnvEdits","next","source","edit","edits","commented","modifyEnv","envPath","removeEnvEdits","lines","keep","i","line","target","j","result","lastWasBlank","isBlank","modifyEnvRemove"],"sources":["../../src/runtime/env.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../core/types\";\n\nexport interface EnvEdit {\n type: \"comment\" | \"var\";\n /** For \"comment\": the text after `# `. For \"var\": the KEY. */\n key: string;\n /** Only for \"var\" entries. */\n value?: string;\n}\n\nfunction appendEnvContent(existing: string, content: string): string {\n const withNewLine =\n !existing.length || existing.endsWith(\"\\n\") ? existing : existing + \"\\n\";\n return withNewLine + content + \"\\n\";\n}\n\nexport function applyEnvEdits(source: string, edits: EnvEdit[]): string {\n let next = source;\n for (const edit of edits) {\n if (edit.type === \"comment\") {\n const commented = `# ${edit.key}`;\n if (!next.includes(commented)) {\n next = appendEnvContent(next, commented);\n }\n continue;\n }\n if (!next.includes(`${edit.key}=`)) {\n next = appendEnvContent(next, `${edit.key}=${edit.value ?? \"\"}`);\n }\n }\n return next;\n}\n\nexport function modifyEnv(envPath: string, edits: EnvEdit[]): ModifyOutcome {\n const existing = fs.existsSync(envPath)\n ? fs.readFileSync(envPath, \"utf8\")\n : \"\";\n const next = applyEnvEdits(existing, edits);\n if (next === existing) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(envPath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/**\n * Remove lines matching the given edits from env source. Var edits remove the\n * exact `KEY=...` line (anchored, so `FOO` does not match `FOO_BAR`). Comment\n * edits remove the `# key` line only when it has become orphaned — i.e. the\n * next non-blank line is another comment, another orphaned block, or EOF.\n */\nexport function removeEnvEdits(source: string, edits: EnvEdit[]): string {\n const lines = source.split(\"\\n\");\n const keep: boolean[] = lines.map(() => true);\n\n for (const edit of edits) {\n if (edit.type !== \"var\") continue;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i]) continue;\n const line = lines[i];\n if (\n line === `${edit.key}=${edit.value ?? \"\"}` ||\n line.startsWith(`${edit.key}=`)\n ) {\n keep[i] = false;\n }\n }\n }\n\n for (const edit of edits) {\n if (edit.type !== \"comment\") continue;\n const target = `# ${edit.key}`;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i] || lines[i] !== target) continue;\n let j = i + 1;\n while (j < lines.length && (!keep[j] || lines[j].trim() === \"\")) j++;\n const nextIsComment = j >= lines.length || lines[j].startsWith(\"#\");\n if (nextIsComment) {\n keep[i] = false;\n }\n }\n }\n\n const result: string[] = [];\n let lastWasBlank = false;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i]) continue;\n const isBlank = lines[i].trim() === \"\";\n if (isBlank && lastWasBlank) continue;\n result.push(lines[i]);\n lastWasBlank = isBlank;\n }\n\n while (result.length > 0 && result[result.length - 1].trim() === \"\") {\n result.pop();\n }\n\n return result.length === 0 ? \"\" : result.join(\"\\n\") + \"\\n\";\n}\n\nexport function modifyEnvRemove(\n envPath: string,\n edits: EnvEdit[],\n): ModifyOutcome {\n const existing = fs.existsSync(envPath)\n ? fs.readFileSync(envPath, \"utf8\")\n : \"\";\n const next = removeEnvEdits(existing, edits);\n if (next === existing) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(envPath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;AAWA,SAASC,EAAiB,GAAkB,GAAyB;CAGnE,QADE,CAACC,EAAS,UAAUA,EAAS,SAAS,IAAI,IAAIA,IAAWA,IAAW,QACjDC,IAAU;AACjC;AAEA,SAAgBC,EAAc,GAAgB,GAA0B;CACtE,IAAIC,IAAOC;CACX,KAAK,IAAMC,KAAQC,GAAO;EACxB,IAAID,EAAK,SAAS,WAAW;GAC3B,IAAME,IAAY,KAAKF,EAAK;GAC5B,AAAKF,EAAK,SAASI,CAAS,MAC1B,IAAOR,EAAiBI,GAAMI,CAAS;GAEzC;EACF;EACA,AAAKJ,EAAK,SAAS,GAAGE,EAAK,IAAI,EAAE,MAC/B,IAAON,EAAiBI,GAAM,GAAGE,EAAK,IAAI,GAAGA,EAAK,SAAS,IAAI;CAEnE;CACA,OAAOF;AACT;AAEA,SAAgBK,EAAU,GAAiB,GAAiC;CAC1E,IAAMR,IAAWF,EAAG,WAAWW,CAAO,IAClCX,EAAG,aAAaW,GAAS,MAAM,IAC/B,IACEN,IAAOD,EAAcF,GAAUM,CAAK;CAK1C,OAJIH,MAASH,IACJ;EAAE,QAAQ;EAAW,SAAS;CAAM,KAE7CF,EAAG,cAAcW,GA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I;CAGb,OAAOA,EAAO,WAAW,IAAI,KAAKA,EAAO,KAAK,IAAI,IAAI;AACxD;AAEA,SAAgBG,EACd,GACA,GACe;CACf,IAAMpB,IAAWF,EAAG,WAAWW,CAAO,IAClCX,EAAG,aAAaW,GAAS,MAAM,IAC/B,IACEN,IAAOO,EAAeV,GAAUM,CAAK;CAK3C,OAJIH,MAASH,IACJ;EAAE,QAAQ;EAAW,SAAS;CAAM,KAE7CF,EAAG,cAAcW,GAASN,GAAM,MAAM,GAC/B;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { i as e, n as t, r as n, t as r } from "./env-vars-file-B_6esJW3.js";
|
|
2
2
|
import { a as i } from "./util-BLYliuUK.js";
|
|
3
|
-
import { n as a } from "./shared-
|
|
4
|
-
import { i as o, o as s } from "./ts-morph-helpers-
|
|
5
|
-
import { modifyOutcomeToFile as c } from "./modify-file-
|
|
3
|
+
import { n as a } from "./shared-Cc_ns5-y.js";
|
|
4
|
+
import { i as o, o as s } from "./ts-morph-helpers-Bepc-Es2.js";
|
|
5
|
+
import { modifyOutcomeToFile as c } from "./modify-file-DK-tCH9k.js";
|
|
6
6
|
import l from "node:fs";
|
|
7
7
|
import u from "node:path";
|
|
8
8
|
import { Node as d, Project as f, QuoteKind as p, SyntaxKind as m } from "ts-morph";
|
|
@@ -265,4 +265,4 @@ function L(e) {
|
|
|
265
265
|
//#endregion
|
|
266
266
|
export { N as modifyEnvVars, P as modifyEnvVarsFiles, F as unmodifyEnvVars, I as unmodifyEnvVarsFiles };
|
|
267
267
|
|
|
268
|
-
//# sourceMappingURL=env-vars-
|
|
268
|
+
//# sourceMappingURL=env-vars-CcE6ODqC.js.map
|