@velastack/patterns 0.15.3 → 0.15.4
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/_page-CiazQY4O.js +5 -0
- package/dist/chunks/{_page-DkCd_o3E.js.map → _page-CiazQY4O.js.map} +1 -1
- package/dist/chunks/{auth-pages-mZeR1WIj.js → auth-pages-B8H3kQPW.js} +2 -2
- package/dist/chunks/{auth-pages-mZeR1WIj.js.map → auth-pages-B8H3kQPW.js.map} +1 -1
- package/dist/chunks/{collections-Daxlnbm0.js → collections-CFTIAty-.js} +2 -2
- package/dist/chunks/{collections-Daxlnbm0.js.map → collections-CFTIAty-.js.map} +1 -1
- package/dist/chunks/{env-vars-C3TSZc4f.js → env-vars--fyhY-ew.js} +3 -3
- package/dist/chunks/{env-vars-C3TSZc4f.js.map → env-vars--fyhY-ew.js.map} +1 -1
- package/dist/chunks/{generate-CbchamhA.js → generate-B2z0kA5C.js} +2 -2
- package/dist/chunks/{generate-CbchamhA.js.map → generate-B2z0kA5C.js.map} +1 -1
- package/dist/chunks/{generate-CAYM7OUF.js → generate-BSCDKlyL.js} +2 -2
- package/dist/chunks/{generate-CAYM7OUF.js.map → generate-BSCDKlyL.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CZMVPVjS.js → generate.runtime-2T2j6Cgc.js} +5 -5
- package/dist/chunks/{generate.runtime-CZMVPVjS.js.map → generate.runtime-2T2j6Cgc.js.map} +1 -1
- package/dist/chunks/{generate.runtime-_426A1Ij.js → generate.runtime-7rRHLyjy.js} +3 -3
- package/dist/chunks/{generate.runtime-_426A1Ij.js.map → generate.runtime-7rRHLyjy.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bo_s7gYB.js → generate.runtime-9wfx5sJK.js} +2 -2
- package/dist/chunks/{generate.runtime-Bo_s7gYB.js.map → generate.runtime-9wfx5sJK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B7VubPTW.js → generate.runtime-B6Tce286.js} +3 -3
- package/dist/chunks/{generate.runtime-B7VubPTW.js.map → generate.runtime-B6Tce286.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B11mOr45.js → generate.runtime-B9nqVvxO.js} +2 -2
- package/dist/chunks/{generate.runtime-B11mOr45.js.map → generate.runtime-B9nqVvxO.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BL6DpWFI.js → generate.runtime-BCa20dNN.js} +3 -3
- package/dist/chunks/{generate.runtime-BL6DpWFI.js.map → generate.runtime-BCa20dNN.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DP63Wwea.js → generate.runtime-BFyTIABc.js} +4 -4
- package/dist/chunks/{generate.runtime-DP63Wwea.js.map → generate.runtime-BFyTIABc.js.map} +1 -1
- package/dist/chunks/{generate.runtime-VZIxJWlr.js → generate.runtime-B_md4EZa.js} +15 -15
- package/dist/chunks/{generate.runtime-VZIxJWlr.js.map → generate.runtime-B_md4EZa.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BjTZ2Ls-.js → generate.runtime-BpXoagaq.js} +3 -3
- package/dist/chunks/{generate.runtime-BjTZ2Ls-.js.map → generate.runtime-BpXoagaq.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DW9bqOtC.js → generate.runtime-C1zb2WxI.js} +2 -2
- package/dist/chunks/{generate.runtime-DW9bqOtC.js.map → generate.runtime-C1zb2WxI.js.map} +1 -1
- package/dist/chunks/{generate.runtime-373mTxeo.js → generate.runtime-C4R919oE.js} +2 -2
- package/dist/chunks/{generate.runtime-373mTxeo.js.map → generate.runtime-C4R919oE.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BCv4F1Wm.js → generate.runtime-C4qZ7Q30.js} +4 -4
- package/dist/chunks/{generate.runtime-BCv4F1Wm.js.map → generate.runtime-C4qZ7Q30.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C90_2L-8.js → generate.runtime-C8xFPEgP.js} +2 -2
- package/dist/chunks/{generate.runtime-C90_2L-8.js.map → generate.runtime-C8xFPEgP.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cs73i6Zf.js → generate.runtime-CC4XoTnb.js} +2 -2
- package/dist/chunks/{generate.runtime-Cs73i6Zf.js.map → generate.runtime-CC4XoTnb.js.map} +1 -1
- package/dist/chunks/{generate.runtime-jIlQ2GMh.js → generate.runtime-CCL_doqr.js} +2 -2
- package/dist/chunks/{generate.runtime-jIlQ2GMh.js.map → generate.runtime-CCL_doqr.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BEWp57Y7.js → generate.runtime-CKyi82cZ.js} +2 -2
- package/dist/chunks/{generate.runtime-BEWp57Y7.js.map → generate.runtime-CKyi82cZ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DgKiFemb.js → generate.runtime-CNHEuhx4.js} +3 -3
- package/dist/chunks/{generate.runtime-DgKiFemb.js.map → generate.runtime-CNHEuhx4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DIIeK2w9.js → generate.runtime-CPF0TcjM.js} +3 -3
- package/dist/chunks/{generate.runtime-DIIeK2w9.js.map → generate.runtime-CPF0TcjM.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DmbDEjMA.js → generate.runtime-CWNIo1xQ.js} +3 -3
- package/dist/chunks/{generate.runtime-DmbDEjMA.js.map → generate.runtime-CWNIo1xQ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CDY0Ot_t.js → generate.runtime-Cb2u0ft4.js} +5 -5
- package/dist/chunks/{generate.runtime-CDY0Ot_t.js.map → generate.runtime-Cb2u0ft4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-ChSVP7cD.js → generate.runtime-CdpLsiqC.js} +4 -4
- package/dist/chunks/{generate.runtime-ChSVP7cD.js.map → generate.runtime-CdpLsiqC.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DVZUNxtv.js → generate.runtime-ChstrVRw.js} +4 -4
- package/dist/chunks/{generate.runtime-DVZUNxtv.js.map → generate.runtime-ChstrVRw.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bhs7ttZS.js → generate.runtime-CpDUk3Ev.js} +2 -2
- package/dist/chunks/{generate.runtime-Bhs7ttZS.js.map → generate.runtime-CpDUk3Ev.js.map} +1 -1
- package/dist/chunks/{generate.runtime-xrxAElb3.js → generate.runtime-Ctd_522e.js} +3 -3
- package/dist/chunks/{generate.runtime-xrxAElb3.js.map → generate.runtime-Ctd_522e.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bn17HK_S.js → generate.runtime-CviYhOWW.js} +198 -115
- package/dist/chunks/generate.runtime-CviYhOWW.js.map +1 -0
- package/dist/chunks/{generate.runtime-BRV9hIl5.js → generate.runtime-CxJaHusI.js} +2 -2
- package/dist/chunks/{generate.runtime-BRV9hIl5.js.map → generate.runtime-CxJaHusI.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DRPxOLnB.js → generate.runtime-D0acTMRF.js} +4 -4
- package/dist/chunks/{generate.runtime-DRPxOLnB.js.map → generate.runtime-D0acTMRF.js.map} +1 -1
- package/dist/chunks/{generate.runtime-fs6GEMx-.js → generate.runtime-D6vRzBoU.js} +4 -4
- package/dist/chunks/{generate.runtime-fs6GEMx-.js.map → generate.runtime-D6vRzBoU.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BRcP6sFt.js → generate.runtime-D7aGjoTD.js} +2 -2
- package/dist/chunks/{generate.runtime-BRcP6sFt.js.map → generate.runtime-D7aGjoTD.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DG9LRwbt.js → generate.runtime-DPtjvhGr.js} +2 -2
- package/dist/chunks/{generate.runtime-DG9LRwbt.js.map → generate.runtime-DPtjvhGr.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BjrtdoYE.js → generate.runtime-DmHZZz4Z.js} +2 -2
- package/dist/chunks/{generate.runtime-BjrtdoYE.js.map → generate.runtime-DmHZZz4Z.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DXqBku2y.js → generate.runtime-O5eQdhHV.js} +4 -4
- package/dist/chunks/{generate.runtime-DXqBku2y.js.map → generate.runtime-O5eQdhHV.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DKL7VAAd.js → generate.runtime-Uq_L7TtO.js} +5 -5
- package/dist/chunks/{generate.runtime-DKL7VAAd.js.map → generate.runtime-Uq_L7TtO.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C_hrLPD4.js → generate.runtime-VWQfzXXv.js} +3 -3
- package/dist/chunks/{generate.runtime-C_hrLPD4.js.map → generate.runtime-VWQfzXXv.js.map} +1 -1
- package/dist/chunks/{generate.runtime-v3KCv1B6.js → generate.runtime-WL1mm8gp.js} +2 -2
- package/dist/chunks/{generate.runtime-v3KCv1B6.js.map → generate.runtime-WL1mm8gp.js.map} +1 -1
- package/dist/chunks/{generate.runtime-sey-wxXB.js → generate.runtime-vJFz9Q7V.js} +7 -7
- package/dist/chunks/{generate.runtime-sey-wxXB.js.map → generate.runtime-vJFz9Q7V.js.map} +1 -1
- package/dist/chunks/{gitignore-CBiWFRif.js → gitignore-DUzIQXIo.js} +2 -2
- package/dist/chunks/{gitignore-CBiWFRif.js.map → gitignore-DUzIQXIo.js.map} +1 -1
- package/dist/chunks/{i18n-Ho8H91Ze.js → i18n-BoYcqVBi.js} +2 -2
- package/dist/chunks/{i18n-Ho8H91Ze.js.map → i18n-BoYcqVBi.js.map} +1 -1
- package/dist/chunks/{modify-file-BOEKlIDw.js → modify-file-DRdmZIvW.js} +2 -2
- package/dist/chunks/{modify-file-BOEKlIDw.js.map → modify-file-DRdmZIvW.js.map} +1 -1
- package/dist/chunks/{pocketbase-CvsJYXj-.js → pocketbase-BrDs1_84.js} +23 -7
- package/dist/chunks/pocketbase-BrDs1_84.js.map +1 -0
- package/dist/chunks/{providers-BEjDonyG.js → providers-Dhr_mzm6.js} +2 -2
- package/dist/chunks/{providers-BEjDonyG.js.map → providers-Dhr_mzm6.js.map} +1 -1
- package/dist/chunks/{schema-DnMqw2Hn.js → schema-C16iVOAG.js} +2 -2
- package/dist/chunks/{schema-DnMqw2Hn.js.map → schema-C16iVOAG.js.map} +1 -1
- package/dist/chunks/{shared-CSwGWMcN.js → shared-D7-ZAoqr.js} +2 -2
- package/dist/chunks/{shared-CSwGWMcN.js.map → shared-D7-ZAoqr.js.map} +1 -1
- package/dist/chunks/{ui-CpjUq_lm.js → ui-BI9OQpuR.js} +2 -2
- package/dist/chunks/{ui-CpjUq_lm.js.map → ui-BI9OQpuR.js.map} +1 -1
- package/dist/chunks/{write-result-DlB-id5k.js → write-result-Do8AcYbL.js} +2 -2
- package/dist/chunks/{write-result-DlB-id5k.js.map → write-result-Do8AcYbL.js.map} +1 -1
- package/dist/index.js +2161 -2152
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/_page-DkCd_o3E.js +0 -5
- package/dist/chunks/generate.runtime-Bn17HK_S.js.map +0 -1
- package/dist/chunks/pocketbase-CvsJYXj-.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_page-
|
|
1
|
+
{"version":3,"file":"_page-CiazQY4O.js","names":["app_sidebar_default$1","nav_main_default$1","nav_user_default$1","user_avatar_default$1","changeEmail_default$1","changePassword_default$1","confirmEmailChange_default$1","confirmReset_default$1","login_default$2","otp_default$1","profile_default$1","reset_default$1","signup_default$2","welcome_default$1","user_default$1","_layout_server_default$3","_layout_default$1","_page_default$37","server_test_default$19","_layout_server_default$2","_page_server_default$17","_page_default$36","_page_default$35","_page_server_default$16","_page_default$34","_page_default$33","server_test_default$18","_page_server_default$15","_page_default$32","_page_default$31","server_test_default$17","_server_default$3","server_test_default$16","_page_server_default$14","_page_default$30","_page_default$29","server_test_default$15","_server_default$2","server_test_default$14","_page_server_default$13","_page_default$28","_page_default$27","server_test_default$13","_page_server_default$12","_page_default$26","_page_default$25","server_test_default$12","_page_server_default$11","_page_default$24","_page_default$23","server_test_default$11","_page_server_default$10","_page_default$22","_page_default$21","server_test_default$10","_page_default$20","_page_default$19","app_sidebar_default","nav_main_default","nav_user_default","user_avatar_default","changeEmail_default","changePassword_default","confirmEmailChange_default","confirmReset_default","login_default$1","otp_default","profile_default","reset_default","signup_default$1","welcome_default","user_default","_layout_server_default$1","_layout_default","_page_default$18","server_test_default$9","_layout_server_default","_page_server_default$9","_page_default$17","_page_default$16","form_remote_default$7","_page_server_default$8","_page_default$15","_page_default$14","form_remote_default$6","server_test_default$8","_page_server_default$7","_page_default$13","_page_default$12","form_remote_default$5","server_test_default$7","_server_default$1","server_test_default$6","_page_server_default$6","_page_default$11","_page_default$10","form_remote_default$4","server_test_default$5","_server_default","server_test_default$4","_page_server_default$5","_page_default$9","_page_default$8","form_remote_default$3","server_test_default$3","_page_server_default$4","_page_default$7","_page_default$6","form_remote_default$2","server_test_default$2","_page_server_default$3","_page_default$5","_page_default$4","form_remote_default$1","server_test_default$1","_page_server_default$2","_page_default$3","_page_default$2","form_remote_default","next_url_default","server_test_default","login_default","signup_default","_page_server_default$1","_page_default$1","_page_server_default","_page_default"],"sources":[],"mappings":""}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as ee, F as te, Ft as ne, G as re, Gt as ie, H as ae, Ht as oe, I as se, It as ce, J as le, Jt as ue, K as de, Kt as fe, L as d, Lt as f, M as p, Mt as m, N as h, Nt as g, O as _, Ot as v, P as y, Pt as b, Q as x, Qt as S, R as C, Rt as w, S as T, St as E, T as D, Tt as O, U as k, Ut as A, V as j, Vt as M, W as N, Wt as P, X as F, Xt as I, Y as L, Yt as R, Z as z, Zt as B, _ as V, _n as pe, _t as me, a as he, an as ge, at as _e, b as ve, bt as ye, c as be, cn as xe, ct as Se, d as Ce, dn as we, dt as Te, en as Ee, et as De, f as Oe, fn as ke, ft as Ae, g as je, gn as Me, gt as Ne, h as Pe, hn as Fe, ht as Ie, i as Le, in as Re, it as ze, j as Be, jt as Ve, k as He, kt as Ue, l as We, ln as Ge, lt as Ke, m as qe, mn as Je, mt as Ye, n as Xe, nn as Ze, nt as Qe, o as $e, on as et, ot as tt, p as nt, pn as rt, pt as it, q as at, qt as ot, r as st, rn as ct, rt as lt, s as ut, sn as dt, st as ft, t as pt, tn as mt, tt as ht, u as gt, un as _t, ut as vt, v as yt, vn as bt, vt as xt, w as St, wt as Ct, x as wt, xt as Tt, y as Et, yn as Dt, yt as Ot, z as kt, zt as At } from "./_page-
|
|
1
|
+
import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as ee, F as te, Ft as ne, G as re, Gt as ie, H as ae, Ht as oe, I as se, It as ce, J as le, Jt as ue, K as de, Kt as fe, L as d, Lt as f, M as p, Mt as m, N as h, Nt as g, O as _, Ot as v, P as y, Pt as b, Q as x, Qt as S, R as C, Rt as w, S as T, St as E, T as D, Tt as O, U as k, Ut as A, V as j, Vt as M, W as N, Wt as P, X as F, Xt as I, Y as L, Yt as R, Z as z, Zt as B, _ as V, _n as pe, _t as me, a as he, an as ge, at as _e, b as ve, bt as ye, c as be, cn as xe, ct as Se, d as Ce, dn as we, dt as Te, en as Ee, et as De, f as Oe, fn as ke, ft as Ae, g as je, gn as Me, gt as Ne, h as Pe, hn as Fe, ht as Ie, i as Le, in as Re, it as ze, j as Be, jt as Ve, k as He, kt as Ue, l as We, ln as Ge, lt as Ke, m as qe, mn as Je, mt as Ye, n as Xe, nn as Ze, nt as Qe, o as $e, on as et, ot as tt, p as nt, pn as rt, pt as it, q as at, qt as ot, r as st, rn as ct, rt as lt, s as ut, sn as dt, st as ft, t as pt, tn as mt, tt as ht, u as gt, un as _t, ut as vt, v as yt, vn as bt, vt as xt, w as St, wt as Ct, x as wt, xt as Tt, y as Et, yn as Dt, yt as Ot, z as kt, zt as At } from "./_page-CiazQY4O.js";
|
|
2
2
|
import { t as jt } from "./modify-user-signup-ENhadGKH.js";
|
|
3
3
|
import H from "node:fs";
|
|
4
4
|
import U from "node:path";
|
|
@@ -308,4 +308,4 @@ async function mn(e, t, n) {
|
|
|
308
308
|
}
|
|
309
309
|
export { Q as detectMode, mn as swapAuthPages };
|
|
310
310
|
|
|
311
|
-
//# sourceMappingURL=auth-pages-
|
|
311
|
+
//# sourceMappingURL=auth-pages-B8H3kQPW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-pages-mZeR1WIj.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__3_7_","__import_glob__3_8_","__import_glob__3_9_","__import_glob__3_10_","__import_glob__3_11_","__import_glob__3_12_","__import_glob__3_13_","__import_glob__3_14_","__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$7","server_test_default$14","_page_server_default$12","_page_default$31","_page_server_default$10","server_test_default$16","server_test_default$8","_page_server_default$19","server_test_default$7","_page_default$35","_page_server_default$13","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$16","_page_server_default$9","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$18","_page_server_default$11","server_test_default$10","_page_default$8","form_remote_default$9","_page_default$15","_page_server_default$20","_page_server_default$14","_page_default$36","_page_default$20","form_remote_default$8","server_test_default$2","_page_server_default$17","server_test_default$3","_page_default$30","_page_default$13","_page_server_default$15","_page_server_default$8","_page_default$27","_page_default$10","_layout_server_default$3","_page_default$9","_page_server_default$21","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$22","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$23","_layout_server_default","signup_default$4","form_remote_default$10","server_test_default$6","_server_default$3","_page_default$18","form_remote_default$14","profile_default","confirmReset_default$1","form_remote_default$13","changePassword_default","nav_user_default$1","_page_server_default$24","_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$7","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","_page_default$24","form_remote_default$11","_page_default$21","_page_default$37","_page_default$22","form_remote_default$12","app_sidebar_default","server_test_default$9","_page_default$32","_page_default$14","modifyUserSignup","fs","path","prettier","sveltePlugin","signup_default$2","_page_server_default$6","_page_default$6","signup_default$1","_page_default$5","form_remote_default$6","_page_default$4","_page_server_default$5","_page_server_default$4","form_remote_default$5","form_remote_default$4","_page_server_default$3","_page_server_default$2","form_remote_default$3","form_remote_default$2","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","ORIGINALS","earlier","releases","release","pattern","files","LEGACY","TEMPLATES","WHATSAPP_CODE","AUTH","pageGroups","group","name","mode","detectMode","root","SHAPES","pick","shape","rel","stock","candidatesFor","seen","whatsapp","from","to","legacy","direction","originals","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/**\n * Pages as earlier releases wrote them, in a directory named for the last\n * release that did: a project still has them until it runs the pattern again.\n * `auth-1.1` is signup before it had a one-time code. `auth-1.3` and\n * `whatsapp-1.0` gave the session cookie thirty days, which outlived its token.\n */\nconst ORIGINALS = raw(\n import.meta.glob<string>(\"../originals/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n }),\n \"../originals/\",\n);\n\n/** The files of every earlier release of `pattern`, each keyed like `TEMPLATES`. */\nfunction earlier(pattern: \"auth\" | \"whatsapp\"): Record<string, string>[] {\n const releases = new Map<string, Record<string, string>>();\n for (const [key, content] of Object.entries(ORIGINALS)) {\n const release = key.slice(0, key.indexOf(\"/\"));\n if (!release.startsWith(`${pattern}-`)) continue;\n const files = releases.get(release) ?? {};\n files[key.slice(release.length + 1)] = content;\n releases.set(release, files);\n }\n return [...releases.values()];\n}\n\nconst LEGACY = { stock: earlier(\"auth\"), whatsapp: earlier(\"whatsapp\") };\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 version of `rel` the swap starts from, paired with what it becomes:\n * the stock page, current or from an earlier release, and the WhatsApp one on\n * `enable`; the WhatsApp page, current or earlier, and the current stock one\n * 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 const [from, to, legacy] =\n direction === \"enable\"\n ? [current, whatsapp, LEGACY.stock]\n : [whatsapp, current, LEGACY.whatsapp];\n const originals = [from, ...legacy.map((files) => pick(files, shape, rel))];\n for (const original of originals) {\n if (!original || seen.has(original)) continue;\n seen.add(original);\n candidates.push({ original, template: to });\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] : [],\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C5C,GAAS;EAC3B,IAAM,CAAC6C,GAAMC,GAAIC,KACfC,MAAc,WACV;GAAChD;GAAS4C;GAAUjB,EAAO;EAAK,IAChC;GAACiB;GAAU5C;GAAS2B,EAAO;EAAQ,GACnCsB,IAAY,CAACJ,GAAM,GAAGE,EAAO,KAAK,MAAUT,EAAKZ,GAAOa,GAAOC,CAAG,CAAC,CAAC;EAC1E,KAAK,IAAMjC,KAAY0C,GACrB,AAAK1C,KAAY,GAAK,IAAIA,CAAQ,MAClCoC,EAAK,IAAIpC,CAAQ,GACjBD,EAAW,KAAK;GAAE;GAAU,UAAUwC;EAAG,CAAC;CAE9C;CACA,OAAOxC;AACT;AAOA,IAAM4C,KAA2B;CAC/B,SAAS,MAAYrD,EAAQ,SAAS,oBAAoB;CAC1D,QAAQ,MACNK,EACG,QACC,yFACA,EACF,CAAC,CACA,QACC,6JACA,EACF;CACJ,OAAOpC;AACT;AAOA,eAAsBqF,GACpB,GACA,GACA,GACqC;CACrC,IAAMjB,IAAOC,EAAWC,CAAI,GAGtBnC,IACJ+C,MAAc,WACVnB,IACI,OAAO,iBAAiBA,EAAc,OAAO,GAAG,GACpDpB,oBAAW,IAAI,IAA2B;CAEhD,KAAK,IAAMiB,KAAS,OAAO,OAAOK,GAAWG,CAAI,CAAC,GAAG;EACnD,IAAMvB,IAAU,MAAM,QAAQ,IAC5Be,EAAM,KAAK,MACT3B,GACE/B,EAAK,KAAKoE,GAAMI,CAAG,GACnBE,GAAcR,GAAMM,GAAKQ,CAAS,GAClC/C,GACAuC,EAAI,SAAS,wBAAwB,IAAI,CAACU,EAAe,IAAI,CAAC,CAChE,CACF,CACF;EACA,KAAK,IAAM,CAACpD,GAAUe,MAAYL,GAAWG,GAASG,CAAI,GACxD,EAAS,IAAIhB,GAAUe,CAAO;CAElC;CACA,OAAOJ;AACT"}
|
|
1
|
+
{"version":3,"file":"auth-pages-B8H3kQPW.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__3_7_","__import_glob__3_8_","__import_glob__3_9_","__import_glob__3_10_","__import_glob__3_11_","__import_glob__3_12_","__import_glob__3_13_","__import_glob__3_14_","__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$7","server_test_default$14","_page_server_default$12","_page_default$31","_page_server_default$10","server_test_default$16","server_test_default$8","_page_server_default$19","server_test_default$7","_page_default$35","_page_server_default$13","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$16","_page_server_default$9","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$18","_page_server_default$11","server_test_default$10","_page_default$8","form_remote_default$9","_page_default$15","_page_server_default$20","_page_server_default$14","_page_default$36","_page_default$20","form_remote_default$8","server_test_default$2","_page_server_default$17","server_test_default$3","_page_default$30","_page_default$13","_page_server_default$15","_page_server_default$8","_page_default$27","_page_default$10","_layout_server_default$3","_page_default$9","_page_server_default$21","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$22","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$23","_layout_server_default","signup_default$4","form_remote_default$10","server_test_default$6","_server_default$3","_page_default$18","form_remote_default$14","profile_default","confirmReset_default$1","form_remote_default$13","changePassword_default","nav_user_default$1","_page_server_default$24","_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$7","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","_page_default$24","form_remote_default$11","_page_default$21","_page_default$37","_page_default$22","form_remote_default$12","app_sidebar_default","server_test_default$9","_page_default$32","_page_default$14","modifyUserSignup","fs","path","prettier","sveltePlugin","signup_default$2","_page_server_default$6","_page_default$6","signup_default$1","_page_default$5","form_remote_default$6","_page_default$4","_page_server_default$5","_page_server_default$4","form_remote_default$5","form_remote_default$4","_page_server_default$3","_page_server_default$2","form_remote_default$3","form_remote_default$2","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","ORIGINALS","earlier","releases","release","pattern","files","LEGACY","TEMPLATES","WHATSAPP_CODE","AUTH","pageGroups","group","name","mode","detectMode","root","SHAPES","pick","shape","rel","stock","candidatesFor","seen","whatsapp","from","to","legacy","direction","originals","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/**\n * Pages as earlier releases wrote them, in a directory named for the last\n * release that did: a project still has them until it runs the pattern again.\n * `auth-1.1` is signup before it had a one-time code. `auth-1.3` and\n * `whatsapp-1.0` gave the session cookie thirty days, which outlived its token.\n */\nconst ORIGINALS = raw(\n import.meta.glob<string>(\"../originals/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n }),\n \"../originals/\",\n);\n\n/** The files of every earlier release of `pattern`, each keyed like `TEMPLATES`. */\nfunction earlier(pattern: \"auth\" | \"whatsapp\"): Record<string, string>[] {\n const releases = new Map<string, Record<string, string>>();\n for (const [key, content] of Object.entries(ORIGINALS)) {\n const release = key.slice(0, key.indexOf(\"/\"));\n if (!release.startsWith(`${pattern}-`)) continue;\n const files = releases.get(release) ?? {};\n files[key.slice(release.length + 1)] = content;\n releases.set(release, files);\n }\n return [...releases.values()];\n}\n\nconst LEGACY = { stock: earlier(\"auth\"), whatsapp: earlier(\"whatsapp\") };\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 version of `rel` the swap starts from, paired with what it becomes:\n * the stock page, current or from an earlier release, and the WhatsApp one on\n * `enable`; the WhatsApp page, current or earlier, and the current stock one\n * 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 const [from, to, legacy] =\n direction === \"enable\"\n ? [current, whatsapp, LEGACY.stock]\n : [whatsapp, current, LEGACY.whatsapp];\n const originals = [from, ...legacy.map((files) => pick(files, shape, rel))];\n for (const original of originals) {\n if (!original || seen.has(original)) continue;\n seen.add(original);\n candidates.push({ original, template: to });\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,eAAeqT,EAAU,GAAiB,GAAmC;CAC3E,IAAI;EACF,OAAO,MAAM3B,GAAS,OAAO4B,GAAS;GACpC,UAAUC;GACV,SAAS,CAAC5B,EAAY;EACxB,CAAC;CACH,QAAQ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,KAAY0C,GACrB,AAAK1C,KAAY,GAAK,IAAIA,CAAQ,MAClCoC,EAAK,IAAIpC,CAAQ,GACjBD,EAAW,KAAK;GAAE;GAAU,UAAUwC;EAAG,CAAC;CAE9C;CACA,OAAOxC;AACT;AAOA,IAAM4C,KAA2B;CAC/B,SAAS,MAAYrD,EAAQ,SAAS,oBAAoB;CAC1D,QAAQ,MACNK,EACG,QACC,yFACA,EACF,CAAC,CACA,QACC,6JACA,EACF;CACJ,OAAOpC;AACT;AAOA,eAAsBqF,GACpB,GACA,GACA,GACqC;CACrC,IAAMjB,IAAOC,EAAWC,CAAI,GAGtBnC,IACJ+C,MAAc,WACVnB,IACI,OAAO,iBAAiBA,EAAc,OAAO,GAAG,GACpDpB,oBAAW,IAAI,IAA2B;CAEhD,KAAK,IAAMiB,KAAS,OAAO,OAAOK,GAAWG,CAAI,CAAC,GAAG;EACnD,IAAMvB,IAAU,MAAM,QAAQ,IAC5Be,EAAM,KAAK,MACT3B,GACE/B,EAAK,KAAKoE,GAAMI,CAAG,GACnBE,GAAcR,GAAMM,GAAKQ,CAAS,GAClC/C,GACAuC,EAAI,SAAS,wBAAwB,IAAI,CAACU,EAAe,IAAI,CAAC,CAChE,CACF,CACF;EACA,KAAK,IAAM,CAACpD,GAAUe,MAAYL,GAAWG,GAASG,CAAI,GACxD,EAAS,IAAIhB,GAAUe,CAAO;CAElC;CACA,OAAOJ;AACT"}
|
|
@@ -193,6 +193,6 @@ async function T(e, t) {
|
|
|
193
193
|
}
|
|
194
194
|
}), r;
|
|
195
195
|
}
|
|
196
|
-
export {
|
|
196
|
+
export { y as a, m as i, g as n, w as o, d as r, v as t };
|
|
197
197
|
|
|
198
|
-
//# sourceMappingURL=collections-
|
|
198
|
+
//# sourceMappingURL=collections-CFTIAty-.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collections-Daxlnbm0.js","names":["__exportAll","NOOP_LOGGER","formatSource","withPocketbase","migrationDelay","getMigrationFile","collections_exports","applyCollectionFieldsPatches","createCollections","dropCollections","planCollectionDrops","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","readMigration","applyFieldChanges","change","f","InvalidArgumentError","index","collection","newFields","body","ensureCollectionFields","have","missing","dropCollectionIdempotent","getCollectionStats","plans","names","stats","specs","getLogger","dropped","original","readFileSync","filePath","content","written","writeFileSync","languageFromPath","collections","created"],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync, writeFileSync } 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 { formatSource } from \"../core/format-result\";\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(await readMigration(migrationFile, options));\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: (name: string) => Promise<{\n id: string;\n fields: CollectionFieldSpec[];\n indexes?: string[];\n }>;\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 const body: Record<string, unknown> = { fields: newFields };\n if (patch.indexes?.length) {\n // PocketBase replaces the list, so the ones it has are sent back.\n const existing = collection.indexes ?? [];\n body.indexes = [\n ...existing,\n ...patch.indexes.filter((index) => !existing.includes(index)),\n ];\n }\n await pb.collections.update(collection.id, body);\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push(await readMigration(migrationFile, options));\n }\n\n return migrations;\n}\n\n/**\n * Adds to an existing collection every field of `spec` it lacks, by name, so a\n * project that created it under an older spec gets the new fields. Fields are\n * only added, never changed or removed. Returns the migration files written.\n */\nexport async function ensureCollectionFields(\n pb: PocketBase,\n spec: CollectionSpec,\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const existing = await pb.collections.getOne(spec.name);\n const have = new Set(\n (existing.fields as { name: string }[]).map((field) => field.name),\n );\n const missing = spec.fields.filter((field) => !have.has(field.name));\n if (missing.length === 0) return [];\n logger.info(\n `Adding ${missing.map((field) => field.name).join(\", \")} to collection \"${spec.name}\"`,\n );\n return applyCollectionFieldsPatches(\n pb,\n [\n {\n collectionName: spec.name,\n changes: missing.map((field) => ({ op: \"add\" as const, field })),\n },\n ],\n options,\n logger,\n );\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(await readMigration(migrationFile, options));\n }\n });\n\n return migrations;\n}\n\n/**\n * A migration PocketBase has just written, as a file of the result, formatted\n * where it lies.\n *\n * PocketBase writes migrations in its own style, which the project's\n * `prettier --check` rejects. Formatting used to wait for `writeResult`, so a\n * run that failed in between (a component that could not be installed, a\n * package install that died) left the migration as PocketBase wrote it. It is\n * formatted here instead, as soon as it is read back, and marked `written` so\n * `writeResult` reports the file, as it did when it was the one to format it,\n * without writing it a second time.\n */\nexport async function readMigration(\n filePath: string,\n options: Pick<Options, \"env\" | \"root\">,\n): Promise<File> {\n const original = readFileSync(filePath, \"utf8\");\n const content = await formatSource(original, filePath, options, {\n created: true,\n });\n // Only a file this call rewrote is marked. `getMigrationFile` hands back\n // the latest migration of that name, which is an earlier run's when this\n // one changed nothing; that file is formatted already and not reported.\n const written = content !== original;\n if (written) {\n writeFileSync(filePath, content, \"utf8\");\n }\n return {\n path: filePath,\n language: languageFromPath(filePath),\n content,\n status: \"success\",\n ...(written ? { written } : {}),\n };\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(await readMigration(migrationFile, options));\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;;;;;;;;;AA6BA,SAASW,EACP,GACS;CACT,IACEC,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,O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A,eAAsBtD,EACpB,GACA,GACiB;CACjB,IAAIyD,EAAY,WAAW,GACzB,OAAO,CAAC;CAGV,IAAMjC,IAAqB,CAAC,GACtBL,IAAS6B,EAAUpB,CAAO;CA0BhC,OAxBA,MAAMjC,EAAeiC,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAMQ,KAAcqB,GAAa;GACpC,EAAO,KAAK,wBAAwBrB,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAMnB,EACxBL,GACAwB,GACAjB,CACF;GACA,IAAI,CAACuC,GAAS;GACd,MAAM9D,EAAe;GAErB,IAAMiC,IAAgBhC,EACpBuC,EAAW,MACX,WACAR,CACF;GACA,AAAKC,KAILL,EAAW,KAAK,MAAMM,EAAcD,GAAeD,CAAO,CAAC;EAC7D;CACF,CAAC,GAEMJ;AACT"}
|
|
1
|
+
{"version":3,"file":"collections-CFTIAty-.js","names":["__exportAll","NOOP_LOGGER","formatSource","withPocketbase","migrationDelay","getMigrationFile","collections_exports","applyCollectionFieldsPatches","createCollections","dropCollections","planCollectionDrops","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","readMigration","applyFieldChanges","change","f","InvalidArgumentError","index","collection","newFields","body","ensureCollectionFields","have","missing","dropCollectionIdempotent","getCollectionStats","plans","names","stats","specs","getLogger","dropped","original","readFileSync","filePath","content","written","writeFileSync","languageFromPath","collections","created"],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync, writeFileSync } 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 { formatSource } from \"../core/format-result\";\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(await readMigration(migrationFile, options));\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: (name: string) => Promise<{\n id: string;\n fields: CollectionFieldSpec[];\n indexes?: string[];\n }>;\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 const body: Record<string, unknown> = { fields: newFields };\n if (patch.indexes?.length) {\n // PocketBase replaces the list, so the ones it has are sent back.\n const existing = collection.indexes ?? [];\n body.indexes = [\n ...existing,\n ...patch.indexes.filter((index) => !existing.includes(index)),\n ];\n }\n await pb.collections.update(collection.id, body);\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push(await readMigration(migrationFile, options));\n }\n\n return migrations;\n}\n\n/**\n * Adds to an existing collection every field of `spec` it lacks, by name, so a\n * project that created it under an older spec gets the new fields. Fields are\n * only added, never changed or removed. Returns the migration files written.\n */\nexport async function ensureCollectionFields(\n pb: PocketBase,\n spec: CollectionSpec,\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const existing = await pb.collections.getOne(spec.name);\n const have = new Set(\n (existing.fields as { name: string }[]).map((field) => field.name),\n );\n const missing = spec.fields.filter((field) => !have.has(field.name));\n if (missing.length === 0) return [];\n logger.info(\n `Adding ${missing.map((field) => field.name).join(\", \")} to collection \"${spec.name}\"`,\n );\n return applyCollectionFieldsPatches(\n pb,\n [\n {\n collectionName: spec.name,\n changes: missing.map((field) => ({ op: \"add\" as const, field })),\n },\n ],\n options,\n logger,\n );\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(await readMigration(migrationFile, options));\n }\n });\n\n return migrations;\n}\n\n/**\n * A migration PocketBase has just written, as a file of the result, formatted\n * where it lies.\n *\n * PocketBase writes migrations in its own style, which the project's\n * `prettier --check` rejects. Formatting used to wait for `writeResult`, so a\n * run that failed in between (a component that could not be installed, a\n * package install that died) left the migration as PocketBase wrote it. It is\n * formatted here instead, as soon as it is read back, and marked `written` so\n * `writeResult` reports the file, as it did when it was the one to format it,\n * without writing it a second time.\n */\nexport async function readMigration(\n filePath: string,\n options: Pick<Options, \"env\" | \"root\">,\n): Promise<File> {\n const original = readFileSync(filePath, \"utf8\");\n const content = await formatSource(original, filePath, options, {\n created: true,\n });\n // Only a file this call rewrote is marked. `getMigrationFile` hands back\n // the latest migration of that name, which is an earlier run's when this\n // one changed nothing; that file is formatted already and not reported.\n const written = content !== original;\n if (written) {\n writeFileSync(filePath, content, \"utf8\");\n }\n return {\n path: filePath,\n language: languageFromPath(filePath),\n content,\n status: \"success\",\n ...(written ? { written } : {}),\n };\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(await readMigration(migrationFile, options));\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;;;;;;;;;AA6BA,SAASW,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,IAAIJ,EAAS,KAAK,MAAM,CAACG,EAAE,MAAMA,EAAE,EAAE,CAAC,CAAC;CAG1D,OAFIL,EAAU,OAAO,MAAUI,EAAI,IAAIH,EAAM,YAAa,CAAC,IAAUF,IAE9D;EACL,GAAGA;EACH,QAAQD,EAAQ,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n as t } from "./shared-
|
|
3
|
-
import { r as n } from "./modify-file-
|
|
2
|
+
import { n as t } from "./shared-D7-ZAoqr.js";
|
|
3
|
+
import { r as n } from "./modify-file-DRdmZIvW.js";
|
|
4
4
|
import { i as r, n as i, r as a, t as o } from "./env-vars-file-B2zHQZqO.js";
|
|
5
5
|
import { i as s, o as c } from "./ts-morph-helpers-B4KZXP44.js";
|
|
6
6
|
import l from "node:fs";
|
|
@@ -271,4 +271,4 @@ function R(e) {
|
|
|
271
271
|
}
|
|
272
272
|
export { P as modifyEnvVars, F as modifyEnvVarsFiles, k as readEnvVarNames, I as unmodifyEnvVars, L as unmodifyEnvVarsFiles };
|
|
273
273
|
|
|
274
|
-
//# sourceMappingURL=env-vars-
|
|
274
|
+
//# sourceMappingURL=env-vars--fyhY-ew.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env-vars-C3TSZc4f.js","names":["languageFromPath","toDeleteEntry","modifyOutcomeToFile","envVarsFile","ENV_MODULE","envVarEntry","ENV_DECL_CANDIDATES","ensureNamedImport","formatLikeSource","fs","path","VARIABLES","DEFINE","unwrap","current","expr","Node","exportedLocalName","decl","sf","spec","bindsName","name","ni","statement","nameNode","SyntaxKind","id","locateVariables","reExported","local","init","value","arg","object","propertyName","prop","inner","declaredNames","names","quoteOf","addEnvVars","located","quote","unique","dedupe","specs","entries","declared","missing","removeEnvVars","wanted","doomed","seen","newProject","Project","QuoteKind","findEnvDecl","rel","abs","root","readEnvVarNames","filePath","relative","REASONS","addHint","file","reason","removeHint","modifyEnvVars","existing","original","result","changed","modifyEnvVarsFiles","create","modify","unmodifyEnvVars","holdsNothing","unmodifyEnvVarsFiles","deleted","outcome"],"sources":["../../src/runtime/env-vars.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type Expression,\n type ObjectLiteralElementLike,\n type ObjectLiteralExpression,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { modifyOutcomeToFile } from \"./modify-file\";\nimport {\n ENV_DECL_CANDIDATES,\n envVarEntry,\n envVarsFile,\n ENV_MODULE,\n type EnvVarSpec,\n} from \"./env-vars-file\";\nimport { ensureNamedImport, formatLikeSource } from \"./ts-morph-helpers\";\n\nexport { ENV_DECL_CANDIDATES, envVarEntry, envVarsFile, type EnvVarSpec };\n\n/**\n * Declares environment variables in `src/env.ts`, where SvelteKit 3 reads\n * them: a variable it finds no declaration for is not exposed through\n * `$app/env/private` or `$app/env/public` at all.\n *\n * Three shapes of `variables` are edited:\n *\n * - `export const variables = defineEnvVars({ ... })`\n * - `const variables = defineEnvVars({ ... }); export { variables }`\n * - either of the above with a plain object literal in place of the call\n *\n * Entries are matched by property name, quoted or not, and an entry that is\n * already there is never touched: a project that declared `STRIPE_SECRET_KEY`\n * as required keeps it required.\n */\n\nconst VARIABLES = \"variables\";\nconst DEFINE = \"defineEnvVars\";\n\nexport type EnvVarsUnsupported =\n /** `variables` is exported some other way: a function, `export let variables;`, a re-export. */\n | \"not-variable\"\n /** `variables` is not an object literal or `defineEnvVars({ ... })`. */\n | \"not-object\"\n /** The object spreads another one in, which may already declare the names. */\n | \"spread\"\n /** A computed key (`[name]: ...`) whose name can't be read. */\n | \"computed-key\";\n\nexport type EnvVarsEditResult =\n | { status: \"changed\" | \"unchanged\" }\n | { status: \"unsupported\"; reason: EnvVarsUnsupported };\n\ntype Located =\n | { kind: \"object\"; object: ObjectLiteralExpression }\n | { kind: \"missing\" }\n | { kind: \"unsupported\"; reason: EnvVarsUnsupported };\n\nfunction unwrap(expr: Expression): Expression {\n let current = expr;\n for (;;) {\n if (\n Node.isParenthesizedExpression(current) ||\n Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current)\n ) {\n current = current.getExpression();\n continue;\n }\n return current;\n }\n}\n\n/** The local name exported as `variables`: itself, or `x` in `export { x as variables }`. */\nfunction exportedLocalName(sf: SourceFile): string | null | \"re-export\" {\n for (const decl of sf.getExportDeclarations()) {\n for (const spec of decl.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== VARIABLES) continue;\n if (decl.getModuleSpecifier()) return \"re-export\";\n return spec.getName();\n }\n }\n return null;\n}\n\n/** A top-level import or destructuring pattern that binds `name`. */\nfunction bindsName(sf: SourceFile, name: string): boolean {\n const imported = sf\n .getImportDeclarations()\n .some(\n (decl) =>\n decl.getDefaultImport()?.getText() === name ||\n decl.getNamespaceImport()?.getText() === name ||\n decl\n .getNamedImports()\n .some(\n (ni) => (ni.getAliasNode()?.getText() ?? ni.getName()) === name,\n ),\n );\n if (imported) return true;\n return sf.getVariableStatements().some((statement) =>\n statement.getDeclarations().some((decl) => {\n const nameNode = decl.getNameNode();\n return (\n !Node.isIdentifier(nameNode) &&\n nameNode\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === name &&\n (Node.isBindingElement(id.getParent()) ||\n Node.isShorthandPropertyAssignment(id.getParent())),\n )\n );\n }),\n );\n}\n\nfunction locateVariables(sf: SourceFile): Located {\n const reExported = exportedLocalName(sf);\n if (reExported === \"re-export\") {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const local = reExported ?? VARIABLES;\n\n const decl = sf.getVariableDeclaration(local);\n if (!decl) {\n // A function, class, import or destructured binding of that name,\n // exported or not, is not ours to replace.\n const taken =\n sf.getFunction(local) ?? sf.getClass(local) ?? sf.getEnum(local);\n if (taken || reExported || bindsName(sf, local)) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n return { kind: \"missing\" };\n }\n if (!reExported && !decl.isExported()) {\n // `const variables = ...` that SvelteKit can't see; exporting it is the\n // developer's call, not ours.\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n if (!Node.isIdentifier(decl.getNameNode())) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const init = decl.getInitializer();\n if (!init) return { kind: \"unsupported\", reason: \"not-variable\" };\n\n const value = unwrap(init);\n if (Node.isObjectLiteralExpression(value)) {\n return { kind: \"object\", object: value };\n }\n if (\n Node.isCallExpression(value) &&\n value.getExpression().getText() === DEFINE\n ) {\n const arg = value.getArguments()[0];\n const object = arg && unwrap(arg as Expression);\n if (object && Node.isObjectLiteralExpression(object)) {\n return { kind: \"object\", object };\n }\n }\n return { kind: \"unsupported\", reason: \"not-object\" };\n}\n\n/** A property's name as SvelteKit sees it, `null` for a spread or computed key. */\nfunction propertyName(prop: ObjectLiteralElementLike): string | null {\n if (Node.isSpreadAssignment(prop)) return null;\n const nameNode = prop.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) {\n const inner = nameNode.getExpression();\n return Node.isStringLiteral(inner) ||\n Node.isNoSubstitutionTemplateLiteral(inner)\n ? inner.getLiteralText()\n : null;\n }\n if (\n Node.isStringLiteral(nameNode) ||\n Node.isNoSubstitutionTemplateLiteral(nameNode)\n ) {\n return nameNode.getLiteralText();\n }\n return nameNode.getText();\n}\n\nfunction declaredNames(\n object: ObjectLiteralExpression,\n): Set<string> | EnvVarsUnsupported {\n const names = new Set<string>();\n for (const prop of object.getProperties()) {\n if (Node.isSpreadAssignment(prop)) return \"spread\";\n const name = propertyName(prop);\n if (name === null) return \"computed-key\";\n names.add(name);\n }\n return names;\n}\n\n/** The quote the file already writes its strings with. */\nfunction quoteOf(sf: SourceFile): \"'\" | '\"' {\n const first = sf.getFirstDescendantByKind(SyntaxKind.StringLiteral);\n return first?.getText().startsWith('\"') ? '\"' : \"'\";\n}\n\n/**\n * Add a declaration for every spec `sf` doesn't declare yet. Creates\n * `export const variables = defineEnvVars({ ... })`, and its import, when the\n * file has no `variables` at all. Neither formats nor saves.\n */\nexport function addEnvVars(\n sf: SourceFile,\n specs: EnvVarSpec[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const quote = quoteOf(sf);\n\n if (located.kind === \"missing\") {\n const unique = dedupe(specs);\n if (unique.length === 0) return { status: \"unchanged\" };\n ensureNamedImport(sf, ENV_MODULE, DEFINE);\n const entries = unique\n .map((spec) => `\\t${envVarEntry(spec, { quote })}`)\n .join(\",\\n\");\n sf.addStatements(\n `\\nexport const ${VARIABLES} = ${DEFINE}({\\n${entries}\\n});`,\n );\n return { status: \"changed\" };\n }\n\n const declared = declaredNames(located.object);\n if (typeof declared === \"string\") {\n return { status: \"unsupported\", reason: declared };\n }\n const missing = dedupe(specs).filter((spec) => !declared.has(spec.name));\n if (missing.length === 0) return { status: \"unchanged\" };\n for (const spec of missing) {\n located.object.addProperty(envVarEntry(spec, { quote }));\n }\n return { status: \"changed\" };\n}\n\n/**\n * Remove the declarations of `names` from `sf`. A file with no `variables`,\n * or none of the names, is unchanged. Neither formats nor saves.\n */\nexport function removeEnvVars(\n sf: SourceFile,\n names: string[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"missing\") return { status: \"unchanged\" };\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const wanted = new Set(names);\n const doomed = located.object.getProperties().filter((prop) => {\n const name = propertyName(prop);\n return name !== null && wanted.has(name);\n });\n if (doomed.length === 0) return { status: \"unchanged\" };\n for (const prop of doomed.reverse()) prop.remove();\n if (located.object.getProperties().length === 0) {\n located.object.replaceWithText(\"{}\");\n }\n return { status: \"changed\" };\n}\n\nfunction dedupe(specs: EnvVarSpec[]): EnvVarSpec[] {\n const seen = new Set<string>();\n return specs.filter((spec) => {\n if (seen.has(spec.name)) return false;\n seen.add(spec.name);\n return true;\n });\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/** The project's declaration file: `src/env.ts` or `src/env.js`, if either exists. */\nexport function findEnvDecl(root: string): string | null {\n for (const rel of ENV_DECL_CANDIDATES) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\n/**\n * The names `src/env.ts` (or `src/env.js`) declares. Spreads and computed\n * keys it can't read are skipped rather than failing the whole read, so a\n * declaration file this module couldn't edit still reports what it can. No\n * file, or no `variables` this can read, is an empty set.\n */\nexport function readEnvVarNames(root: string): Set<string> {\n const filePath = findEnvDecl(root);\n if (!filePath) return new Set();\n\n const sf = newProject().addSourceFileAtPath(filePath);\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return new Set();\n\n const names = new Set<string>();\n for (const prop of located.object.getProperties()) {\n const name = propertyName(prop);\n if (name !== null) names.add(name);\n }\n return names;\n}\n\nfunction relative(root: string, filePath: string): string {\n return path.relative(root, filePath).split(path.sep).join(\"/\");\n}\n\nconst REASONS: Record<EnvVarsUnsupported, string> = {\n \"not-variable\": \"its `variables` export is not a variable this can edit\",\n \"not-object\":\n \"`variables` is not an object literal or a `defineEnvVars({ ... })` call\",\n spread: \"`variables` spreads in another object\",\n \"computed-key\": \"`variables` has a computed key\",\n};\n\nfunction addHint(\n file: string,\n reason: EnvVarsUnsupported,\n specs: EnvVarSpec[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n \"Declare these in the object passed to defineEnvVars() (or exported as `variables`), skipping any already there:\",\n \"\",\n ...dedupe(specs).map((spec) => `${envVarEntry(spec)},`),\n ].join(\"\\n\");\n}\n\nfunction removeHint(\n file: string,\n reason: EnvVarsUnsupported,\n names: string[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n `Remove these declarations from \\`variables\\` by hand: ${names.join(\", \")}`,\n ].join(\"\\n\");\n}\n\nexport interface ModifyEnvVarsResult {\n /** `src/env.ts` to create, when the project has no declaration file. */\n create?: File;\n /** The existing declaration file, already saved when `outcome` changed it. */\n modify?: { filePath: string; outcome: ModifyOutcome };\n}\n\n/**\n * Declare `specs` in the project's `src/env.ts` (or `src/env.js`). Existing\n * entries are never touched.\n *\n * - No declaration file: `create` holds a new `src/env.ts` (always `.ts`,\n * written like the CLI templates' one); nothing is written yet.\n * - An existing file is edited and saved in place, and `modify` reports it\n * like every other runtime modifier: turn it into a File with\n * `modifyOutcomeToFile` (or use {@link modifyEnvVarsFiles}).\n * - A file whose `variables` can't be edited safely is left alone, and the\n * `failed` outcome's message lists the exact entries to paste.\n */\nexport function modifyEnvVars(\n root: string,\n specs: EnvVarSpec[],\n): ModifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n if (dedupe(specs).length === 0) return {};\n const filePath = path.join(root, ENV_DECL_CANDIDATES[0]);\n return {\n create: {\n path: filePath,\n language: languageFromPath(filePath),\n content: envVarsFile(specs),\n status: \"success\",\n },\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = addEnvVars(sf, specs);\n if (result.status === \"unsupported\") {\n return {\n modify: {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: addHint(relative(root, existing), result.reason, specs),\n },\n },\n };\n }\n if (result.status === \"unchanged\") {\n return {\n modify: {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n },\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n modify: { filePath: existing, outcome: { status: \"success\", changed } },\n };\n}\n\n/** {@link modifyEnvVars} as the File entries a pattern's Result carries. */\nexport function modifyEnvVarsFiles(\n root: string,\n specs: EnvVarSpec[],\n): { create: File | null; modify: File | null } {\n const { create, modify } = modifyEnvVars(root, specs);\n return {\n create: create ?? null,\n modify: modify\n ? modifyOutcomeToFile(modify.filePath, modify.outcome)\n : null,\n };\n}\n\nexport interface UnmodifyEnvVarsResult {\n filePath: string;\n outcome: ModifyOutcome;\n /**\n * The revert left nothing but the `defineEnvVars` import and an empty\n * `variables`. The emptied file has been saved; the caller reports it as a\n * delete (`toDeleteEntry(filePath)`) instead of a modify, as\n * {@link unmodifyEnvVarsFiles} does.\n */\n deleted: boolean;\n}\n\n/**\n * Remove the declarations of `names` from `src/env.ts` (or `.js`). A project\n * without the file, or without the names, is a no-op success.\n */\nexport function unmodifyEnvVars(\n root: string,\n names: string[],\n): UnmodifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n return {\n filePath: path.join(root, ENV_DECL_CANDIDATES[0]),\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = removeEnvVars(sf, names);\n if (result.status === \"unsupported\") {\n return {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: removeHint(relative(root, existing), result.reason, names),\n },\n deleted: false,\n };\n }\n if (result.status === \"unchanged\") {\n return {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n filePath: existing,\n outcome: { status: \"success\", changed },\n deleted: changed && holdsNothing(sf),\n };\n}\n\n/** {@link unmodifyEnvVars} as the File entries a pattern's Result carries. */\nexport function unmodifyEnvVarsFiles(\n root: string,\n names: string[],\n): { modify: File | null; delete: File | null } {\n const { filePath, outcome, deleted } = unmodifyEnvVars(root, names);\n if (deleted) return { modify: null, delete: toDeleteEntry(filePath) };\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * Only the `defineEnvVars` import, an empty `variables` and its\n * `export { variables }` are left. Comments don't count.\n */\nfunction holdsNothing(sf: SourceFile): boolean {\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return false;\n if (located.object.getProperties().length > 0) return false;\n const decl = located.object.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n return sf.getStatements().every((statement: Statement) => {\n if (statement === decl) return true;\n if (Node.isEmptyStatement(statement)) return true;\n if (Node.isImportDeclaration(statement)) {\n return (\n statement.getModuleSpecifierValue() === ENV_MODULE &&\n !statement.getDefaultImport() &&\n !statement.getNamespaceImport() &&\n statement.getNamedImports().every((ni) => ni.getName() === DEFINE)\n );\n }\n if (Node.isExportDeclaration(statement)) {\n return (\n !statement.getModuleSpecifier() &&\n statement\n .getNamedExports()\n .every(\n (spec) =>\n (spec.getAliasNode()?.getText() ?? spec.getName()) === VARIABLES,\n )\n );\n }\n return false;\n });\n}\n"],"mappings":";;;;;;;;;AA4CA,IAAMW,IAAY,aACZC,IAAS;AAqBf,SAASC,EAAO,GAA8B;CAC5C,IAAIC,IAAUC;CACd,SACE,IACEC,EAAK,0BAA0BF,CAAO,KACtCE,EAAK,eAAeF,CAAO,KAC3BE,EAAK,sBAAsBF,CAAO,GAElC,IAAUA,EAAQ,cAAc;MAGlC,OAAOA;AAEX;AAGA,SAASG,EAAkB,GAA6C;CACtE,KAAK,IAAMC,KAAQC,EAAG,sBAAsB,GAC1C,KAAK,IAAMC,KAAQF,EAAK,gBAAgB,GAEtC,KADiBE,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAK,QAAQ,OAC/CT,GAEjB,OADIO,EAAK,mBAAmB,IAAU,cAC/BE,EAAK,QAAQ;CAGxB,OAAO;AACT;AAGA,SAASC,EAAU,GAAgB,GAAuB;CAcxD,OAbiBF,EACd,sBAAsB,CAAC,CACvB,MACE,MACCD,EAAK,iBAAiB,CAAC,EAAE,QAAQ,MAAMI,KACvCJ,EAAK,mBAAmB,CAAC,EAAE,QAAQ,MAAMI,KACzCJ,EACG,gBAAgB,CAAC,CACjB,MACE,OAAQK,EAAG,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAG,QAAQ,OAAOD,CAC7D,CAEJ,IAAiB,KACdH,EAAG,sBAAsB,CAAC,CAAC,MAAM,MACtCK,EAAU,gBAAgB,CAAC,CAAC,MAAM,MAAS;EACzC,IAAMC,IAAWP,EAAK,YAAY;EAClC,OACE,CAACF,EAAK,aAAaS,CAAQ,KAC3BA,EACG,qBAAqBC,EAAW,UAAU,CAAC,CAC3C,MACE,MACC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AC,SAAS,GAAG,OAAO;CACtD,IAAMxB,IAAOwB,EAAQ,OAAO,uBAC1BhB,EAAW,iBACb;CACA,OAAOP,EAAG,cAAc,CAAC,CAAC,OAAO,MAC3BK,MAAcN,KACdF,EAAK,iBAAiBQ,CAAS,IAAU,KACzCR,EAAK,oBAAoBQ,CAAS,IAElCA,EAAU,wBAAwB,MAAA,uBAClC,CAACA,EAAU,iBAAiB,KAC5B,CAACA,EAAU,mBAAmB,KAC9BA,EAAU,gBAAgB,CAAC,CAAC,OAAO,MAAOD,EAAG,QAAQ,MAAMX,CAAM,IAGjEI,EAAK,oBAAoBQ,CAAS,IAElC,CAACA,EAAU,mBAAmB,KAC9BA,EACG,gBAAgB,CAAC,CACjB,OACE,OACEJ,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAK,QAAQ,OAAOT,CAC3D,IAGC,EACR;AACH"}
|
|
1
|
+
{"version":3,"file":"env-vars--fyhY-ew.js","names":["languageFromPath","toDeleteEntry","modifyOutcomeToFile","envVarsFile","ENV_MODULE","envVarEntry","ENV_DECL_CANDIDATES","ensureNamedImport","formatLikeSource","fs","path","VARIABLES","DEFINE","unwrap","current","expr","Node","exportedLocalName","decl","sf","spec","bindsName","name","ni","statement","nameNode","SyntaxKind","id","locateVariables","reExported","local","init","value","arg","object","propertyName","prop","inner","declaredNames","names","quoteOf","addEnvVars","located","quote","unique","dedupe","specs","entries","declared","missing","removeEnvVars","wanted","doomed","seen","newProject","Project","QuoteKind","findEnvDecl","rel","abs","root","readEnvVarNames","filePath","relative","REASONS","addHint","file","reason","removeHint","modifyEnvVars","existing","original","result","changed","modifyEnvVarsFiles","create","modify","unmodifyEnvVars","holdsNothing","unmodifyEnvVarsFiles","deleted","outcome"],"sources":["../../src/runtime/env-vars.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type Expression,\n type ObjectLiteralElementLike,\n type ObjectLiteralExpression,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { modifyOutcomeToFile } from \"./modify-file\";\nimport {\n ENV_DECL_CANDIDATES,\n envVarEntry,\n envVarsFile,\n ENV_MODULE,\n type EnvVarSpec,\n} from \"./env-vars-file\";\nimport { ensureNamedImport, formatLikeSource } from \"./ts-morph-helpers\";\n\nexport { ENV_DECL_CANDIDATES, envVarEntry, envVarsFile, type EnvVarSpec };\n\n/**\n * Declares environment variables in `src/env.ts`, where SvelteKit 3 reads\n * them: a variable it finds no declaration for is not exposed through\n * `$app/env/private` or `$app/env/public` at all.\n *\n * Three shapes of `variables` are edited:\n *\n * - `export const variables = defineEnvVars({ ... })`\n * - `const variables = defineEnvVars({ ... }); export { variables }`\n * - either of the above with a plain object literal in place of the call\n *\n * Entries are matched by property name, quoted or not, and an entry that is\n * already there is never touched: a project that declared `STRIPE_SECRET_KEY`\n * as required keeps it required.\n */\n\nconst VARIABLES = \"variables\";\nconst DEFINE = \"defineEnvVars\";\n\nexport type EnvVarsUnsupported =\n /** `variables` is exported some other way: a function, `export let variables;`, a re-export. */\n | \"not-variable\"\n /** `variables` is not an object literal or `defineEnvVars({ ... })`. */\n | \"not-object\"\n /** The object spreads another one in, which may already declare the names. */\n | \"spread\"\n /** A computed key (`[name]: ...`) whose name can't be read. */\n | \"computed-key\";\n\nexport type EnvVarsEditResult =\n | { status: \"changed\" | \"unchanged\" }\n | { status: \"unsupported\"; reason: EnvVarsUnsupported };\n\ntype Located =\n | { kind: \"object\"; object: ObjectLiteralExpression }\n | { kind: \"missing\" }\n | { kind: \"unsupported\"; reason: EnvVarsUnsupported };\n\nfunction unwrap(expr: Expression): Expression {\n let current = expr;\n for (;;) {\n if (\n Node.isParenthesizedExpression(current) ||\n Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current)\n ) {\n current = current.getExpression();\n continue;\n }\n return current;\n }\n}\n\n/** The local name exported as `variables`: itself, or `x` in `export { x as variables }`. */\nfunction exportedLocalName(sf: SourceFile): string | null | \"re-export\" {\n for (const decl of sf.getExportDeclarations()) {\n for (const spec of decl.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== VARIABLES) continue;\n if (decl.getModuleSpecifier()) return \"re-export\";\n return spec.getName();\n }\n }\n return null;\n}\n\n/** A top-level import or destructuring pattern that binds `name`. */\nfunction bindsName(sf: SourceFile, name: string): boolean {\n const imported = sf\n .getImportDeclarations()\n .some(\n (decl) =>\n decl.getDefaultImport()?.getText() === name ||\n decl.getNamespaceImport()?.getText() === name ||\n decl\n .getNamedImports()\n .some(\n (ni) => (ni.getAliasNode()?.getText() ?? ni.getName()) === name,\n ),\n );\n if (imported) return true;\n return sf.getVariableStatements().some((statement) =>\n statement.getDeclarations().some((decl) => {\n const nameNode = decl.getNameNode();\n return (\n !Node.isIdentifier(nameNode) &&\n nameNode\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === name &&\n (Node.isBindingElement(id.getParent()) ||\n Node.isShorthandPropertyAssignment(id.getParent())),\n )\n );\n }),\n );\n}\n\nfunction locateVariables(sf: SourceFile): Located {\n const reExported = exportedLocalName(sf);\n if (reExported === \"re-export\") {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const local = reExported ?? VARIABLES;\n\n const decl = sf.getVariableDeclaration(local);\n if (!decl) {\n // A function, class, import or destructured binding of that name,\n // exported or not, is not ours to replace.\n const taken =\n sf.getFunction(local) ?? sf.getClass(local) ?? sf.getEnum(local);\n if (taken || reExported || bindsName(sf, local)) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n return { kind: \"missing\" };\n }\n if (!reExported && !decl.isExported()) {\n // `const variables = ...` that SvelteKit can't see; exporting it is the\n // developer's call, not ours.\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n if (!Node.isIdentifier(decl.getNameNode())) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const init = decl.getInitializer();\n if (!init) return { kind: \"unsupported\", reason: \"not-variable\" };\n\n const value = unwrap(init);\n if (Node.isObjectLiteralExpression(value)) {\n return { kind: \"object\", object: value };\n }\n if (\n Node.isCallExpression(value) &&\n value.getExpression().getText() === DEFINE\n ) {\n const arg = value.getArguments()[0];\n const object = arg && unwrap(arg as Expression);\n if (object && Node.isObjectLiteralExpression(object)) {\n return { kind: \"object\", object };\n }\n }\n return { kind: \"unsupported\", reason: \"not-object\" };\n}\n\n/** A property's name as SvelteKit sees it, `null` for a spread or computed key. */\nfunction propertyName(prop: ObjectLiteralElementLike): string | null {\n if (Node.isSpreadAssignment(prop)) return null;\n const nameNode = prop.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) {\n const inner = nameNode.getExpression();\n return Node.isStringLiteral(inner) ||\n Node.isNoSubstitutionTemplateLiteral(inner)\n ? inner.getLiteralText()\n : null;\n }\n if (\n Node.isStringLiteral(nameNode) ||\n Node.isNoSubstitutionTemplateLiteral(nameNode)\n ) {\n return nameNode.getLiteralText();\n }\n return nameNode.getText();\n}\n\nfunction declaredNames(\n object: ObjectLiteralExpression,\n): Set<string> | EnvVarsUnsupported {\n const names = new Set<string>();\n for (const prop of object.getProperties()) {\n if (Node.isSpreadAssignment(prop)) return \"spread\";\n const name = propertyName(prop);\n if (name === null) return \"computed-key\";\n names.add(name);\n }\n return names;\n}\n\n/** The quote the file already writes its strings with. */\nfunction quoteOf(sf: SourceFile): \"'\" | '\"' {\n const first = sf.getFirstDescendantByKind(SyntaxKind.StringLiteral);\n return first?.getText().startsWith('\"') ? '\"' : \"'\";\n}\n\n/**\n * Add a declaration for every spec `sf` doesn't declare yet. Creates\n * `export const variables = defineEnvVars({ ... })`, and its import, when the\n * file has no `variables` at all. Neither formats nor saves.\n */\nexport function addEnvVars(\n sf: SourceFile,\n specs: EnvVarSpec[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const quote = quoteOf(sf);\n\n if (located.kind === \"missing\") {\n const unique = dedupe(specs);\n if (unique.length === 0) return { status: \"unchanged\" };\n ensureNamedImport(sf, ENV_MODULE, DEFINE);\n const entries = unique\n .map((spec) => `\\t${envVarEntry(spec, { quote })}`)\n .join(\",\\n\");\n sf.addStatements(\n `\\nexport const ${VARIABLES} = ${DEFINE}({\\n${entries}\\n});`,\n );\n return { status: \"changed\" };\n }\n\n const declared = declaredNames(located.object);\n if (typeof declared === \"string\") {\n return { status: \"unsupported\", reason: declared };\n }\n const missing = dedupe(specs).filter((spec) => !declared.has(spec.name));\n if (missing.length === 0) return { status: \"unchanged\" };\n for (const spec of missing) {\n located.object.addProperty(envVarEntry(spec, { quote }));\n }\n return { status: \"changed\" };\n}\n\n/**\n * Remove the declarations of `names` from `sf`. A file with no `variables`,\n * or none of the names, is unchanged. Neither formats nor saves.\n */\nexport function removeEnvVars(\n sf: SourceFile,\n names: string[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"missing\") return { status: \"unchanged\" };\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const wanted = new Set(names);\n const doomed = located.object.getProperties().filter((prop) => {\n const name = propertyName(prop);\n return name !== null && wanted.has(name);\n });\n if (doomed.length === 0) return { status: \"unchanged\" };\n for (const prop of doomed.reverse()) prop.remove();\n if (located.object.getProperties().length === 0) {\n located.object.replaceWithText(\"{}\");\n }\n return { status: \"changed\" };\n}\n\nfunction dedupe(specs: EnvVarSpec[]): EnvVarSpec[] {\n const seen = new Set<string>();\n return specs.filter((spec) => {\n if (seen.has(spec.name)) return false;\n seen.add(spec.name);\n return true;\n });\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/** The project's declaration file: `src/env.ts` or `src/env.js`, if either exists. */\nexport function findEnvDecl(root: string): string | null {\n for (const rel of ENV_DECL_CANDIDATES) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\n/**\n * The names `src/env.ts` (or `src/env.js`) declares. Spreads and computed\n * keys it can't read are skipped rather than failing the whole read, so a\n * declaration file this module couldn't edit still reports what it can. No\n * file, or no `variables` this can read, is an empty set.\n */\nexport function readEnvVarNames(root: string): Set<string> {\n const filePath = findEnvDecl(root);\n if (!filePath) return new Set();\n\n const sf = newProject().addSourceFileAtPath(filePath);\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return new Set();\n\n const names = new Set<string>();\n for (const prop of located.object.getProperties()) {\n const name = propertyName(prop);\n if (name !== null) names.add(name);\n }\n return names;\n}\n\nfunction relative(root: string, filePath: string): string {\n return path.relative(root, filePath).split(path.sep).join(\"/\");\n}\n\nconst REASONS: Record<EnvVarsUnsupported, string> = {\n \"not-variable\": \"its `variables` export is not a variable this can edit\",\n \"not-object\":\n \"`variables` is not an object literal or a `defineEnvVars({ ... })` call\",\n spread: \"`variables` spreads in another object\",\n \"computed-key\": \"`variables` has a computed key\",\n};\n\nfunction addHint(\n file: string,\n reason: EnvVarsUnsupported,\n specs: EnvVarSpec[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n \"Declare these in the object passed to defineEnvVars() (or exported as `variables`), skipping any already there:\",\n \"\",\n ...dedupe(specs).map((spec) => `${envVarEntry(spec)},`),\n ].join(\"\\n\");\n}\n\nfunction removeHint(\n file: string,\n reason: EnvVarsUnsupported,\n names: string[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n `Remove these declarations from \\`variables\\` by hand: ${names.join(\", \")}`,\n ].join(\"\\n\");\n}\n\nexport interface ModifyEnvVarsResult {\n /** `src/env.ts` to create, when the project has no declaration file. */\n create?: File;\n /** The existing declaration file, already saved when `outcome` changed it. */\n modify?: { filePath: string; outcome: ModifyOutcome };\n}\n\n/**\n * Declare `specs` in the project's `src/env.ts` (or `src/env.js`). Existing\n * entries are never touched.\n *\n * - No declaration file: `create` holds a new `src/env.ts` (always `.ts`,\n * written like the CLI templates' one); nothing is written yet.\n * - An existing file is edited and saved in place, and `modify` reports it\n * like every other runtime modifier: turn it into a File with\n * `modifyOutcomeToFile` (or use {@link modifyEnvVarsFiles}).\n * - A file whose `variables` can't be edited safely is left alone, and the\n * `failed` outcome's message lists the exact entries to paste.\n */\nexport function modifyEnvVars(\n root: string,\n specs: EnvVarSpec[],\n): ModifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n if (dedupe(specs).length === 0) return {};\n const filePath = path.join(root, ENV_DECL_CANDIDATES[0]);\n return {\n create: {\n path: filePath,\n language: languageFromPath(filePath),\n content: envVarsFile(specs),\n status: \"success\",\n },\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = addEnvVars(sf, specs);\n if (result.status === \"unsupported\") {\n return {\n modify: {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: addHint(relative(root, existing), result.reason, specs),\n },\n },\n };\n }\n if (result.status === \"unchanged\") {\n return {\n modify: {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n },\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n modify: { filePath: existing, outcome: { status: \"success\", changed } },\n };\n}\n\n/** {@link modifyEnvVars} as the File entries a pattern's Result carries. */\nexport function modifyEnvVarsFiles(\n root: string,\n specs: EnvVarSpec[],\n): { create: File | null; modify: File | null } {\n const { create, modify } = modifyEnvVars(root, specs);\n return {\n create: create ?? null,\n modify: modify\n ? modifyOutcomeToFile(modify.filePath, modify.outcome)\n : null,\n };\n}\n\nexport interface UnmodifyEnvVarsResult {\n filePath: string;\n outcome: ModifyOutcome;\n /**\n * The revert left nothing but the `defineEnvVars` import and an empty\n * `variables`. The emptied file has been saved; the caller reports it as a\n * delete (`toDeleteEntry(filePath)`) instead of a modify, as\n * {@link unmodifyEnvVarsFiles} does.\n */\n deleted: boolean;\n}\n\n/**\n * Remove the declarations of `names` from `src/env.ts` (or `.js`). A project\n * without the file, or without the names, is a no-op success.\n */\nexport function unmodifyEnvVars(\n root: string,\n names: string[],\n): UnmodifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n return {\n filePath: path.join(root, ENV_DECL_CANDIDATES[0]),\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = removeEnvVars(sf, names);\n if (result.status === \"unsupported\") {\n return {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: removeHint(relative(root, existing), result.reason, names),\n },\n deleted: false,\n };\n }\n if (result.status === \"unchanged\") {\n return {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n filePath: existing,\n outcome: { status: \"success\", changed },\n deleted: changed && holdsNothing(sf),\n };\n}\n\n/** {@link unmodifyEnvVars} as the File entries a pattern's Result carries. */\nexport function unmodifyEnvVarsFiles(\n root: string,\n names: string[],\n): { modify: File | null; delete: File | null } {\n const { filePath, outcome, deleted } = unmodifyEnvVars(root, names);\n if (deleted) return { modify: null, delete: toDeleteEntry(filePath) };\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * Only the `defineEnvVars` import, an empty `variables` and its\n * `export { variables }` are left. Comments don't count.\n */\nfunction holdsNothing(sf: SourceFile): boolean {\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return false;\n if (located.object.getProperties().length > 0) return false;\n const decl = located.object.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n return sf.getStatements().every((statement: Statement) => {\n if (statement === decl) return true;\n if (Node.isEmptyStatement(statement)) return true;\n if (Node.isImportDeclaration(statement)) {\n return (\n statement.getModuleSpecifierValue() === ENV_MODULE &&\n !statement.getDefaultImport() &&\n !statement.getNamespaceImport() &&\n statement.getNamedImports().every((ni) => ni.getName() === DEFINE)\n );\n }\n if (Node.isExportDeclaration(statement)) {\n return (\n !statement.getModuleSpecifier() &&\n statement\n .getNamedExports()\n .every(\n (spec) =>\n (spec.getAliasNode()?.getText() ?? spec.getName()) === VARIABLES,\n )\n );\n }\n return false;\n });\n}\n"],"mappings":";;;;;;;;;AA4CA,IAAMW,IAAY,aACZC,IAAS;AAqBf,SAASC,EAAO,GAA8B;CAC5C,IAAIC,IAAUC;CACd,SACE,IACEC,EAAK,0BAA0BF,CAAO,KACtCE,EAAK,eAAeF,CAAO,KAC3BE,EAAK,sBAAsBF,CAAO,GAElC,IAAUA,EAAQ,cAAc;MAGlC,OAAOA;AAEX;AAGA,SAASG,EAAkB,GAA6C;CACtE,KAAK,IAAMC,KAAQC,EAAG,sBAAsB,GAC1C,KAAK,IAAMC,KAAQF,EAAK,gBAAgB,GAEtC,KADiBE,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAK,QAAQ,OAC/CT,GAEjB,OADIO,EAAK,mBAAmB,IAAU,cAC/BE,EAAK,QAAQ;CAGxB,OAAO;AACT;AAGA,SAASC,EAAU,GAAgB,GAAuB;CAcxD,OAbiBF,EACd,sBAAsB,CAAC,CACvB,MACE,MACCD,EAAK,iBAAiB,CAAC,EAAE,QAAQ,MAAMI,KACvCJ,EAAK,mBAAmB,CAAC,EAAE,QAAQ,MAAMI,KACzCJ,EACG,gBAAgB,CAAC,CACjB,MACE,OAAQK,EAAG,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAG,QAAQ,OAAOD,CAC7D,CAEJ,IAAiB,KACdH,EAAG,sBAAsB,CAAC,CAAC,MAAM,MACtCK,EAAU,gBAAgB,CAAC,CAAC,MAAM,MAAS;EACzC,IAAMC,IAAWP,EAAK,YAAY;EAClC,OACE,CAACF,EAAK,aAAaS,CAAQ,KAC3BA,EACG,qBAAqBC,EAAW,UAA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Q,OAAO,cAAc,CAAC,CAAC,SAAS,GAAG,OAAO;CACtD,IAAMxB,IAAOwB,EAAQ,OAAO,uBAC1BhB,EAAW,iBACb;CACA,OAAOP,EAAG,cAAc,CAAC,CAAC,OAAO,MAC3BK,MAAcN,KACdF,EAAK,iBAAiBQ,CAAS,IAAU,KACzCR,EAAK,oBAAoBQ,CAAS,IAElCA,EAAU,wBAAwB,MAAA,uBAClC,CAACA,EAAU,iBAAiB,KAC5B,CAACA,EAAU,mBAAmB,KAC9BA,EAAU,gBAAgB,CAAC,CAAC,OAAO,MAAOD,EAAG,QAAQ,MAAMX,CAAM,IAGjEI,EAAK,oBAAoBQ,CAAS,IAElC,CAACA,EAAU,mBAAmB,KAC9BA,EACG,gBAAgB,CAAC,CACjB,OACE,OACEJ,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAK,QAAQ,OAAOT,CAC3D,IAGC,EACR;AACH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as e, d as t, f as n, g as r, h as i, i as a, l as o, m as s, o as c, p as l, r as u, s as d, t as f, u as p } from "./generate-CL7wG0ZC.js";
|
|
2
2
|
import { t as m } from "./providers-DrK_hjSr.js";
|
|
3
3
|
import { t as h } from "./util-mXrQ89nG.js";
|
|
4
|
-
import { n as g } from "./shared-
|
|
4
|
+
import { n as g } from "./shared-D7-ZAoqr.js";
|
|
5
5
|
// src/patterns/disable/ai/generate.ts
|
|
6
6
|
var _ = /* #__PURE__ */ Object.assign({
|
|
7
7
|
"../../enable/ai/creates/src/routes/(public)/ai/+page.svelte": r,
|
|
@@ -54,4 +54,4 @@ async function T(t) {
|
|
|
54
54
|
}
|
|
55
55
|
export { T as i, w as n, b as r, C as t };
|
|
56
56
|
|
|
57
|
-
//# sourceMappingURL=generate-
|
|
57
|
+
//# sourceMappingURL=generate-B2z0kA5C.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-
|
|
1
|
+
{"version":3,"file":"generate-B2z0kA5C.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__2_0_","__import_glob__2_1_","__import_glob__2_2_","PROVIDER_PACKAGES","ai_default","server_test_default$1","_page_default","_server_default","PROVIDERS","ai_default$2","server_test_default","demoDir","_server_default$1","PACKAGES","envEditsFor","DEMO_DIR","ai_default$1","allProviderPaths","appRelativePath","toDeleteEntry","createsRaw","createsAppModeRaw","providersRaw","demoDirs","dirs","options","atDemoDir","path","dir","aiPaths","paths","raw","prefix","key","allEnvEdits","provider","allEnvNames","variable","generate"],"sources":["../../src/patterns/disable/ai/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { appRelativePath } from \"../../../core/util\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport {\n DEMO_DIR,\n demoDir,\n envEditsFor,\n PACKAGES,\n PROVIDER_PACKAGES,\n PROVIDERS,\n} from \"../../enable/ai/generate\";\n\nconst createsRaw = import.meta.glob<string>(\"../../enable/ai/creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst createsAppModeRaw = import.meta.glob<string>(\n \"../../enable/ai/creates-app-mode/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\nconst providersRaw = import.meta.glob<string>(\"../../enable/ai/providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\ntype DemoOptions = Pick<Options, \"features\" | \"routeGroups\">;\n\n/**\n * Where enable-ai may have put the demo page in this project: the group it\n * picks with auth on and with it off. Auth enabled after AI leaves the page\n * in the public group, so both are candidates.\n */\nexport function demoDirs(options: DemoOptions): string[] {\n const dirs = [false, true].map((auth) =>\n demoDir({ ...options, features: { ...options.features, auth } }),\n );\n return [...new Set(dirs)];\n}\n\n/** A path enable-ai writes, with the stored demo directory moved to `dir`. */\nfunction atDemoDir(path: string, dir: string): string {\n return path.startsWith(DEMO_DIR)\n ? `${dir}/${path.slice(DEMO_DIR.length)}`\n : path;\n}\n\n/**\n * Every path enable-ai writes for this project: the model module, the\n * endpoint and its test, and the demo page in its current default group.\n * `generate.runtime.ts` adds the page in the other group when it exists.\n */\nexport function aiPaths(options: DemoOptions): string[] {\n const dir = demoDir(options);\n const paths = new Set<string>(allProviderPaths(providersRaw));\n for (const [raw, prefix] of [\n [createsRaw, \"../../enable/ai/creates/\"],\n [createsAppModeRaw, \"../../enable/ai/creates-app-mode/\"],\n ] as const) {\n for (const key of Object.keys(raw)) {\n paths.add(atDemoDir(appRelativePath(key, prefix), dir));\n }\n }\n return [...paths].sort();\n}\n\n/**\n * The `.env` lines every provider writes. Which provider was chosen is not\n * recorded, so all are removed; keys that are not there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\n/** Every provider's env var names, as `src/env.ts` declares them. */\nexport function allEnvNames(): string[] {\n return PROVIDERS.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n );\n}\n\nexport async function generate(options: Options) {\n return {\n creates: [],\n modifies: [],\n // Missing ones are skipped, and emptied directories (api/chat, ai) go too.\n deletes: aiPaths(options).map(toDeleteEntry),\n components: [],\n packages: [],\n // zod and the shadcn button/textarea stay: other code uses them.\n uninstalls: [...PACKAGES, ...Object.values(PROVIDER_PACKAGES).flat()],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;AAcA,IAAMyB,IAAa,uBAAA,OAAA;CAAA,+DAAAzB;CAAA,0DAAAC;CAAA,8DAAAC;AAIlB,CAAA,GAEKwB,IAAoB,uBAAA,OAAA;CAAA,mEAAAvB;CAAA,uEAAAC;AAG1B,CAAA,GAEMuB,IAAe,uBAAA,OAAA;CAAA,4DAAAtB;CAAA,0DAAAC;CAAA,yDAAAC;AAIpB,CAAA;AASD,SAAgBqB,EAAS,GAAgC;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ACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as e, c as t, n, o as r, r as i, s as a } from "./generate-BDGmczK8.js";
|
|
2
2
|
import { t as o } from "./providers-DrK_hjSr.js";
|
|
3
|
-
import { n as s } from "./shared-
|
|
3
|
+
import { n as s } from "./shared-D7-ZAoqr.js";
|
|
4
4
|
// src/patterns/disable/analytics/generate.ts
|
|
5
5
|
var c = /* #__PURE__ */ Object.assign({
|
|
6
6
|
"../../enable/analytics/providers/google/src/lib/components/analytics/analytics.svelte": t,
|
|
@@ -29,4 +29,4 @@ async function d(e) {
|
|
|
29
29
|
}
|
|
30
30
|
export { u as n, d as r, l as t };
|
|
31
31
|
|
|
32
|
-
//# sourceMappingURL=generate-
|
|
32
|
+
//# sourceMappingURL=generate-BSCDKlyL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-
|
|
1
|
+
{"version":3,"file":"generate-BSCDKlyL.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","analytics_default$2","analytics_default","analytics_default$1","envEditsFor","gtag_default","allProviderPaths","toDeleteEntry","providersRaw","allEnvEdits","PROVIDERS","provider","allEnvNames","variable","generate"],"sources":["../../src/patterns/disable/analytics/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { envEditsFor, PROVIDERS } from \"../../enable/analytics/generate\";\n\nconst providersRaw = import.meta.glob<string>(\n \"../../enable/analytics/providers/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\n/**\n * The `.env` lines every provider writes. The project only has one set, but\n * which one is not recorded anywhere, so all are removed; keys that are not\n * there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\n/** Every provider's env var names, as `src/env.ts` declares them. */\nexport function allEnvNames(): string[] {\n return PROVIDERS.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n );\n}\n\nexport async function generate(_options: Options) {\n return {\n creates: [],\n modifies: [],\n // Every provider's files: missing ones are skipped, and the emptied\n // components/analytics directory goes with them.\n deletes: allProviderPaths(providersRaw).map(toDeleteEntry),\n components: [],\n packages: [],\n // PostHog's SDK; the other providers load a script and install nothing.\n uninstalls: [\"posthog-js\"],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;AAMA,IAAMW,IAAe,uBAAA,OAAA;CAAA,yFAAAX;CAAA,gFAAAC;CAAA,4FAAAC;CAAA,0FAAAC;AAGrB,CAAA;AAOA,SAAgBS,IAAyB;CACvC,OAAOC,EAAU,SAAS,MAAaN,EAAYO,CAAQ,CAAC;AAC9D;AAGA,SAAgBC,IAAwB;CACtC,OAAOF,EAAU,SAAS,OACvBC,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,MAAaE,EAAS,GAAG,CACrD;AACF;AAEA,eAAsBC,EAAS,GAAmB;CAChD,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EAGX,SAASR,EAAiBE,CAAY,CAAC,CAAC,IAAID,CAAa;EACzD,YAAY,CAAC;EACb,UAAU,CAAC;EAEX,YAAY,CAAC,YAAY;EACzB,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { n as e } from "./logger-t1HxmpG2.js";
|
|
2
|
-
import {
|
|
2
|
+
import { o as t } from "./collections-CFTIAty-.js";
|
|
3
3
|
import { i as n, n as r, t as i } from "./pocketbase-B2ksFrvH.js";
|
|
4
|
-
import { r as a } from "./modify-file-
|
|
4
|
+
import { r as a } from "./modify-file-DRdmZIvW.js";
|
|
5
5
|
import { n as o } from "./site-B5zrFba9.js";
|
|
6
6
|
import { t as s } from "./dedent-CCUOcPFW.js";
|
|
7
7
|
import { _ as c, a as l, o as u, r as d } from "./ts-morph-helpers-B4KZXP44.js";
|
|
8
8
|
import { t as f } from "./svelte-file-DfplF3BU.js";
|
|
9
|
-
import { localizeAuthPages as p } from "./i18n-
|
|
9
|
+
import { localizeAuthPages as p } from "./i18n-BoYcqVBi.js";
|
|
10
10
|
import m from "node:fs";
|
|
11
11
|
import h from "node:path";
|
|
12
12
|
import { Project as g, SyntaxKind as _ } from "ts-morph";
|
|
@@ -277,7 +277,7 @@ async function A(s) {
|
|
|
277
277
|
} }), await r();
|
|
278
278
|
let n = await e.collections.getOne("users");
|
|
279
279
|
if (!n) throw Error("Users collection not found");
|
|
280
|
-
let a = n.verificationTemplate.body.replace("{APP_URL}/_/#/auth/confirm-verification/{TOKEN}", "{APP_URL}/confirm-verification/{TOKEN}"), o = n.resetPasswordTemplate.body.replace(
|
|
280
|
+
let a = n.verificationTemplate.body.replace("{APP_URL}/_/#/auth/confirm-verification/{TOKEN}", "{APP_URL}/confirm-verification/{TOKEN}"), o = n.resetPasswordTemplate.body.replace(/\{APP_URL\}\/_\/#\/auth\/confirm-(?:password-)?reset\/\{TOKEN\}/, "{APP_URL}/confirm-reset/{TOKEN}"), d = n.confirmEmailChangeTemplate.body.replace("{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}", "{APP_URL}/confirm-email-change/{TOKEN}");
|
|
281
281
|
l.info("Locking down users collection rules and email templates"), await e.collections.update("users", {
|
|
282
282
|
listRule: "@request.auth.id = id",
|
|
283
283
|
viewRule: "@request.auth.id = id",
|
|
@@ -322,4 +322,4 @@ async function A(s) {
|
|
|
322
322
|
}
|
|
323
323
|
export { A as generate };
|
|
324
324
|
|
|
325
|
-
//# sourceMappingURL=generate.runtime-
|
|
325
|
+
//# sourceMappingURL=generate.runtime-2T2j6Cgc.js.map
|