@velastack/patterns 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/dist/chunks/{_layout-kkgN0IF7.js → _layout-D-FzWqn0.js} +2 -2
  2. package/dist/chunks/{_layout-kkgN0IF7.js.map → _layout-D-FzWqn0.js.map} +1 -1
  3. package/dist/chunks/_page-C7kGoW7_.js +6 -0
  4. package/dist/chunks/_page-C7kGoW7_.js.map +1 -0
  5. package/dist/chunks/_page-e_I-fdSR.js +6 -0
  6. package/dist/chunks/_page-e_I-fdSR.js.map +1 -0
  7. package/dist/chunks/auth-pages-B52ei-4z.js +291 -0
  8. package/dist/chunks/auth-pages-B52ei-4z.js.map +1 -0
  9. package/dist/chunks/{collections-Dz2fvKnz.js → collections-zzZ_HQxB.js} +2 -2
  10. package/dist/chunks/{collections-Dz2fvKnz.js.map → collections-zzZ_HQxB.js.map} +1 -1
  11. package/dist/chunks/{compose-handle-D_Rz3Fzo.js → compose-handle-BDlZ7Pif.js} +2 -2
  12. package/dist/chunks/{compose-handle-D_Rz3Fzo.js.map → compose-handle-BDlZ7Pif.js.map} +1 -1
  13. package/dist/chunks/{config-target-Dx3w6WSk.js → config-target-rHgjaA8u.js} +2 -2
  14. package/dist/chunks/{config-target-Dx3w6WSk.js.map → config-target-rHgjaA8u.js.map} +1 -1
  15. package/dist/chunks/{constants-BjyMU5s8.js → constants-Rq8SCXwH.js} +2 -2
  16. package/dist/chunks/{constants-BjyMU5s8.js.map → constants-Rq8SCXwH.js.map} +1 -1
  17. package/dist/chunks/dispatch-D4TN9pdW.js +6 -0
  18. package/dist/chunks/dispatch-D4TN9pdW.js.map +1 -0
  19. package/dist/chunks/{env-vars-C1NUX-bf.js → env-vars-CcE6ODqC.js} +4 -4
  20. package/dist/chunks/{env-vars-C1NUX-bf.js.map → env-vars-CcE6ODqC.js.map} +1 -1
  21. package/dist/chunks/{format-result-DZ8De8KY.js → format-result-BVoLVknk.js} +2 -2
  22. package/dist/chunks/format-result-BVoLVknk.js.map +1 -0
  23. package/dist/chunks/{generate-DeaBlnK6.js → generate-B6Odfk5f.js} +2 -2
  24. package/dist/chunks/{generate-DeaBlnK6.js.map → generate-B6Odfk5f.js.map} +1 -1
  25. package/dist/chunks/{generate-WMJo3QGZ.js → generate-Bg0E3eWm.js} +2 -2
  26. package/dist/chunks/{generate-WMJo3QGZ.js.map → generate-Bg0E3eWm.js.map} +1 -1
  27. package/dist/chunks/{generate-Gcc8iRkZ.js → generate-CFqpRi9D.js} +3 -3
  28. package/dist/chunks/{generate-Gcc8iRkZ.js.map → generate-CFqpRi9D.js.map} +1 -1
  29. package/dist/chunks/{generate-BW3l5Fxw.js → generate-CZGHByV3.js} +2 -2
  30. package/dist/chunks/{generate-BW3l5Fxw.js.map → generate-CZGHByV3.js.map} +1 -1
  31. package/dist/chunks/{generate.runtime-IlBCcXvv.js → generate.runtime-5rIc-RNL.js} +7 -7
  32. package/dist/chunks/{generate.runtime-IlBCcXvv.js.map → generate.runtime-5rIc-RNL.js.map} +1 -1
  33. package/dist/chunks/{generate.runtime-BgTz41Zg.js → generate.runtime-BK3mR0Rj.js} +92 -140
  34. package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +1 -0
  35. package/dist/chunks/{generate.runtime-cwvAoKoH.js → generate.runtime-BpMN5Uq-.js} +3 -3
  36. package/dist/chunks/{generate.runtime-cwvAoKoH.js.map → generate.runtime-BpMN5Uq-.js.map} +1 -1
  37. package/dist/chunks/{generate.runtime-DD51OSuL.js → generate.runtime-CAn1qIQ_.js} +4 -4
  38. package/dist/chunks/{generate.runtime-DD51OSuL.js.map → generate.runtime-CAn1qIQ_.js.map} +1 -1
  39. package/dist/chunks/{generate.runtime-CuNhY5hn.js → generate.runtime-CEqLgLT9.js} +16 -11
  40. package/dist/chunks/generate.runtime-CEqLgLT9.js.map +1 -0
  41. package/dist/chunks/{generate.runtime-B1jVAnDI.js → generate.runtime-CK10Mum5.js} +8 -8
  42. package/dist/chunks/{generate.runtime-B1jVAnDI.js.map → generate.runtime-CK10Mum5.js.map} +1 -1
  43. package/dist/chunks/{generate.runtime-DqD3PW-W.js → generate.runtime-CZ46nkSL.js} +3 -3
  44. package/dist/chunks/{generate.runtime-DqD3PW-W.js.map → generate.runtime-CZ46nkSL.js.map} +1 -1
  45. package/dist/chunks/{generate.runtime-CslAvllQ.js → generate.runtime-CbE9RHcf.js} +5 -5
  46. package/dist/chunks/generate.runtime-CbE9RHcf.js.map +1 -0
  47. package/dist/chunks/{generate.runtime-CCr1lvo4.js → generate.runtime-CpMKXBkn.js} +7 -7
  48. package/dist/chunks/{generate.runtime-CCr1lvo4.js.map → generate.runtime-CpMKXBkn.js.map} +1 -1
  49. package/dist/chunks/{generate.runtime-6FXJM8hT.js → generate.runtime-CqncBFNg.js} +5 -5
  50. package/dist/chunks/{generate.runtime-6FXJM8hT.js.map → generate.runtime-CqncBFNg.js.map} +1 -1
  51. package/dist/chunks/generate.runtime-DG2z6kqH.js +68 -0
  52. package/dist/chunks/generate.runtime-DG2z6kqH.js.map +1 -0
  53. package/dist/chunks/{generate.runtime-C6bSvGMb.js → generate.runtime-DHHlYfTD.js} +6 -6
  54. package/dist/chunks/{generate.runtime-C6bSvGMb.js.map → generate.runtime-DHHlYfTD.js.map} +1 -1
  55. package/dist/chunks/generate.runtime-DJ9MVVPC.js +325 -0
  56. package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +1 -0
  57. package/dist/chunks/{generate.runtime-CnPraLKv.js → generate.runtime-DVB7uuht.js} +4 -4
  58. package/dist/chunks/{generate.runtime-CnPraLKv.js.map → generate.runtime-DVB7uuht.js.map} +1 -1
  59. package/dist/chunks/{generate.runtime-kvxmTlQb.js → generate.runtime-Db0HZyj3.js} +3 -3
  60. package/dist/chunks/{generate.runtime-kvxmTlQb.js.map → generate.runtime-Db0HZyj3.js.map} +1 -1
  61. package/dist/chunks/{generate.runtime-D_sQOeQa.js → generate.runtime-Djas9UNy.js} +6 -6
  62. package/dist/chunks/{generate.runtime-D_sQOeQa.js.map → generate.runtime-Djas9UNy.js.map} +1 -1
  63. package/dist/chunks/{generate.runtime-Ce_rwzNa.js → generate.runtime-Dl6OQ7pe.js} +4 -4
  64. package/dist/chunks/{generate.runtime-Ce_rwzNa.js.map → generate.runtime-Dl6OQ7pe.js.map} +1 -1
  65. package/dist/chunks/{generate.runtime-1-91UmM8.js → generate.runtime-DoZJHtZh.js} +4 -4
  66. package/dist/chunks/{generate.runtime-1-91UmM8.js.map → generate.runtime-DoZJHtZh.js.map} +1 -1
  67. package/dist/chunks/generate.runtime-Dp7SsCQG.js +42 -0
  68. package/dist/chunks/generate.runtime-Dp7SsCQG.js.map +1 -0
  69. package/dist/chunks/{generate.runtime-C8zJRNYG.js → generate.runtime-E-zoeSKW.js} +5 -5
  70. package/dist/chunks/{generate.runtime-C8zJRNYG.js.map → generate.runtime-E-zoeSKW.js.map} +1 -1
  71. package/dist/chunks/{generate.runtime-pVLzzpUM.js → generate.runtime-EQnytCFL.js} +40 -40
  72. package/dist/chunks/generate.runtime-EQnytCFL.js.map +1 -0
  73. package/dist/chunks/generate.runtime-IWEhGhWY.js +218 -0
  74. package/dist/chunks/generate.runtime-IWEhGhWY.js.map +1 -0
  75. package/dist/chunks/{generate.runtime-CYagyR5c.js → generate.runtime-a3R4hqFy.js} +6 -6
  76. package/dist/chunks/{generate.runtime-CYagyR5c.js.map → generate.runtime-a3R4hqFy.js.map} +1 -1
  77. package/dist/chunks/{generate.runtime-zJpEufTc.js → generate.runtime-aQnBmH8D.js} +9 -9
  78. package/dist/chunks/generate.runtime-aQnBmH8D.js.map +1 -0
  79. package/dist/chunks/{generate.runtime-Dtgw9IQO.js → generate.runtime-axm9wcQv.js} +5 -5
  80. package/dist/chunks/{generate.runtime-Dtgw9IQO.js.map → generate.runtime-axm9wcQv.js.map} +1 -1
  81. package/dist/chunks/{generate.runtime-DHBRyMAq.js → generate.runtime-hTKzxH2M.js} +5 -5
  82. package/dist/chunks/{generate.runtime-DHBRyMAq.js.map → generate.runtime-hTKzxH2M.js.map} +1 -1
  83. package/dist/chunks/{generate.runtime-BA3tDKnn.js → generate.runtime-kciwaXxh.js} +5 -5
  84. package/dist/chunks/{generate.runtime-BA3tDKnn.js.map → generate.runtime-kciwaXxh.js.map} +1 -1
  85. package/dist/chunks/{generate.runtime-B_UVGa3q.js → generate.runtime-koQxLywh.js} +5 -5
  86. package/dist/chunks/{generate.runtime-B_UVGa3q.js.map → generate.runtime-koQxLywh.js.map} +1 -1
  87. package/dist/chunks/{generate.runtime-DM4o_QYY.js → generate.runtime-rs1ZOIET.js} +5 -5
  88. package/dist/chunks/{generate.runtime-DM4o_QYY.js.map → generate.runtime-rs1ZOIET.js.map} +1 -1
  89. package/dist/chunks/{generate.runtime-DV3WmZtb.js → generate.runtime-uLUiPgqx.js} +6 -6
  90. package/dist/chunks/{generate.runtime-DV3WmZtb.js.map → generate.runtime-uLUiPgqx.js.map} +1 -1
  91. package/dist/chunks/{modify-file-BlDeeurK.js → modify-file-DK-tCH9k.js} +3 -3
  92. package/dist/chunks/{modify-file-BlDeeurK.js.map → modify-file-DK-tCH9k.js.map} +1 -1
  93. package/dist/chunks/modify-nav-user-BLyrW2sK.js +71 -0
  94. package/dist/chunks/modify-nav-user-BLyrW2sK.js.map +1 -0
  95. package/dist/chunks/{modify-svelte-config-remote-p0TfVzxm.js → modify-svelte-config-remote-DhuRX4FI.js} +2 -2
  96. package/dist/chunks/{modify-svelte-config-remote-p0TfVzxm.js.map → modify-svelte-config-remote-DhuRX4FI.js.map} +1 -1
  97. package/dist/chunks/modify-user-signup-BbqTiUuA.js +54 -0
  98. package/dist/chunks/modify-user-signup-BbqTiUuA.js.map +1 -0
  99. package/dist/chunks/{pocketbase-Dry6ry17.js → pocketbase-CgwbH1gI.js} +2 -2
  100. package/dist/chunks/{pocketbase-Dry6ry17.js.map → pocketbase-CgwbH1gI.js.map} +1 -1
  101. package/dist/chunks/{shared-CZC4d7Uj.js → shared-Cc_ns5-y.js} +2 -2
  102. package/dist/chunks/{shared-CZC4d7Uj.js.map → shared-Cc_ns5-y.js.map} +1 -1
  103. package/dist/chunks/{site-BwCA18Sv.js → site-lj0CDdQ1.js} +2 -2
  104. package/dist/chunks/{site-BwCA18Sv.js.map → site-lj0CDdQ1.js.map} +1 -1
  105. package/dist/chunks/{table-core-AjBpYi-y.js → table-core-DhDqT03G.js} +2 -2
  106. package/dist/chunks/{table-core-AjBpYi-y.js.map → table-core-DhDqT03G.js.map} +1 -1
  107. package/dist/chunks/{test-setup-DEmWd9Ul.js → test-setup-B9fQ5L_-.js} +5 -5
  108. package/dist/chunks/{test-setup-DEmWd9Ul.js.map → test-setup-B9fQ5L_-.js.map} +1 -1
  109. package/dist/chunks/{ts-morph-helpers-CDW4lhox.js → ts-morph-helpers-Bepc-Es2.js} +27 -23
  110. package/dist/chunks/ts-morph-helpers-Bepc-Es2.js.map +1 -0
  111. package/dist/chunks/{ui-X698F10c.js → ui-CuCsupFq.js} +3 -3
  112. package/dist/chunks/{ui-X698F10c.js.map → ui-CuCsupFq.js.map} +1 -1
  113. package/dist/chunks/{unmodify-load-CyGzC1Hu.js → unmodify-load-Bl5vXQiL.js} +2 -2
  114. package/dist/chunks/{unmodify-load-CyGzC1Hu.js.map → unmodify-load-Bl5vXQiL.js.map} +1 -1
  115. package/dist/chunks/whatsapp-CguKGTtw.js +105 -0
  116. package/dist/chunks/whatsapp-CguKGTtw.js.map +1 -0
  117. package/dist/chunks/{write-result-B68lvI57.js → write-result-DiZsCS_y.js} +5 -5
  118. package/dist/chunks/{write-result-B68lvI57.js.map → write-result-DiZsCS_y.js.map} +1 -1
  119. package/dist/index.d.ts +133 -1
  120. package/dist/index.js +2240 -2005
  121. package/dist/index.js.map +1 -1
  122. package/package.json +2 -2
  123. package/dist/chunks/dispatch-CXOXPLFk.js +0 -6
  124. package/dist/chunks/dispatch-CXOXPLFk.js.map +0 -1
  125. package/dist/chunks/format-result-DZ8De8KY.js.map +0 -1
  126. package/dist/chunks/generate.runtime-BO778G0r.js +0 -188
  127. package/dist/chunks/generate.runtime-BO778G0r.js.map +0 -1
  128. package/dist/chunks/generate.runtime-BgTz41Zg.js.map +0 -1
  129. package/dist/chunks/generate.runtime-CexC1Oky.js +0 -269
  130. package/dist/chunks/generate.runtime-CexC1Oky.js.map +0 -1
  131. package/dist/chunks/generate.runtime-CslAvllQ.js.map +0 -1
  132. package/dist/chunks/generate.runtime-CuNhY5hn.js.map +0 -1
  133. package/dist/chunks/generate.runtime-pVLzzpUM.js.map +0 -1
  134. package/dist/chunks/generate.runtime-zJpEufTc.js.map +0 -1
  135. package/dist/chunks/nav-user-BRIHOOpG.js +0 -6
  136. package/dist/chunks/nav-user-BRIHOOpG.js.map +0 -1
  137. package/dist/chunks/ts-morph-helpers-CDW4lhox.js.map +0 -1
@@ -1,269 +0,0 @@
1
- import { t as e } from "./dedent-Gq6Krl4n.js";
2
- import { n as t } from "./logger-CQONztPm.js";
3
- import { a as n, i as r, n as i, o as a, r as o, s, t as c } from "./dispatch-CXOXPLFk.js";
4
- import { _ as l, o as u, r as d } from "./ts-morph-helpers-CDW4lhox.js";
5
- import { modifyOutcomeToFile as f } from "./modify-file-BlDeeurK.js";
6
- import { t as p } from "./svelte-file-B3RfgVdt.js";
7
- import m from "node:fs";
8
- import h from "node:path";
9
- import { SyntaxKind as g } from "ts-morph";
10
- //#region src/patterns/enable/subscriptions/modifies/modify-webhook-server.ts
11
- var _ = e`
12
- Wire the subscription event handlers into src/routes/webhooks/stripe/handlers/dispatch.ts:
13
-
14
- Add imports:
15
- import { handleSubscriptionCreated } from "./subscription/created";
16
- import { handleSubscriptionUpdated } from "./subscription/updated";
17
- import { handleSubscriptionDeleted } from "./subscription/deleted";
18
-
19
- Add switch cases inside the event.type switch:
20
- case "customer.subscription.created":
21
- await handleSubscriptionCreated(event.data.object, locals);
22
- break;
23
- case "customer.subscription.updated":
24
- await handleSubscriptionUpdated(event.data.object, locals);
25
- break;
26
- case "customer.subscription.deleted":
27
- await handleSubscriptionDeleted(event.data.object, locals);
28
- break;
29
- `, v = "Enable payments first — src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.", y = e`
30
- case "customer.subscription.created":
31
- await handleSubscriptionCreated(event.data.object, locals);
32
- break;
33
-
34
- case "customer.subscription.updated":
35
- await handleSubscriptionUpdated(event.data.object, locals);
36
- break;
37
-
38
- case "customer.subscription.deleted":
39
- await handleSubscriptionDeleted(event.data.object, locals);
40
- break;
41
- `;
42
- function b(e) {
43
- if (!m.existsSync(e)) return {
44
- status: "not-found",
45
- message: v
46
- };
47
- let t = m.readFileSync(e, "utf8");
48
- if (t.includes("handleSubscriptionCreated")) return {
49
- status: "success",
50
- changed: !1
51
- };
52
- let n = !1, { source: r } = l(t, (e) => {
53
- d(e, [
54
- {
55
- namedImports: ["handleSubscriptionCreated"],
56
- moduleSpecifier: "./subscription/created"
57
- },
58
- {
59
- namedImports: ["handleSubscriptionUpdated"],
60
- moduleSpecifier: "./subscription/updated"
61
- },
62
- {
63
- namedImports: ["handleSubscriptionDeleted"],
64
- moduleSpecifier: "./subscription/deleted"
65
- }
66
- ]);
67
- let t = e.getDescendantsOfKind(g.SwitchStatement).find((e) => e.getExpression().getText().includes("event.type"));
68
- if (!t) return;
69
- let r = t.getCaseBlock().getClauses(), i = r.find((e) => e.getKind() === g.DefaultClause), a = `${y}\n\n`;
70
- if (i) i.replaceWithText(a + i.getText());
71
- else if (r.length > 0) {
72
- let e = r[r.length - 1];
73
- e.replaceWithText(e.getText() + `\n\n${y}`);
74
- } else return;
75
- u(e), n = !0;
76
- });
77
- return n ? (m.writeFileSync(e, r, "utf8"), {
78
- status: "success",
79
- changed: !0
80
- }) : {
81
- status: "failed",
82
- message: _
83
- };
84
- }
85
- //#endregion
86
- //#region src/patterns/enable/subscriptions/modifies/modify-by-template.ts
87
- function x(e, t, n, r) {
88
- if (!m.existsSync(e)) return {
89
- status: "not-found",
90
- message: r
91
- };
92
- let i = m.readFileSync(e, "utf8");
93
- if (i.includes(n)) return {
94
- status: "success",
95
- changed: !1
96
- };
97
- let a = t.replace(/^[ \t]*\/\/[ \t]*\[!code highlight:\d+\][ \t]*\r?\n/gm, "").replace(/^[ \t]*<!--[ \t]*\[!code highlight:\d+\][ \t]*-->[ \t]*\r?\n/gm, "");
98
- return i === a ? {
99
- status: "success",
100
- changed: !1
101
- } : (m.writeFileSync(e, a, "utf8"), {
102
- status: "success",
103
- changed: !0
104
- });
105
- }
106
- //#endregion
107
- //#region src/patterns/enable/subscriptions/modifies/modify-app-layout-server.ts
108
- var S = ["Create src/routes/(app)/+layout.server.ts before enabling subscriptions.", "Enable auth first — the (app) layout is provided by the velastack-auth baseline."].join("\n");
109
- function C(e, t) {
110
- return x(e, t, "loadActiveSubscription", S);
111
- }
112
- //#endregion
113
- //#region src/patterns/enable/subscriptions/modifies/modify-app-layout-svelte.ts
114
- var w = [
115
- "Pass the subscription prop to <AppSidebar> in src/routes/(app)/+layout.svelte:",
116
- "",
117
- "<AppSidebar user={data.user} subscription={data.subscription} />"
118
- ].join("\n"), T = ["Create src/routes/(app)/+layout.svelte with an <AppSidebar /> that receives the subscription prop."].join("\n");
119
- function E(e) {
120
- if (!m.existsSync(e)) return {
121
- status: "not-found",
122
- message: T
123
- };
124
- let t = p.fromPath(e);
125
- return t.hasElement("AppSidebar") ? t.hasAttribute("AppSidebar", "subscription") ? {
126
- status: "success",
127
- changed: !1
128
- } : t.appendToAttributes("AppSidebar", " subscription={data.subscription}") ? (t.writeTo(e), {
129
- status: "success",
130
- changed: t.hasChanged()
131
- }) : {
132
- status: "failed",
133
- message: w
134
- } : {
135
- status: "failed",
136
- message: w
137
- };
138
- }
139
- //#endregion
140
- //#region src/patterns/enable/subscriptions/modifies/modify-app-sidebar.ts
141
- var D = "{ id: string; productName: string | null } | null", O = [
142
- "Update src/lib/components/app-sidebar.svelte to forward a subscription prop:",
143
- "",
144
- "1. Add `subscription = null` to the destructured $props() call.",
145
- `2. Add \`subscription?: ${D}\` to the props type.`,
146
- "3. Pass `{subscription}` to <NavUser>."
147
- ].join("\n"), k = ["Create src/lib/components/app-sidebar.svelte before enabling subscriptions."].join("\n");
148
- function A(e) {
149
- let t = !1, { source: n } = l(e, (e) => {
150
- for (let n of e.getVariableDeclarations()) {
151
- let e = n.getInitializer();
152
- if (!e || e.getText() !== "$props()") continue;
153
- let r = n.getNameNode();
154
- if (r.getKind() !== g.ObjectBindingPattern) continue;
155
- let i = r.asKindOrThrow(g.ObjectBindingPattern), a = i.getElements();
156
- if (a.some((e) => e.getName() === "subscription")) return;
157
- let o = n.getTypeNode();
158
- if (o?.getKind() === g.IntersectionType) {
159
- let e = o.asKindOrThrow(g.IntersectionType);
160
- for (let t of e.getTypeNodes()) {
161
- if (t.getKind() !== g.TypeLiteral) continue;
162
- let e = t.asKindOrThrow(g.TypeLiteral), n = e.getProperties().map((e) => e.getText().replace(/[;,]\s*$/, ""));
163
- if (!n.some((e) => /^\s*subscription\??\s*:/.test(e))) {
164
- n.push(`subscription?: ${D}`), e.replaceWithText(`{ ${n.join("; ")}; }`);
165
- break;
166
- }
167
- }
168
- }
169
- let s = a.map((e) => e.getText()), c = a.findIndex((e) => e.getDotDotDotToken() || e.getInitializer());
170
- c === -1 && (c = s.length), s.splice(c, 0, "subscription = null"), i.replaceWithText(`{ ${s.join(", ")} }`), t = !0;
171
- }
172
- u(e);
173
- });
174
- return {
175
- source: n,
176
- wasAdded: t
177
- };
178
- }
179
- function j(e) {
180
- if (!m.existsSync(e)) return {
181
- status: "not-found",
182
- message: k
183
- };
184
- let t = m.readFileSync(e, "utf8");
185
- if (t.includes("subscription?: {") || t.includes("subscription={subscription}") || t.includes("{subscription}")) return {
186
- status: "success",
187
- changed: !1
188
- };
189
- let n = new p(t);
190
- if (!n.hasElement("NavUser")) return {
191
- status: "failed",
192
- message: O
193
- };
194
- let r = n.modifyScript((e) => A(e).source), i = !n.hasAttribute("NavUser", "subscription") && n.appendToAttributes("NavUser", " {subscription}");
195
- return !r && !i ? {
196
- status: "failed",
197
- message: O
198
- } : (n.writeTo(e), {
199
- status: "success",
200
- changed: n.hasChanged()
201
- });
202
- }
203
- //#endregion
204
- //#region src/patterns/enable/subscriptions/modifies/modify-nav-user.ts
205
- var M = ["src/lib/components/nav-user.svelte is missing.", "Enable auth and payments first; subscriptions layers a plan label on top of the existing nav-user."].join("\n");
206
- function N(e, t) {
207
- return x(e, t, "planLabel", M);
208
- }
209
- //#endregion
210
- //#region src/patterns/enable/subscriptions/modifies/modify-billing-page-server.ts
211
- var P = ["src/routes/(app)/billing/+page.server.ts is missing.", "Enable payments first — subscriptions extends the billing page with plan management."].join("\n");
212
- function F(e, t) {
213
- return x(e, t, "selectPlan", P);
214
- }
215
- //#endregion
216
- //#region src/patterns/enable/subscriptions/modifies/modify-billing-page-svelte.ts
217
- var I = ["src/routes/(app)/billing/+page.svelte is missing.", "Enable payments first — subscriptions extends the billing page with plan management."].join("\n");
218
- function L(e, t) {
219
- return x(e, t, "availablePlans", I);
220
- }
221
- //#endregion
222
- //#region src/patterns/enable/subscriptions/generate.runtime.ts
223
- var R = /* #__PURE__ */ Object.assign({
224
- "./preview-modifies/src/lib/components/app-sidebar.svelte": s,
225
- "./preview-modifies/src/lib/components/nav-user.svelte": a,
226
- "./preview-modifies/src/routes/(app)/+layout.server.ts": n,
227
- "./preview-modifies/src/routes/(app)/+layout.svelte": r,
228
- "./preview-modifies/src/routes/(app)/billing/+page.server.ts": o,
229
- "./preview-modifies/src/routes/(app)/billing/+page.svelte": i,
230
- "./preview-modifies/src/routes/webhooks/stripe/handlers/dispatch.ts": c
231
- });
232
- function z(e) {
233
- let t = R[`./preview-modifies/${e}`];
234
- if (t === void 0) throw Error(`Missing template for ${e} in subscriptions preview-modifies`);
235
- return t;
236
- }
237
- async function B(e) {
238
- let n = t(e), r = [], i = (e) => {
239
- e && r.push(e);
240
- };
241
- n.info("Modifying webhooks/stripe/handlers/dispatch.ts");
242
- let a = h.join(e.root, "src", "routes", "webhooks", "stripe", "handlers", "dispatch.ts");
243
- i(f(a, b(a))), n.info("Modifying (app)/+layout.server.ts");
244
- let o = h.join(e.root, "src", "routes", "(app)", "+layout.server.ts");
245
- i(f(o, C(o, z("src/routes/(app)/+layout.server.ts")))), n.info("Modifying (app)/+layout.svelte");
246
- let s = h.join(e.root, "src", "routes", "(app)", "+layout.svelte");
247
- i(f(s, E(s))), n.info("Modifying app-sidebar.svelte");
248
- let c = h.join(e.root, "src", "lib", "components", "app-sidebar.svelte");
249
- i(f(c, j(c))), n.info("Modifying nav-user.svelte");
250
- let l = h.join(e.root, "src", "lib", "components", "nav-user.svelte");
251
- i(f(l, N(l, z("src/lib/components/nav-user.svelte")))), n.info("Modifying billing/+page.server.ts");
252
- let u = h.join(e.root, "src", "routes", "(app)", "billing", "+page.server.ts");
253
- i(f(u, F(u, z("src/routes/(app)/billing/+page.server.ts")))), n.info("Modifying billing/+page.svelte");
254
- let d = h.join(e.root, "src", "routes", "(app)", "billing", "+page.svelte");
255
- return i(f(d, L(d, z("src/routes/(app)/billing/+page.svelte")))), {
256
- creates: [],
257
- modifies: r,
258
- deletes: [],
259
- components: [],
260
- packages: [],
261
- collections: [],
262
- collectionPatches: [],
263
- collectionDrops: []
264
- };
265
- }
266
- //#endregion
267
- export { B as generate };
268
-
269
- //# sourceMappingURL=generate.runtime-CexC1Oky.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-CexC1Oky.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","__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_","dedent","getLogger","_layout_server_default","_layout_default","_page_default","nav_user_default","_page_server_default","dispatch_default","withInMemoryScript","formatLikeSource","ensureImports","SvelteFile","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$6","SUBSCRIPTION_CASES_SNIPPET","modifyWebhookServer","filePath","original","addedCases","sf","switchStmt","SyntaxKind","stmt","clauses","defaultClause","c","prefix","last","source","modifyByTemplate","notFoundHint","current","idempotencyMarker","stripped","template","NOT_FOUND_HINT$5","modifyAppLayoutServer","FAILURE_HINT$1","NOT_FOUND_HINT$4","modifyAppLayoutSvelte","file","SUBSCRIPTION_TYPE","FAILURE_HINT","NOT_FOUND_HINT$3","updateScript","wasAdded","out","decl","init","nameNode","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","scriptChanged","src","templateChanged","NOT_FOUND_HINT$2","modifyNavUser","NOT_FOUND_HINT$1","modifyBillingPageServer","NOT_FOUND_HINT","modifyBillingPageSvelte","previewRaw","app_sidebar_default","content","relativePath","generate","logger","options","modifies","pushResult","webhookServerPath","modifyOutcomeToFile","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-by-template.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/enable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/enable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Wire the subscription event handlers into src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n Add imports:\n import { handleSubscriptionCreated } from \"./subscription/created\";\n import { handleSubscriptionUpdated } from \"./subscription/updated\";\n import { handleSubscriptionDeleted } from \"./subscription/deleted\";\n\n Add switch cases inside the event.type switch:\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first — src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\nconst SUBSCRIPTION_CASES_SNIPPET = dedent`\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n let addedCases = false;\n const { source } = withInMemoryScript(original, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"handleSubscriptionCreated\"],\n moduleSpecifier: \"./subscription/created\",\n },\n {\n namedImports: [\"handleSubscriptionUpdated\"],\n moduleSpecifier: \"./subscription/updated\",\n },\n {\n namedImports: [\"handleSubscriptionDeleted\"],\n moduleSpecifier: \"./subscription/deleted\",\n },\n ]);\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n const clauses = caseBlock.getClauses();\n const defaultClause = clauses.find(\n (c) => c.getKind() === SyntaxKind.DefaultClause,\n );\n\n // Prepend subscription cases in front of the default clause, or append\n // before the closing brace of the case block if there's no default.\n const prefix = `${SUBSCRIPTION_CASES_SNIPPET}\\n\\n`;\n if (defaultClause) {\n defaultClause.replaceWithText(prefix + defaultClause.getText());\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(\n last.getText() + `\\n\\n${SUBSCRIPTION_CASES_SNIPPET}`,\n );\n } else {\n return;\n }\n\n formatLikeSource(sf);\n addedCases = true;\n });\n\n if (!addedCases) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Overwrites a file with the given template content, guarded by an idempotency\n * marker: if the current file already contains the marker, the modify is a\n * no-op. Used for complex rewrites where surgical AST changes aren't worth it\n * (e.g. pages that are largely replaced).\n *\n * Strips leading `// [!code highlight:N]` and `<!-- [!code highlight:N] -->`\n * lines so the same content can be shared with preview-modifies, which uses\n * those comments for documentation highlighting.\n */\nexport function modifyByTemplate(\n filePath: string,\n template: string,\n idempotencyMarker: string,\n notFoundHint: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: notFoundHint };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (current.includes(idempotencyMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.server.ts before enabling subscriptions.\",\n \"Enable auth first — the (app) layout is provided by the velastack-auth baseline.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(\n filePath,\n template,\n \"loadActiveSubscription\",\n NOT_FOUND_HINT,\n );\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass the subscription prop to <AppSidebar> in src/routes/(app)/+layout.svelte:\",\n \"\",\n \"<AppSidebar user={data.user} subscription={data.subscription} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with an <AppSidebar /> that receives the subscription prop.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const appended = file.appendToAttributes(\n \"AppSidebar\",\n \" subscription={data.subscription}\",\n );\n if (!appended) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst SUBSCRIPTION_TYPE = \"{ id: string; productName: string | null } | null\";\n\nconst FAILURE_HINT = [\n \"Update src/lib/components/app-sidebar.svelte to forward a subscription prop:\",\n \"\",\n \"1. Add `subscription = null` to the destructured $props() call.\",\n `2. Add \\`subscription?: ${SUBSCRIPTION_TYPE}\\` to the props type.`,\n \"3. Pass `{subscription}` to <NavUser>.\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/lib/components/app-sidebar.svelte before enabling subscriptions.\",\n].join(\"\\n\");\n\nfunction updateScript(source: string): {\n source: string;\n wasAdded: boolean;\n} {\n let wasAdded = false;\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n if (elements.some((e) => e.getName() === \"subscription\")) {\n // Already has subscription prop — no-op.\n return;\n }\n\n // Insert subscription?: ... into the props type literal if present.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^\\s*subscription\\??\\s*:/.test(t))) {\n continue;\n }\n propTexts.push(`subscription?: ${SUBSCRIPTION_TYPE}`);\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Insert `subscription = null` before the first rest/default-only element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elementTexts.length;\n elementTexts.splice(insertIdx, 0, \"subscription = null\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n wasAdded = true;\n }\n formatLikeSource(sf);\n });\n return { source: out, wasAdded };\n}\n\nexport function modifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (\n original.includes(\"subscription?: {\") ||\n original.includes(\"subscription={subscription}\") ||\n original.includes(\"{subscription}\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n if (!file.hasElement(\"NavUser\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const scriptChanged = file.modifyScript((src) => updateScript(src).source);\n\n const templateChanged = !file.hasAttribute(\"NavUser\", \"subscription\")\n ? file.appendToAttributes(\"NavUser\", \" {subscription}\")\n : false;\n\n if (!scriptChanged && !templateChanged) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/lib/components/nav-user.svelte is missing.\",\n \"Enable auth and payments first; subscriptions layers a plan label on top of the existing nav-user.\",\n].join(\"\\n\");\n\nexport function modifyNavUser(\n filePath: string,\n template: string,\n): ModifyOutcome {\n // `planLabel` is unique to subscriptions — safe idempotency marker.\n return modifyByTemplate(filePath, template, \"planLabel\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.server.ts is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"selectPlan\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.svelte is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageSvelte(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"availablePlans\", NOT_FOUND_HINT);\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { modifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { modifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Share the final-state files between preview (rendered as-is) and runtime\n// (used as overwrite templates for modifies that amount to full rewrites).\nconst previewRaw = import.meta.glob<string>(\"./preview-modifies/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nfunction template(relativePath: string): string {\n const key = `./preview-modifies/${relativePath}`;\n const content = previewRaw[key];\n if (content === undefined) {\n throw new Error(\n `Missing template for ${relativePath} in subscriptions preview-modifies`,\n );\n }\n return content;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n modifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyAppLayoutServer(\n appLayoutServerPath,\n template(\"src/routes/(app)/+layout.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n modifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Modifying app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n navUserPath,\n modifyNavUser(\n navUserPath,\n template(\"src/lib/components/nav-user.svelte\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n modifyBillingPageServer(\n billingPageServerPath,\n template(\"src/routes/(app)/billing/+page.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n modifyBillingPageSvelte(\n billingPageSveltePath,\n template(\"src/routes/(app)/billing/+page.svelte\"),\n ),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAUA,IAAMA,IAAe,CAAM;;;;;;;;;;;;;;;;;;GAoBrBC,IACJ,0GAEI8B,IAA6B,CAAM;;;;;;;;;;;;;AAczC,SAAgBC,EAAoB,GAAiC;CACnE,IAAI,CAACL,EAAG,WAAWM,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAAShC;CAAe;CAGxD,IAAMiC,IAAWP,EAAG,aAAaM,GAAU,MAAM;CACjD,IAAIC,EAAS,SAAS,2BAA2B,GAC/C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAIC,IAAa,IACX,EAAE,cAAWZ,EAAmBW,IAAW,MAAO;EACtD,EAAcE,GAAI;GAChB;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;GACA;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;GACA;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;EACF,CAAC;EAED,IAAMC,IAAaD,EAChB,qBAAqBE,EAAW,eAAe,CAAC,CAChD,MAAM,MAASC,EAAK,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,YAAY,CAAC;EACvE,IAAI,CAACF,GAAY;EAGjB,IAAMG,IADYH,EAAW,aACb,CAAA,CAAU,WAAW,GAC/BI,IAAgBD,EAAQ,MAC3B,MAAME,EAAE,QAAQ,MAAMJ,EAAW,aACpC,GAIMK,IAAS,GAAGZ,EAA2B;EAC7C,IAAIU,GACF,EAAc,gBAAgBE,IAASF,EAAc,QAAQ,CAAC;OACzD,IAAID,EAAQ,SAAS,GAAG;GAC7B,IAAMI,IAAOJ,EAAQA,EAAQ,SAAS;GACtC,EAAK,gBACHI,EAAK,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oC,CAC/C,CACF,CACF,GAEA0C,EAAO,KAAK,gCAAgC;CAC5C,IAAMO,IAAsBxE,EAAK,KAC/BkE,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPAE,EACEE,EACEE,GACA5C,EAAsB4C,CAAmB,CAC3C,CACF,GAEAP,EAAO,KAAK,8BAA8B;CAC1C,IAAMQ,IAAiBzE,EAAK,KAC1BkE,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJAE,EACEE,EAAoBG,GAAgBvB,EAAiBuB,CAAc,CAAC,CACtE,GAEAR,EAAO,KAAK,2BAA2B;CACvC,IAAMS,IAAc1E,EAAK,KACvBkE,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAWA,AAVAE,EACEE,EACEI,GACAnB,EACEmB,GACAnD,EAAS,oCAAoC,CAC/C,CACF,CACF,GAEA0C,EAAO,KAAK,mCAAmC;CAC/C,IAAMU,IAAwB3E,EAAK,KACjCkE,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVAE,EACEE,EACEK,GACAlB,EACEkB,GACApD,EAAS,0CAA0C,CACrD,CACF,CACF,GAEA0C,EAAO,KAAK,gCAAgC;CAC5C,IAAMW,IAAwB5E,EAAK,KACjCkE,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAWA,OAVAE,EACEE,EACEM,GACAjB,EACEiB,GACArD,EAAS,uCAAuC,CAClD,CACF,CACF,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-CslAvllQ.js","names":["libModule","getLogger","planDropsForCollections","withInMemoryScript","removeUnusedBindingElement","ensureBlankLineAfterImports","removePropsBindingIfUnused","removeImportByModuleSpecifier","SvelteFile","fs","path","unmodifyLayoutServer","layoutPath","originalSource","sourceFile","Project","literals","SyntaxKind","obj","userProp","formatLikeSource","unmodifyRootLayoutSvelte","source","file","markup","out","content","sf","unmodifyHooksServer","hooksServerPath","callExpr","ce","firstArg","optionsObj","authProp","generate","logger","options","modifies","pushResult","layoutServerFile","modifyOutcomeToFile","layoutCandidates","layoutFile","p","hooksServerFile"],"sources":["../../src/patterns/disable/auth/modifies/+layout.server.ts","../../src/patterns/disable/auth/modifies/root-layout.svelte.ts","../../src/patterns/disable/auth/modifies/hooks.server.ts","../../src/patterns/disable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeUnusedBindingElement,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n if (!originalSource.includes(\"locals.pb.authStore.record\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const literals = sourceFile.getDescendantsOfKind(\n SyntaxKind.ObjectLiteralExpression,\n );\n for (const obj of literals) {\n const userProp = obj.getProperty(\"user\");\n if (!userProp || userProp.getKind() !== SyntaxKind.PropertyAssignment) {\n continue;\n }\n const value = (userProp as import(\"ts-morph\").PropertyAssignment)\n .getInitializer()\n ?.getText();\n if (value === \"locals.pb.authStore.record\") {\n userProp.remove();\n }\n }\n // `user` was often the layout's only use of `locals`, which enable-auth\n // destructured for it.\n removeUnusedBindingElement(sourceFile, \"locals\");\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n removePropsBindingIfUnused,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nexport function unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(layoutPath, \"utf8\");\n const file = new SvelteFile(source);\n if (!file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.removeElement(\"AuthMenu.Root\");\n const markup = file.toString().replace(/<script[\\s\\S]*?<\\/script>/g, \"\");\n\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/auth-menu\"));\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/avatar\"));\n // enable-auth added `data` for the menu's `data.user`.\n removePropsBindingIfUnused(sf, \"data\", markup);\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n return { status: \"success\", changed: false };\n }\n\n authProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerFile,\n unmodifyLayoutServer(layoutServerFile),\n ),\n );\n\n logger.info(\"Reverting root layout\");\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, unmodifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, unmodifyHooksServer(hooksServerFile)),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"oauth_accounts\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAQA,SAAgBW,EAAqB,GAAmC;CACtE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAiBJ,EAAG,aAAaG,GAAY,MAAM;CACzD,IAAI,CAACC,EAAe,SAAS,4BAA4B,GACvD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAMC,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBH,CAAU,GAEnDI,IAAWF,EAAW,qBAC1BG,EAAW,uBACb;CACA,KAAK,IAAMC,KAAOF,GAAU;EAC1B,IAAMG,IAAWD,EAAI,YAAY,MAAM;EACvC,AAAKC,KAAYA,EAAS,QAAQ,MAAMF,EAAW,sBAGpCE,EACZ,eAAe,CAAC,EACf,QAAQ,MACE,gCACZA,EAAS,OAAO;CAEpB;CAQA,OALAf,EAA2BU,GAAY,QAAQ,GAE/CM,EAAiBN,CAAU,GAC3BA,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAASA,EAAW,YAAY,MAAMD;CACxC;AACF;;;ACpCA,SAAgBQ,EAAyB,GAAmC;CAC1E,IAAI,CAACZ,EAAG,WAAWG,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMU,IAASb,EAAG,aAAaG,GAAY,MAAM,GAC3CW,IAAO,IAAIf,EAAWc,CAAM;CAClC,IAAI,CAACC,EAAK,WAAW,eAAe,GAClC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,EAAK,cAAc,eAAe;CAClC,IAAMC,IAASD,EAAK,SA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ropsBinding","formatLikeSource","ensureImports","SvelteFile","withPocketbase","migrationDelay","getMigrationFile","ensureSiteFile","fs","path","modifyLayoutServer","layoutPath","snippet","originalSource","sourceFile","Project","addUserProp","obj","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","el","parts","tail","currentName","body","expr","ret","inner","bodyExpr","AUTH_MENU_NAVBAR_ITEM","IMPORT_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$1","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","COOKIE_LOGIN","modifyTestSetup","setupPath","helper","generate","options","logger","creates","pb","input","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","modifyOutcomeToFile","layoutCandidates","layoutFile","p","hooksServerFile","testSetupFile","remote","modifySvelteConfigRemote","siteFile"],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/modifies/test-setup.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<Avatar.Root>\n\t\t\t\t\t\t\t{#if data.user?.avatar}\n\t\t\t\t\t\t\t\t<Avatar.Image\n\t\t\t\t\t\t\t\t\tsrc=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n\t\t\t\t\t\t\t\t\talt={data.user?.email}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t<Avatar.Fallback>\n\t\t\t\t\t\t\t\t{data.user?.email?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import * as Avatar from '#lib/components/ui/avatar/index.js';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"#lib/components/ui/auth-menu/index.js\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"#lib/components/ui/avatar/index.js\",\n },\n ]);\n // The menu reads `data.user`; the template's layout takes no props.\n ensurePropsBinding(sf, \"data\");\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", AUTH_MENU_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the auth option in hooks.server.ts:\n\n handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Find the handlePocketbase(...) call\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Ensure auth property exists\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n optionsObj.addPropertyAssignment({\n name: \"auth\",\n initializer: `{ protectedRoutes: ['/(app)'] }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // If auth exists, ensure protectedRoutes includes '/(app)'\n if (authProp.getKind() === SyntaxKind.PropertyAssignment) {\n const authInit = (\n authProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (authInit && authInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const authObj = authInit as import(\"ts-morph\").ObjectLiteralExpression;\n const prProp = authObj.getProperty(\"protectedRoutes\");\n if (!prProp) {\n authObj.addPropertyAssignment({\n name: \"protectedRoutes\",\n initializer: `['/(app)']`,\n });\n } else if (prProp.getKind() === SyntaxKind.PropertyAssignment) {\n const prInit = (\n prProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (prInit && prInit.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = prInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasApp = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \"/(app)\");\n if (!hasApp) {\n arr.addElement(`'/(app)'`);\n }\n } else {\n (prProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `['/(app)']`,\n );\n }\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst COOKIE_LOGIN = dedent`\n // Login is a remote function, so there is no form action to post to: carry\n // the session the way the browser does, in the \\`pb_auth\\` cookie.\n async function authenticateUser(agent: Agent, user: { email: string }) {\n const client = new PocketBase(process.env.POCKETBASE_URL!);\n await client.collection(\"users\").authWithPassword(user.email, testUserPassword);\n agent.set(\"Cookie\", client.authStore.exportToCookie().split(\";\")[0]);\n }\n`;\n\n/**\n * The template's server-test helper logs in by posting the `/login` form\n * action, which this pattern replaces with a remote function. A project\n * without the helper (or with its own) has nothing to fix.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(setupPath);\n const helper = sourceFile.getFunction(\"authenticateUser\");\n\n if (!helper || !/\\.post\\(\\s*[\"'`]\\/login[\"'`]\\s*\\)/.test(helper.getText())) {\n return { status: \"success\", changed: false };\n }\n\n helper.replaceWithText(COOKIE_LOGIN);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifySvelteConfigRemote } from \"../../../runtime/modify-svelte-config-remote\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifyTestSetup } from \"./modifies/test-setup\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying test/setup.ts\");\n const testSetupFile = path.join(options.root, \"test\", \"setup.ts\");\n pushResult(\n modifyOutcomeToFile(testSetupFile, modifyTestSetup(testSetupFile)),\n );\n\n logger.info(\"Modifying config for remote functions\");\n const remote = modifySvelteConfigRemote(options.root);\n pushResult(modifyOutcomeToFile(remote.filePath, remote.outcome));\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAMA,SAAgBe,EAAmB,GAAmC;CACpE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAAG;EAC9B,IAAMC,IAAU,CAAM;;;;;EAOtB,OADAJ,EAAG,cAAcG,GAAYC,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CAC5C;CAEA,IAAMC,IAAiBL,EAAG,aAAaG,GAAY,MAAM,GAEnDG,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBJ,CAAU,GAGnDK,KAAe,MAAoD;EAEvE,AADkBC,EAAI,YAAY,MAAM,KAEtCA,EAAI,sBAAsB;GACxB,MAAM;GACN,aAAa;EACf,CAAC;CAEL,GAGIC,GACAC,GAKEC,IAAUN,EAAW,uBAAuB,MAAM;CACxD,IAAIM,KACSA,EAAQ,uBAAuBC,EAAW,iBAChC,CAAA,EAAI,iBAAiB,GAC1B;EACd,IAAMC,IAAcF,EAAQ,qBAC1BC,EAAW,aACb;EACA,IAAIC,GACF,IAAYA;OACP;GACL,IAAMC,IAAOH,EAAQ,eAAe;GACpC,IAAIG,GAAM;IACR,IAAMC,IAAaD,EAAK,yBACtBF,EAAW,aACb;IACA,IAAIG,GACF,IAAYA;SACP;KACL,IAAMC,IAAcF,EAAK,yBACvBF,EAAW,kBACb;KACA,AAAII,MACF,IAASA;IAEb;GACF;EACF;CACF;CAGF,IAAI,CAACP,GAAW;EACd,IAAMQ,IAAUZ,EAAW,YAAY,MAAM;EAC7C,AAAIY,KAAWA,EAAQ,WAAW,MAChC,IAASA;CAEb;CAGA,IAAI,CAACR,KAAa,CAACC,GAUjB,OATAL,EAAW,YAAY;EACrB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C;CACnD,IAAMkB,IAASC,EAAyBpB,EAAQ,IAAI;CACpD,EAAWa,EAAoBM,EAAO,UAAUA,EAAO,OAAO,CAAC;CAG/D,IAAME,IAAW,MAAMrF,EAAegE,CAAO;CAE7C,OAAO;EACL,SAASqB,IAAW,CAACA,CAAQ,IAAI,CAAC;EAClC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-pVLzzpUM.js","names":["isLibSpecifier","getLogger","planDropsForCollections","modifyEnvRemove","removeNavItemFromScript","formatLikeSource","SvelteFile","STRIPE_ENV_VAR_NAMES","fs","path","unmodifyNavUser","navUserPath","source","file","wasRemoved","tryRemove","run","result","src","fn","CALL_EXPRESSIONS","unmodifyUserSignup","userSignupPath","originalSource","sourceFile","Project","QuoteKind","module","decl","d","linkFn","s","callStatements","SyntaxKind","ce","call","stmt","generate","isAppMode","options","logger","modifies","deletes","pushResult","envEdits","envPath","modifyOutcomeToFile","envVars","unmodifyEnvVarsFiles"],"sources":["../../src/patterns/disable/payments/modifies/modify-nav-user.ts","../../src/patterns/disable/payments/modifies/modify-user-signup.ts","../../src/patterns/disable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { removeNavItemFromScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(source);\n let wasRemoved = false;\n\n const tryRemove = (run: (fn: (s: string) => string) => boolean) => {\n if (wasRemoved) return;\n run((src) => {\n const result = removeNavItemFromScript(\n src,\n \"Billing\",\n \"@lucide/svelte/icons/credit-card\",\n );\n if (result.wasRemoved) wasRemoved = true;\n return result.source;\n });\n };\n\n tryRemove((fn) => file.modifyModuleScript(fn));\n if (!wasRemoved) tryRemove((fn) => file.modifyScript(fn));\n\n if (!wasRemoved) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(navUserPath, file.toString(), \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\nimport { isLibSpecifier } from \"../../../../runtime/lib-specifier\";\n\nconst CALL_EXPRESSIONS = new Set([\n \"linkStripeCustomer.run\",\n // Projects from before the workflow: an inline helper called directly.\n \"linkStripeCustomer\",\n]);\n\nexport function unmodifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (!originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n for (const module of [\"workflows/link-stripe-customer\", \"stripe\"]) {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => isLibSpecifier(d.getModuleSpecifierValue(), module));\n if (decl) decl.remove();\n }\n\n const linkFn = sourceFile.getVariableStatement((s) =>\n s.getDeclarations().some((d) => d.getName() === \"linkStripeCustomer\"),\n );\n if (linkFn) linkFn.remove();\n\n const callStatements = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => CALL_EXPRESSIONS.has(ce.getExpression().getText()));\n for (const call of callStatements) {\n const stmt = call.getFirstAncestorByKind(SyntaxKind.ExpressionStatement);\n if (stmt) stmt.remove();\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnvRemove, type EnvEdit } from \"../../../runtime/env\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { STRIPE_ENV_VAR_NAMES } from \"../../enable/payments/runtime/env-vars\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Stripping Stripe credentials from .env\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\" },\n { type: \"var\", key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\" },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\" },\n ];\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnvRemove(envPath, envEdits)));\n\n logger.info(\"Removing Stripe variables from src/env.ts\");\n const envVars = unmodifyEnvVarsFiles(options.root, STRIPE_ENV_VAR_NAMES);\n pushResult(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n if (isAppMode) {\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(\"Reverting signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, unmodifyUserSignup(userSignupPath)),\n );\n }\n\n const collectionNames = [\n \"transactions\",\n \"stripe_customers\",\n \"stripe_payment_methods\",\n \"stripe_prices\",\n \"stripe_products\",\n ];\n const collectionDrops = await planDropsForCollections(\n isAppMode ? collectionNames : [\"stripe_prices\", \"stripe_products\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes,\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;AAKA,SAAgBU,EAAgB,GAAoC;CAClE,IAAI,CAACF,EAAG,WAAWG,CAAW,GAC5B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAASJ,EAAG,aAAaG,GAAa,MAAM;CAClD,IAAI,CAACC,EAAO,SAAS,UAAU,GAC7B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAO,IAAIP,EAAWM,CAAM,GAC9BE,IAAa,IAEXC,KAAa,MAAgD;EACjE,AAAID,KACJE,GAAK,MAAQ;GACX,IAAMC,IAASb,EACbc,GACA,WACA,kCACF;GAEA,OADID,EAAO,eAAY,IAAa,KAC7BA,EAAO;EAChB,CAAC;CACH;CAUA,OARAF,GAAW,MAAOF,EAAK,mBAAmBM,CAAE,CAAC,GACxCL,KAAYC,GAAW,MAAOF,EAAK,aAAaM,CAAE,CAAC,GAEnDL,KAILN,EAAG,cAAcG,GAAaE,EAAK,SAAS,GAAG,MAAM,GAC9C;EAAE,QAAQ;EAAW,SAAS;CAAK,KAJjC;EAAE,QAAQ;EAAW,SAAS;CAAM;AAK/C;;;AClCA,IAAMO,oBAAmB,IAAI,IAAI,CAC/B,0BAEA,oBACF,CAAC;AAED,SAAgBC,EAAmB,GAAuC;CACxE,IAAI,CAACb,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CAEA,EAAO,KAAK,wCAAwC;CACpD,IAAM+B,IAAsB;EAC1B;GAAE,MAAM;GAAW,KAAK;EAAqB;EAC7C;GAAE,MAAM;GAAO,KAAK;EAAoB;EACxC;GAAE,MAAM;GAAO,KAAK;EAAgC;EACpD;GAAE,MAAM;GAAO,KAAK;EAAwB;CAC9C,GACMC,IAAUpC,EAAK,KAAK8B,EAAQ,MAAM,MAAM;CAG9C,AAFAI,EAAWG,EAAoBD,GAAS1C,EAAgB0C,GAASD,CAAQ,CAAC,CAAC,GAE3EJ,EAAO,KAAK,2CAA2C;CACvD,IAAMO,IAAUC,EAAqBT,EAAQ,MAAMhC,CAAoB;CAIvE,IAHAoC,EAAWI,EAAQ,MAAM,GACrBA,EAAQ,UAAQL,EAAQ,KAAKK,EAAQ,MAAM,GAE3CT,GAAW;EACb,EAAO,KAAK,2BAA2B;EACvC,IAAM3B,IAAcF,EAAK,KACvB8B,EAAQ,MACR,OACA,OACA,cACA,iBACF;EAGA,AAFAI,EAAWG,EAAoBnC,GAAaD,EAAgBC,CAAW,CAAC,CAAC,GAEzE6B,EAAO,KAAK,kCAAkC;EAC9C,IAAMlB,IAAiBb,EAAK,KAC1B8B,EAAQ,MACR,OACA,UACA,YACA,UACA,UACA,iBACF;EACA,EACEO,EAAoBxB,GAAgBD,EAAmBC,CAAc,CAAC,CACxE;CACF;CAcA,OAAO;EACL,SAAS,CAAC;EACV;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BpB,EAC5BoC,IAAY;GAPZ;GACA;GACA;GACA;GACA;EAGY,IAAkB,CAAC,iBAAiB,iBAAiB,GACjEC,CACF;CAWA;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-zJpEufTc.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","dedent","getLogger","withInMemoryScript","ensurePropsBinding","formatLikeSource","ensureImports","SvelteFile","withPocketbase","migrationDelay","getMigrationFile","ensureSiteFile","fs","path","modifyLayoutServer","layoutPath","snippet","originalSource","sourceFile","Project","addUserProp","obj","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","el","parts","tail","currentName","body","expr","ret","inner","bodyExpr","AUTH_MENU_NAVBAR_ITEM","IMPORT_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$2","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT$1","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","VARIANTS","NOT_FOUND_HINT","modifySidebarMenuButton","filePath","to","variant","from","updated","generate","options","logger","creates","pb","input","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","modifyOutcomeToFile","layoutCandidates","layoutFile","p","hooksServerFile","sidebarMenuButtonFile","siteFile"],"sources":["../../src/patterns/enable/auth/modifies/+layout.server.ts","../../src/patterns/enable/auth/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth/modifies/hooks.server.ts","../../src/patterns/enable/auth/modifies/sidebar-menu-button.svelte.ts","../../src/patterns/enable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<Avatar.Root>\n\t\t\t\t\t\t\t{#if data.user?.avatar}\n\t\t\t\t\t\t\t\t<Avatar.Image\n\t\t\t\t\t\t\t\t\tsrc=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n\t\t\t\t\t\t\t\t\talt={data.user?.email}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t<Avatar.Fallback>\n\t\t\t\t\t\t\t\t{data.user?.email?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import * as Avatar from '#lib/components/ui/avatar/index.js';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"#lib/components/ui/auth-menu/index.js\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"#lib/components/ui/avatar/index.js\",\n },\n ]);\n // The menu reads `data.user`; the template's layout takes no props.\n ensurePropsBinding(sf, \"data\");\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", AUTH_MENU_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the auth option in hooks.server.ts:\n\n handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Find the handlePocketbase(...) call\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Ensure auth property exists\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n optionsObj.addPropertyAssignment({\n name: \"auth\",\n initializer: `{ protectedRoutes: ['/(app)'] }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // If auth exists, ensure protectedRoutes includes '/(app)'\n if (authProp.getKind() === SyntaxKind.PropertyAssignment) {\n const authInit = (\n authProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (authInit && authInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const authObj = authInit as import(\"ts-morph\").ObjectLiteralExpression;\n const prProp = authObj.getProperty(\"protectedRoutes\");\n if (!prProp) {\n authObj.addPropertyAssignment({\n name: \"protectedRoutes\",\n initializer: `['/(app)']`,\n });\n } else if (prProp.getKind() === SyntaxKind.PropertyAssignment) {\n const prInit = (\n prProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (prInit && prInit.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = prInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasApp = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \"/(app)\");\n if (!hasApp) {\n arr.addElement(`'/(app)'`);\n }\n } else {\n (prProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `['/(app)']`,\n );\n }\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst VARIANTS = [\n {\n from: \"'data-active': isActive,\",\n to: \"'data-active': isActive ? true : undefined,\",\n },\n {\n from: '\"data-active\": isActive,',\n to: '\"data-active\": isActive ? true : undefined,',\n },\n];\n\nconst NOT_FOUND_HINT = dedent`\n The shadcn-svelte sidebar component was not installed at the expected path.\n Run: vela enable auth (or install the 'sidebar' shadcn-svelte component).\n`;\n\nexport function modifySidebarMenuButton(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n\n if (VARIANTS.some(({ to }) => original.includes(to))) {\n return { status: \"success\", changed: false };\n }\n\n const variant = VARIANTS.find(({ from }) => original.includes(from));\n if (!variant) {\n return { status: \"success\", changed: false };\n }\n\n const updated = original.replace(variant.from, variant.to);\n fs.writeFileSync(filePath, updated, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifySidebarMenuButton } from \"./modifies/sidebar-menu-button.svelte\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying sidebar-menu-button.svelte\");\n const sidebarMenuButtonFile = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"ui\",\n \"sidebar\",\n \"sidebar-menu-button.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n sidebarMenuButtonFile,\n modifySidebarMenuButton(sidebarMenuButtonFile),\n ),\n );\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\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,4BACF;CACA,EACEa,EACEK,GACAzB,EAAwByB,CAAqB,CAC/C,CACF;CAGA,IAAMC,IAAW,MAAMvF,EAAeoE,CAAO;CAE7C,OAAO;EACL,SAASmB,IAAW,CAACA,CAAQ,IAAI,CAAC;EAClC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,6 +0,0 @@
1
- //#region src/patterns/enable/payments/creates-app-mode/src/routes/(app)/billing/+page.server.ts?raw
2
- var e = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"#lib/stripe.js\";\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n depends(\"app:billing\");\n\n let customer;\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n locals.admin.filter(\"user = {:user}\", { user: user.id }),\n );\n } catch {\n // The link-stripe-customer workflow started at signup has not finished.\n return { paymentMethods: [], user, billingReady: false };\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n return {\n billingReady: true,\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n };\n};\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n};\n", t = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import * as Card from '#lib/components/ui/card/index.js';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import * as AlertDialog from '#lib/components/ui/alert-dialog/index.js';\n import SetupButton from '#lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate } from '$app/navigation';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if !data.billingReady}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">Setting up billing</p>\n <p class=\"text-sm\">This takes a moment after signing up. Refresh to check again.</p>\n </div>\n {:else if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n {#if data.billingReady}\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n {/if}\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", n = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n // [!code highlight:1]\n import CreditCardIcon from '@lucide/svelte/icons/credit-card';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '#lib/components/ui/avatar/index.js';\n import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';\n import * as Sidebar from '#lib/components/ui/sidebar/index.js';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n // [!code highlight:5]\n {\n title: 'Billing',\n url: '/billing',\n icon: CreditCardIcon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() || user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name || user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() || user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name || user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n";
3
- //#endregion
4
- export { t as n, e as r, n as t };
5
-
6
- //# sourceMappingURL=nav-user-BRIHOOpG.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"nav-user-BRIHOOpG.js","names":["_page_server_default","_page_default","nav_user_default"],"sources":[],"mappings":""}