@velastack/patterns 0.2.7 → 0.2.9

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 (78) hide show
  1. package/README.md +15 -0
  2. package/dist/chunks/{collections-B3lAtPlQ.js → collections-DDYlpDNO.js} +38 -22
  3. package/dist/chunks/collections-DDYlpDNO.js.map +1 -0
  4. package/dist/chunks/constants-DSFKQwtP.js +6 -0
  5. package/dist/chunks/{constants-PBCzh8eY.js.map → constants-DSFKQwtP.js.map} +1 -1
  6. package/dist/chunks/dispatch-B5PfQ2CA.js +6 -0
  7. package/dist/chunks/dispatch-B5PfQ2CA.js.map +1 -0
  8. package/dist/chunks/{generate.runtime-BKb9thdE.js → generate.runtime-AjCpCfv3.js} +2 -2
  9. package/dist/chunks/{generate.runtime-BKb9thdE.js.map → generate.runtime-AjCpCfv3.js.map} +1 -1
  10. package/dist/chunks/{generate.runtime-DCvLLO7w.js → generate.runtime-B6kxV3Bi.js} +67 -124
  11. package/dist/chunks/generate.runtime-B6kxV3Bi.js.map +1 -0
  12. package/dist/chunks/{generate.runtime-CXXwLatT.js → generate.runtime-BYJZB1ad.js} +2 -2
  13. package/dist/chunks/{generate.runtime-CXXwLatT.js.map → generate.runtime-BYJZB1ad.js.map} +1 -1
  14. package/dist/chunks/{generate.runtime-BsuyMwoj.js → generate.runtime-B_Fk1Jjs.js} +2 -2
  15. package/dist/chunks/{generate.runtime-BsuyMwoj.js.map → generate.runtime-B_Fk1Jjs.js.map} +1 -1
  16. package/dist/chunks/{generate.runtime-BjULAL3h.js → generate.runtime-BcVAKzoY.js} +3 -3
  17. package/dist/chunks/{generate.runtime-BjULAL3h.js.map → generate.runtime-BcVAKzoY.js.map} +1 -1
  18. package/dist/chunks/{generate.runtime-Dc98DCsh.js → generate.runtime-BgezGu15.js} +3 -3
  19. package/dist/chunks/{generate.runtime-Dc98DCsh.js.map → generate.runtime-BgezGu15.js.map} +1 -1
  20. package/dist/chunks/{generate.runtime-BdTCMGGB.js → generate.runtime-BpYOznG5.js} +3 -3
  21. package/dist/chunks/{generate.runtime-BdTCMGGB.js.map → generate.runtime-BpYOznG5.js.map} +1 -1
  22. package/dist/chunks/{generate.runtime-DKJaYtVZ.js → generate.runtime-BtX_9lLk.js} +42 -66
  23. package/dist/chunks/generate.runtime-BtX_9lLk.js.map +1 -0
  24. package/dist/chunks/{generate.runtime-lqPPXQyS.js → generate.runtime-CTiJEVF2.js} +4 -4
  25. package/dist/chunks/{generate.runtime-lqPPXQyS.js.map → generate.runtime-CTiJEVF2.js.map} +1 -1
  26. package/dist/chunks/{generate.runtime-BlQ1vx8j.js → generate.runtime-CZQoVNt3.js} +97 -138
  27. package/dist/chunks/generate.runtime-CZQoVNt3.js.map +1 -0
  28. package/dist/chunks/{generate.runtime-B9gdCz4t.js → generate.runtime-Cq1gqxzg.js} +2 -2
  29. package/dist/chunks/{generate.runtime-B9gdCz4t.js.map → generate.runtime-Cq1gqxzg.js.map} +1 -1
  30. package/dist/chunks/{generate.runtime-FMYR64DL.js → generate.runtime-CycY6kPr.js} +3 -3
  31. package/dist/chunks/{generate.runtime-FMYR64DL.js.map → generate.runtime-CycY6kPr.js.map} +1 -1
  32. package/dist/chunks/{generate.runtime-CGkVUKvz.js → generate.runtime-D2WfvXm2.js} +2 -2
  33. package/dist/chunks/{generate.runtime-CGkVUKvz.js.map → generate.runtime-D2WfvXm2.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-4Iplvp8f.js → generate.runtime-DEl6b1Ti.js} +2 -2
  35. package/dist/chunks/{generate.runtime-4Iplvp8f.js.map → generate.runtime-DEl6b1Ti.js.map} +1 -1
  36. package/dist/chunks/{generate.runtime-Wssys8A0.js → generate.runtime-DH9o-888.js} +18 -18
  37. package/dist/chunks/generate.runtime-DH9o-888.js.map +1 -0
  38. package/dist/chunks/{generate.runtime-kH6XaWQz.js → generate.runtime-DHRCNPVx.js} +3 -3
  39. package/dist/chunks/{generate.runtime-kH6XaWQz.js.map → generate.runtime-DHRCNPVx.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-BltGUllM.js → generate.runtime-DK7iXmAZ.js} +3 -3
  41. package/dist/chunks/{generate.runtime-BltGUllM.js.map → generate.runtime-DK7iXmAZ.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-tAbxWeq-.js → generate.runtime-DRcq4d5D.js} +4 -4
  43. package/dist/chunks/{generate.runtime-tAbxWeq-.js.map → generate.runtime-DRcq4d5D.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-C-Val7lP.js → generate.runtime-Dmwhwgji.js} +3 -3
  45. package/dist/chunks/{generate.runtime-C-Val7lP.js.map → generate.runtime-Dmwhwgji.js.map} +1 -1
  46. package/dist/chunks/generate.runtime-Dtf2BI_5.js +87 -0
  47. package/dist/chunks/generate.runtime-Dtf2BI_5.js.map +1 -0
  48. package/dist/chunks/{generate.runtime-DWeiewRj.js → generate.runtime-OjW1XETW.js} +3 -3
  49. package/dist/chunks/{generate.runtime-DWeiewRj.js.map → generate.runtime-OjW1XETW.js.map} +1 -1
  50. package/dist/chunks/{generate.runtime-QmFJI7G1.js → generate.runtime-vTneb2SY.js} +4 -4
  51. package/dist/chunks/{generate.runtime-QmFJI7G1.js.map → generate.runtime-vTneb2SY.js.map} +1 -1
  52. package/dist/chunks/nav-user-BYI-h8Od.js +6 -0
  53. package/dist/chunks/nav-user-BYI-h8Od.js.map +1 -0
  54. package/dist/chunks/{pocketbase-059B1oot.js → pocketbase-BerjVikJ.js} +2 -2
  55. package/dist/chunks/{pocketbase-059B1oot.js.map → pocketbase-BerjVikJ.js.map} +1 -1
  56. package/dist/chunks/{shared--_BWnGsc.js → shared-Cmbzu7Od.js} +2 -2
  57. package/dist/chunks/{shared--_BWnGsc.js.map → shared-Cmbzu7Od.js.map} +1 -1
  58. package/dist/chunks/{taggedTemplateLiteral-CPUMuLtk.js → taggedTemplateLiteral-Dx0fjWiw.js} +1 -1
  59. package/dist/chunks/{ts-morph-helpers-Bf5iuQW8.js → ts-morph-helpers-teS3yXg-.js} +2 -2
  60. package/dist/chunks/{ts-morph-helpers-Bf5iuQW8.js.map → ts-morph-helpers-teS3yXg-.js.map} +1 -1
  61. package/dist/chunks/{ui-BsG60gQg.js → ui-BdkuOXPw.js} +2 -2
  62. package/dist/chunks/{ui-BsG60gQg.js.map → ui-BdkuOXPw.js.map} +1 -1
  63. package/dist/chunks/{write-result-BN7Ff0rF.js → write-result-BVWPlGvE.js} +9 -9
  64. package/dist/chunks/{write-result-BN7Ff0rF.js.map → write-result-BVWPlGvE.js.map} +1 -1
  65. package/dist/index.d.ts +218 -64
  66. package/dist/index.js +2186 -1702
  67. package/dist/index.js.map +1 -1
  68. package/package.json +3 -3
  69. package/dist/chunks/_server-BSm1eAiY.js +0 -6
  70. package/dist/chunks/_server-BSm1eAiY.js.map +0 -1
  71. package/dist/chunks/collections-B3lAtPlQ.js.map +0 -1
  72. package/dist/chunks/constants-PBCzh8eY.js +0 -6
  73. package/dist/chunks/generate.runtime-BlQ1vx8j.js.map +0 -1
  74. package/dist/chunks/generate.runtime-DCvLLO7w.js.map +0 -1
  75. package/dist/chunks/generate.runtime-DKJaYtVZ.js.map +0 -1
  76. package/dist/chunks/generate.runtime-Wssys8A0.js.map +0 -1
  77. package/dist/chunks/nav-user-CndUO69x.js +0 -6
  78. package/dist/chunks/nav-user-CndUO69x.js.map +0 -1
@@ -1,33 +1,32 @@
1
1
  import { a as e } from "./util-BLYliuUK.js";
2
2
  import { t } from "./dedent-Gq6Krl4n.js";
3
- import { t as n } from "./taggedTemplateLiteral-CPUMuLtk.js";
3
+ import { t as n } from "./taggedTemplateLiteral-Dx0fjWiw.js";
4
4
  import { n as r } from "./logger-CQONztPm.js";
5
5
  import { modifyOutcomeToFile as i } from "./modify-file-Cgu_WeFk.js";
6
- import { l as a, t as o } from "./ts-morph-helpers-Bf5iuQW8.js";
6
+ import { l as a, t as o } from "./ts-morph-helpers-teS3yXg-.js";
7
7
  import { t as s } from "./env-BPfk1VAw.js";
8
- import { getMigrationFile as c, migrationDelay as l, withPocketbase as u } from "./pocketbase-059B1oot.js";
9
- import { createCollectionIdempotent as d } from "./collections-B3lAtPlQ.js";
8
+ import { getMigrationFile as c, migrationDelay as l, withPocketbase as u } from "./pocketbase-BerjVikJ.js";
9
+ import { createCollectionIdempotent as d } from "./collections-DDYlpDNO.js";
10
10
  import f from "node:path";
11
11
  import p from "node:fs";
12
12
  import { Project as m, QuoteKind as h, SyntaxKind as g } from "ts-morph";
13
- import { randomBytes as _ } from "node:crypto";
14
- import v from "stripe";
13
+ import _ from "stripe";
15
14
  //#region src/patterns/enable/payments/modifies/modify-nav-user.ts
16
- var y = [
15
+ var v = [
17
16
  "import CreditCardIcon from '@lucide/svelte/icons/credit-card';",
18
17
  "",
19
18
  "// Add to your navUser array:",
20
19
  "{ title: 'Billing', url: '/billing', icon: CreditCardIcon }"
21
- ].join("\n"), b = [
20
+ ].join("\n"), y = [
22
21
  "Add a Billing nav item to nav-user.svelte:",
23
22
  "",
24
- y
25
- ].join("\n"), x = [
23
+ v
24
+ ].join("\n"), b = [
26
25
  "Create nav-user.svelte with a Billing entry:",
27
26
  "",
28
- y
27
+ v
29
28
  ].join("\n");
30
- function S(e, t, n, r, i) {
29
+ function x(e, t, n, r, i) {
31
30
  let s = new a(e), c = !1, l = (e) => {
32
31
  c || e((e) => {
33
32
  let a = o(e, t, n, r, i);
@@ -39,127 +38,76 @@ function S(e, t, n, r, i) {
39
38
  wasAdded: c
40
39
  };
41
40
  }
42
- function C(e) {
41
+ function S(e) {
43
42
  if (!p.existsSync(e)) return {
44
43
  status: "not-found",
45
- message: x
44
+ message: b
46
45
  };
47
46
  let t = p.readFileSync(e, "utf8");
48
47
  if (t.includes("/billing")) return {
49
48
  status: "success",
50
49
  changed: !1
51
50
  };
52
- let { newNavUserSnippet: n, wasAdded: r } = S(t, "Billing", "/billing", "CreditCardIcon", "@lucide/svelte/icons/credit-card");
51
+ let { newNavUserSnippet: n, wasAdded: r } = x(t, "Billing", "/billing", "CreditCardIcon", "@lucide/svelte/icons/credit-card");
53
52
  return r ? (p.writeFileSync(e, n, "utf8"), {
54
53
  status: "success",
55
54
  changed: !0
56
55
  }) : {
57
56
  status: "failed",
58
- message: b
57
+ message: y
59
58
  };
60
59
  }
61
60
  //#endregion
62
61
  //#region src/patterns/enable/payments/modifies/modify-user-signup.ts
63
- var w = t`
64
- const linkStripeCustomer = async (email: string, user: { id: string }, locals: App.Locals) => {
65
- const matchingCustomer = await stripe.customers.list({
66
- email: email,
67
- limit: 1,
68
- expand: ['data.invoice_settings']
69
- });
70
-
71
- let customer;
72
- let isExistingCustomer = false;
73
-
74
- if (matchingCustomer.data.length > 0) {
75
- isExistingCustomer = true;
76
- customer = matchingCustomer.data[0];
77
- } else {
78
- customer = await stripe.customers.create({
79
- email: email
80
- });
81
- }
82
-
83
- await locals.admin.collection('stripe_customers').create({
84
- id: customer.id,
85
- user: user.id
86
- });
87
-
88
- if (!isExistingCustomer) {
89
- return;
90
- }
91
-
92
- const paymentMethods = await stripe.customers.listPaymentMethods(customer.id, {
93
- type: 'card',
94
- allow_redisplay: 'always'
95
- });
96
-
97
- for (const paymentMethod of paymentMethods.data) {
98
- if (paymentMethod.allow_redisplay === 'unspecified') {
99
- continue;
100
- }
101
-
102
- await locals.admin.collection('stripe_payment_methods').create({
103
- id: paymentMethod.id,
104
- customer: customer.id,
105
- brand: paymentMethod.card?.brand,
106
- last4: paymentMethod.card?.last4,
107
- exp_month: paymentMethod.card?.exp_month,
108
- exp_year: paymentMethod.card?.exp_year
109
- });
110
- }
111
-
112
- const defaultPaymentMethod = customer.invoice_settings?.default_payment_method;
113
-
114
- if (defaultPaymentMethod) {
115
- try {
116
- await locals.admin.collection('stripe_customers').update(customer.id, {
117
- default_payment_method: defaultPaymentMethod
118
- });
119
- } catch {}
120
- }
121
- };
122
- `, T = ["Could not locate the requestVerification call in signup +page.server.ts.", "Add a linkStripeCustomer helper and call it before requestVerification()."].join("\n"), E = ["Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments."].join("\n");
62
+ var C = "$lib/workflows/link-stripe-customer", w = t`
63
+ // Queued here, done in the background: the Stripe calls retry on their own,
64
+ // and the key means a retry never makes a second customer for this user.
65
+ await linkStripeCustomer.run(
66
+ { userId: user.id, email: form.data.email },
67
+ { idempotencyKey: user.id }
68
+ );
69
+ `, T = [
70
+ "Could not locate the requestVerification call in signup +page.server.ts.",
71
+ "Start the workflow once the user exists:",
72
+ "",
73
+ `import { linkStripeCustomer } from '${C}';`,
74
+ "",
75
+ w
76
+ ].join("\n"), E = ["Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments."].join("\n");
123
77
  function D(e) {
124
78
  if (!p.existsSync(e)) return {
125
79
  status: "not-found",
126
80
  message: E
127
81
  };
128
- let n = p.readFileSync(e, "utf8"), r = new m({ manipulationSettings: { quoteKind: h.Single } }).addSourceFileAtPath(e);
129
- if (r.getImportDeclarations().some((e) => e.getModuleSpecifierValue() === "$lib/stripe")) return {
82
+ let t = p.readFileSync(e, "utf8");
83
+ if (t.includes("linkStripeCustomer")) return {
130
84
  status: "success",
131
85
  changed: !1
132
86
  };
133
- r.addImportDeclaration({
134
- defaultImport: "stripe",
135
- moduleSpecifier: "$lib/stripe"
136
- });
137
- let i = r.getDescendantsOfKind(g.CallExpression).find((e) => {
87
+ let n = new m({ manipulationSettings: { quoteKind: h.Single } }).addSourceFileAtPath(e), r = n.getDescendantsOfKind(g.CallExpression).find((e) => {
138
88
  let t = e.getExpression();
139
89
  return t.getKind() === g.PropertyAccessExpression && t.getText().includes("requestVerification");
140
90
  });
141
- if (!i) return {
91
+ if (!r) return {
142
92
  status: "failed",
143
93
  message: T
144
94
  };
145
- let a = i.getFirstAncestorByKind(g.ExpressionStatement);
146
- if (!a) return {
95
+ let i = r.getFirstAncestorByKind(g.ExpressionStatement);
96
+ return i ? (n.addImportDeclaration({
97
+ namedImports: ["linkStripeCustomer"],
98
+ moduleSpecifier: C
99
+ }), i.replaceWithText(w + "\n\n" + i.getText()), n.formatText(), n.saveSync(), {
100
+ status: "success",
101
+ changed: n.getFullText() !== t
102
+ }) : {
147
103
  status: "failed",
148
104
  message: T
149
105
  };
150
- r.addStatements(w);
151
- let o = t`
152
- await linkStripeCustomer(form.data.email, user, locals);
153
- `;
154
- return a.replaceWithText(o + "\n\n" + a.getText()), r.formatText(), r.saveSync(), {
155
- status: "success",
156
- changed: r.getFullText() !== n
157
- };
158
106
  }
159
107
  //#endregion
160
108
  //#region src/patterns/enable/payments/runtime/stripe.ts
161
109
  async function O(e, t, n) {
162
- let r = new v(t), i = await e.collection("users").getFullList(), a = await e.collection("stripe_customers").getFullList(), o = new Set(a.map((e) => e.user)), s = {
110
+ let r = new _(t), i = await e.collection("users").getFullList(), a = await e.collection("stripe_customers").getFullList(), o = new Set(a.map((e) => e.user)), s = {
163
111
  total: i.length,
164
112
  linked: o.size,
165
113
  created: 0,
@@ -213,7 +161,7 @@ async function O(e, t, n) {
213
161
  return s;
214
162
  }
215
163
  async function k(e) {
216
- let t = new v(e), n = await t.products.search({
164
+ let t = new _(e), n = await t.products.search({
217
165
  query: "name:\"Test Product\" AND metadata[\"test\"]:\"true\"",
218
166
  limit: 1
219
167
  });
@@ -244,7 +192,7 @@ async function k(e) {
244
192
  };
245
193
  }
246
194
  async function A(e, t) {
247
- let n = new v(e), r = await n.prices.retrieve(t, { expand: ["product"] }), i = typeof r.product == "string" ? await n.products.retrieve(r.product) : r.product;
195
+ let n = new _(e), r = await n.prices.retrieve(t, { expand: ["product"] }), i = typeof r.product == "string" ? await n.products.retrieve(r.product) : r.product;
248
196
  return r.product = i.id, {
249
197
  product: i,
250
198
  price: r,
@@ -273,7 +221,7 @@ async function P(e) {
273
221
  e && m.push(e);
274
222
  };
275
223
  l.info("Writing Stripe credentials to .env");
276
- let g = _(16).toString("hex"), v = [
224
+ let g = [
277
225
  {
278
226
  type: "comment",
279
227
  key: "Stripe credentials"
@@ -292,14 +240,9 @@ async function P(e) {
292
240
  type: "var",
293
241
  key: "STRIPE_WEBHOOK_SECRET",
294
242
  value: a
295
- },
296
- {
297
- type: "var",
298
- key: "INTERNAL_JOB_SECRET",
299
- value: g
300
243
  }
301
- ], y = f.join(e.root, ".env");
302
- h(i(y, s(y, v))), await u(e.root, async (n) => {
244
+ ], _ = f.join(e.root, ".env");
245
+ h(i(_, s(_, g))), await u(e.root, async (n) => {
303
246
  let r = (e) => d(n, e, l);
304
247
  l.info("Creating stripe_products collection");
305
248
  let i = await r({
@@ -610,41 +553,41 @@ async function P(e) {
610
553
  l.info(`Synced ${u.total} users (created ${u.created}, reused ${u.reused}, skipped ${u.skipped})`);
611
554
  }
612
555
  }), o ? l.info(`Fetching Stripe product/price ${o}`) : l.info("Creating test Stripe product and price");
613
- let { product: b, price: x, existing: S } = o ? await A(t, o) : await k(t);
614
- if (S && l.info("Stripe product/price already exists, skipping creation"), l.info("Seeding Stripe product/price records"), await u(e.root, async (e) => {
556
+ let { product: v, price: y, existing: b } = o ? await A(t, o) : await k(t);
557
+ if (b && l.info("Stripe product/price already exists, skipping creation"), l.info("Seeding Stripe product/price records"), await u(e.root, async (e) => {
615
558
  try {
616
- await e.collection("stripe_products").getOne(b.id);
559
+ await e.collection("stripe_products").getOne(v.id);
617
560
  } catch {
618
561
  await e.collection("stripe_products").create({
619
- id: b.id,
620
- name: b.name,
621
- active: b.active,
622
- default_price: b.default_price
562
+ id: v.id,
563
+ name: v.name,
564
+ active: v.active,
565
+ default_price: v.default_price
623
566
  });
624
567
  }
625
568
  try {
626
- await e.collection("stripe_prices").getOne(x.id);
569
+ await e.collection("stripe_prices").getOne(y.id);
627
570
  } catch {
628
571
  await e.collection("stripe_prices").create({
629
- id: x.id,
630
- billing_scheme: x.billing_scheme,
631
- currency: x.currency,
632
- product: x.product,
633
- recurring: x.recurring,
634
- type: x.type,
635
- unit_amount: x.unit_amount,
636
- active: x.active
572
+ id: y.id,
573
+ billing_scheme: y.billing_scheme,
574
+ currency: y.currency,
575
+ product: y.product,
576
+ recurring: y.recurring,
577
+ type: y.type,
578
+ unit_amount: y.unit_amount,
579
+ active: y.active
637
580
  });
638
581
  }
639
582
  }), l.info("Creating payment +page.svelte"), p.push({
640
583
  path: "src/routes/(public)/payment/+page.svelte",
641
584
  language: "svelte",
642
- content: N(x.id),
585
+ content: N(y.id),
643
586
  status: "success"
644
587
  }), c) {
645
588
  l.info("Modifying nav-user.svelte");
646
589
  let t = f.join(e.root, "src", "lib", "components", "nav-user.svelte");
647
- h(i(t, C(t))), l.info("Modifying signup +page.server.ts");
590
+ h(i(t, S(t))), l.info("Modifying signup +page.server.ts");
648
591
  let n = f.join(e.root, "src", "routes", "(public)", "(auth)", "signup", "+page.server.ts");
649
592
  h(i(n, D(n)));
650
593
  }
@@ -662,4 +605,4 @@ async function P(e) {
662
605
  //#endregion
663
606
  export { P as generate };
664
607
 
665
- //# sourceMappingURL=generate.runtime-DCvLLO7w.js.map
608
+ //# sourceMappingURL=generate.runtime-B6kxV3Bi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate.runtime-B6kxV3Bi.js","names":[],"sources":["../../src/patterns/enable/payments/modifies/modify-nav-user.ts","../../src/patterns/enable/payments/modifies/modify-user-signup.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BILLING_NAV_SNIPPET = [\n \"import CreditCardIcon from '@lucide/svelte/icons/credit-card';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Billing', url: '/billing', icon: CreditCardIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Billing nav item to nav-user.svelte:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Billing entry:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Billing\",\n \"/billing\",\n \"CreditCardIcon\",\n \"@lucide/svelte/icons/credit-card\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst WORKFLOW_MODULE = \"$lib/workflows/link-stripe-customer\";\n\nconst RUN_SNIPPET = dedent`\n // Queued here, done in the background: the Stripe calls retry on their own,\n // and the key means a retry never makes a second customer for this user.\n await linkStripeCustomer.run(\n { userId: user.id, email: form.data.email },\n { idempotencyKey: user.id }\n );\n`;\n\nconst FAILURE_HINT = [\n \"Could not locate the requestVerification call in signup +page.server.ts.\",\n \"Start the workflow once the user exists:\",\n \"\",\n `import { linkStripeCustomer } from '${WORKFLOW_MODULE}';`,\n \"\",\n RUN_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments.\",\n].join(\"\\n\");\n\n/**\n * Starts the link-stripe-customer workflow right after the user is created.\n * The work itself lives in src/lib/workflows/link-stripe-customer.ts.\n */\nexport function modifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\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 const requestVerificationCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => {\n const expr = ce.getExpression();\n return (\n expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n expr.getText().includes(\"requestVerification\")\n );\n });\n\n if (!requestVerificationCall) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const statement = requestVerificationCall.getFirstAncestorByKind(\n SyntaxKind.ExpressionStatement,\n );\n\n if (!statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n sourceFile.addImportDeclaration({\n namedImports: [\"linkStripeCustomer\"],\n moduleSpecifier: WORKFLOW_MODULE,\n });\n\n statement.replaceWithText(RUN_SNIPPET + \"\\n\\n\" + statement.getText());\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import Stripe from \"stripe\";\nimport type PocketBase from \"pocketbase\";\nimport type { Logger } from \"../../../../core/logger\";\n\nexport interface StripeTestFixture {\n product: Stripe.Product;\n price: Stripe.Price;\n existing: boolean;\n}\n\nexport interface SyncUsersResult {\n total: number;\n linked: number;\n created: number;\n reused: number;\n skipped: number;\n}\n\nexport async function syncUsersToStripeCustomers(\n pb: PocketBase,\n stripeSecretKey: string,\n logger: Logger,\n): Promise<SyncUsersResult> {\n const stripe = new Stripe(stripeSecretKey);\n const users = await pb\n .collection(\"users\")\n .getFullList<{ id: string; email: string }>();\n\n const existing = await pb\n .collection(\"stripe_customers\")\n .getFullList<{ id: string; user: string }>();\n const linkedUserIds = new Set(existing.map((c) => c.user));\n\n const result: SyncUsersResult = {\n total: users.length,\n linked: linkedUserIds.size,\n created: 0,\n reused: 0,\n skipped: 0,\n };\n\n for (const user of users) {\n if (linkedUserIds.has(user.id)) {\n result.skipped += 1;\n continue;\n }\n\n if (!user.email) {\n logger.info(`Skipping user ${user.id} with no email`);\n result.skipped += 1;\n continue;\n }\n\n const matching = await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n });\n\n let customer: Stripe.Customer;\n let isExistingCustomer = false;\n\n if (matching.data.length > 0) {\n customer = matching.data[0];\n isExistingCustomer = true;\n result.reused += 1;\n logger.info(`Reusing Stripe customer ${customer.id} for ${user.email}`);\n } else {\n customer = await stripe.customers.create({ email: user.email });\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${user.email}`);\n }\n\n try {\n await pb.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n } catch (error) {\n logger.info(\n `Failed to create stripe_customers row for ${user.email}: ${(error as Error).message}`,\n );\n continue;\n }\n\n if (!isExistingCustomer) {\n continue;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n { type: \"card\", allow_redisplay: \"always\" },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") continue;\n try {\n await pb.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n } catch {}\n }\n\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n if (defaultPaymentMethod) {\n try {\n await pb.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method:\n typeof defaultPaymentMethod === \"string\"\n ? defaultPaymentMethod\n : defaultPaymentMethod.id,\n });\n } catch {}\n }\n }\n\n return result;\n}\n\nexport async function createTestProductAndPrice(\n stripeSecretKey: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n\n const products = await stripe.products.search({\n query: `name:\"Test Product\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n const product = products.data[0];\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n if (prices.data.length > 0) {\n return { product, price: prices.data[0], existing: true };\n }\n }\n\n const product = await stripe.products.create({\n name: \"Test Product\",\n metadata: { test: \"true\" },\n });\n\n const price = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n });\n\n return { product, price, existing: false };\n}\n\nexport async function getProductAndPriceById(\n stripeSecretKey: string,\n priceId: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n const price = await stripe.prices.retrieve(priceId, { expand: [\"product\"] });\n const product =\n typeof price.product === \"string\"\n ? await stripe.products.retrieve(price.product)\n : (price.product as Stripe.Product);\n price.product = product.id;\n return { product, price, existing: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { createCollectionIdempotent } from \"../../../runtime/collections\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { modifyEnv, type EnvEdit } from \"./modifies/modify-env\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./runtime/stripe\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n action: \"created\" | \"updated\",\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, action, options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nfunction paymentPageSnippet(priceId: string): string {\n return dedent`\n <script lang=\"ts\">\n import PaymentButton from '$lib/components/payments/payment-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"${priceId}\" />\n </section>\n `;\n}\n\nexport async function generate(options: Options) {\n const {\n stripeSecretKey,\n stripePublishableKey,\n stripeWebhookSecret,\n stripePriceId,\n } = options.input as {\n stripeSecretKey: string;\n stripePublishableKey: string;\n stripeWebhookSecret: string;\n stripePriceId?: string;\n };\n\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Writing Stripe credentials to .env\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\", value: stripeSecretKey },\n {\n type: \"var\",\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n value: stripePublishableKey,\n },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\", value: stripeWebhookSecret },\n ];\n\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnv(envPath, envEdits)));\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating stripe_products collection\");\n const productsResult = await create({\n name: \"stripe_products\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"name\", required: false, type: \"text\" },\n { name: \"active\", required: false, type: \"text\" },\n { name: \"default_price\", required: false, type: \"text\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_products\",\n \"created\",\n options,\n productsResult.created,\n );\n\n logger.info(\"Creating stripe_prices collection\");\n const pricesResult = await create({\n name: \"stripe_prices\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"billing_scheme\", required: false, type: \"text\" },\n { name: \"currency\", required: false, type: \"text\" },\n { name: \"product\", required: false, type: \"text\" },\n { name: \"recurring\", required: false, type: \"json\" },\n { name: \"type\", required: false, type: \"text\" },\n { name: \"unit_amount\", required: false, type: \"number\" },\n { name: \"active\", required: false, type: \"bool\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_prices\",\n \"created\",\n options,\n pricesResult.created,\n );\n\n if (isAppMode) {\n logger.info(\"Creating stripe_customers collection\");\n const customersResult = await create({\n name: \"stripe_customers\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripeCustomersCollection = customersResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"created\",\n options,\n customersResult.created,\n );\n\n logger.info(\"Creating stripe_payment_methods collection\");\n const paymentMethodsResult = await create({\n name: \"stripe_payment_methods\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"exp_month\", required: true, type: \"number\" },\n { name: \"exp_year\", required: true, type: \"number\" },\n {\n collectionId: stripeCustomersCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripePaymentMethodsCollection = paymentMethodsResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_payment_methods\",\n \"created\",\n options,\n paymentMethodsResult.created,\n );\n\n logger.info(\"Linking default_payment_method on stripe_customers\");\n await pb.collections.update(\"stripe_customers\", {\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethodsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"updated\",\n options,\n );\n\n logger.info(\"Creating transactions collection\");\n const transactionsResult = await create({\n name: \"transactions\",\n type: \"base\",\n fields: [\n {\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"stripe_payment_intent\", required: true, type: \"text\" },\n { name: \"amount\", required: true, type: \"number\" },\n { name: \"currency\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"created\", required: true, type: \"date\" },\n { name: \"stripe_charge\", required: true, type: \"text\" },\n { name: \"stripe_customer\", required: true, type: \"text\" },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n { name: \"receipt_url\", required: true, type: \"url\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"transactions\",\n \"created\",\n options,\n transactionsResult.created,\n );\n\n logger.info(\"Syncing existing PocketBase users to Stripe customers\");\n const syncResult = await syncUsersToStripeCustomers(\n pb,\n stripeSecretKey,\n logger,\n );\n logger.info(\n `Synced ${syncResult.total} users (created ${syncResult.created}, reused ${syncResult.reused}, skipped ${syncResult.skipped})`,\n );\n }\n });\n\n if (stripePriceId) {\n logger.info(`Fetching Stripe product/price ${stripePriceId}`);\n } else {\n logger.info(\"Creating test Stripe product and price\");\n }\n const { product, price, existing } = stripePriceId\n ? await getProductAndPriceById(stripeSecretKey, stripePriceId)\n : await createTestProductAndPrice(stripeSecretKey);\n\n if (existing) {\n logger.info(\"Stripe product/price already exists, skipping creation\");\n }\n\n logger.info(\"Seeding Stripe product/price records\");\n await withPocketbase(options.root, async (pb) => {\n try {\n await pb.collection(\"stripe_products\").getOne(product.id);\n } catch (error) {\n await pb.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n try {\n await pb.collection(\"stripe_prices\").getOne(price.id);\n } catch (error) {\n await pb.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n });\n\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: paymentPageSnippet(price.id),\n status: \"success\",\n });\n\n if (isAppMode) {\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(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying 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, modifyUserSignup(userSignupPath)),\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":";;;;;;;;;;;;;;AAKA,IAAM,IAAsB;CAC1B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EACd,GACA,GACA,GACA,GACA,GACkD;CAClD,IAAM,IAAO,IAAI,EAAW,CAAc,GACtC,IAAW,IAET,KAAU,MAAgD;EAC1D,KACJ,GAAK,MAAW;GACd,IAAM,IAAS,EACb,GACA,GACA,GACA,GACA,CACF;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AgB;GACd,MAAM,EAAG,WAAW,eAAe,CAAC,CAAC,OAAO;IAC1C,IAAI,EAAM;IACV,gBAAgB,EAAM;IACtB,UAAU,EAAM;IAChB,SAAS,EAAM;IACf,WAAW,EAAM;IACjB,MAAM,EAAM;IACZ,aAAa,EAAM;IACnB,QAAQ,EAAM;GAChB,CAAC;EACH;CACF,CAAC,GAED,EAAO,KAAK,+BAA+B,GAC3C,EAAQ,KAAK;EACX,MAAM;EACN,UAAU;EACV,SAAS,EAAmB,EAAM,EAAE;EACpC,QAAQ;CACV,CAAC,GAEG,GAAW;EACb,EAAO,KAAK,2BAA2B;EACvC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;EAGA,AAFA,EAAW,EAAoB,GAAa,EAAc,CAAW,CAAC,CAAC,GAEvE,EAAO,KAAK,kCAAkC;EAC9C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,YACA,UACA,UACA,iBACF;EACA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE;CACF;CAEA,OAAO;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
3
  import { modifyOutcomeToFile as n } from "./modify-file-Cgu_WeFk.js";
4
- import { c as r, l as i, r as a } from "./ts-morph-helpers-Bf5iuQW8.js";
4
+ import { c as r, l as i, r as a } from "./ts-morph-helpers-teS3yXg-.js";
5
5
  import o from "node:path";
6
6
  import s from "node:fs";
7
7
  import { Project as c, QuoteKind as l, SyntaxKind as u } from "ts-morph";
@@ -207,4 +207,4 @@ async function w(e) {
207
207
  //#endregion
208
208
  export { w as generate };
209
209
 
210
- //# sourceMappingURL=generate.runtime-CXXwLatT.js.map
210
+ //# sourceMappingURL=generate.runtime-BYJZB1ad.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CXXwLatT.js","names":[],"sources":["../../src/patterns/enable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/enable/content-negotiation/modifies/hooks.ts","../../src/patterns/enable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/enable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = dedent`\n Wrap your exported handle with the negotiation handler:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { handle as handleNegotiate } from '$lib/negotiate';\n\n export const handle = sequence(handleNegotiate, /* your existing handle */);\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with a negotiation handle:\n\n export { handle } from '$lib/negotiate';\n`;\n\nfunction ensureSequenceImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (existing) {\n const has = existing\n .getNamedImports()\n .some((ni) => ni.getName() === \"sequence\");\n if (!has) existing.addNamedImport(\"sequence\");\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [\"sequence\"],\n moduleSpecifier: \"@sveltejs/kit/hooks\",\n });\n}\n\nfunction ensureNegotiateHandleImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n if (!has)\n existing.addNamedImport({ name: \"handle\", alias: \"handleNegotiate\" });\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"handle\", alias: \"handleNegotiate\" }],\n moduleSpecifier: \"$lib/negotiate\",\n });\n}\n\nexport function modifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const handleStmt = handleDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!handleStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = handleDecl.getInitializer();\n if (!init) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNegotiateHandleImport(sourceFile);\n\n if (init.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n call.insertArgument(0, \"handleNegotiate\");\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n }\n\n ensureSequenceImport(sourceFile);\n handleDecl.setInitializer(`sequence(handleNegotiate, ${init.getText()})`);\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEGOTIATE_ONLY_SNIPPET = dedent`\n import { reroute as negotiateReroute } from '$lib/negotiate';\n\n export const reroute = ({ url }) => negotiateReroute(url.pathname);\n`;\n\nconst FAILURE_HINT = dedent`\n Compose your existing reroute in src/hooks.ts with the negotiation reroute:\n\n import { reroute as negotiateReroute } from '$lib/negotiate';\n\n export const reroute = ({ url }) => existingReroute(negotiateReroute(url.pathname));\n`;\n\nfunction ensureNegotiateImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!has) {\n existing.addNamedImport({ name: \"reroute\", alias: \"negotiateReroute\" });\n }\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"reroute\", alias: \"negotiateReroute\" }],\n moduleSpecifier: \"$lib/negotiate\",\n });\n}\n\nexport function modifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n fs.mkdirSync(path.dirname(hooksPath), { recursive: true });\n fs.writeFileSync(hooksPath, NEGOTIATE_ONLY_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n\n if (!rerouteDecl) {\n ensureNegotiateImport(sourceFile);\n sourceFile.addStatements(\n `\\nexport const reroute = ({ url }) => negotiateReroute(url.pathname);\\n`,\n );\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const rerouteStmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!rerouteStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = rerouteDecl.getInitializer();\n if (!init) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n const initText = init.getText();\n\n if (hasI18nHelper && initText.includes(\"rerouteDeLocalize\")) {\n ensureNegotiateImport(sourceFile);\n rerouteDecl.setInitializer(\n \"({ url }) => rerouteDeLocalize(negotiateReroute(url.pathname))\",\n );\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n return { status: \"failed\", message: FAILURE_HINT };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { Negotiate } from '$lib/negotiate';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<Negotiate />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root +layout.svelte and mount <Negotiate /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nexport function modifyRootLayoutNegotiate(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(\"Negotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"Negotiate\"],\n moduleSpecifier: \"$lib/negotiate\",\n },\n ]);\n });\n return out;\n });\n\n file.appendMarkup(MARKUP_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\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 { modifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { modifyHooksNegotiate } from \"./modifies/hooks\";\nimport { modifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Modifying hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, modifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyRootLayoutNegotiate(rootLayoutPath),\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":";;;;;;;;AAKA,IAAM,IAAe,CAAM;;;;;;;GASrB,IAAiB,CAAM;;;;;AAM7B,SAAS,EAAqB,GAAwB;CACpD,IAAM,IAAW,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,qBAAqB;CACpE,IAAI,GAAU;EAIZ,AAHY,EACT,gBAAgB,CAAC,CACjB,MAAM,MAAO,EAAG,QAAQ,MAAM,UAC5B,KAAK,EAAS,eAAe,UAAU;EAC5C;CACF;CACA,EAAW,qBAAqB;EAC9B,cAAc,CAAC,UAAU;EACzB,iBAAiB;CACnB,CAAC;AACH;AAEA,SAA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AE,QAAQ;EAAW,SAAS,EAAK,WAAW;CAAE;AACzD;;;AC3CA,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAmB,CAAC,GAEpB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB;CAQxE,AAPA,EACE,EACE,GACA,EAA2B,CAAe,CAC5C,CACF,GAEA,EAAO,KAAK,oBAAoB;CAChC,IAAM,IAAY,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU;CAG3D,AAFA,EAAW,EAAoB,GAAW,EAAqB,CAAS,CAAC,CAAC,GAE1E,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,gBACF;CAQA,OAPA,EACE,EACE,GACA,EAA0B,CAAc,CAC1C,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
+ {"version":3,"file":"generate.runtime-BYJZB1ad.js","names":[],"sources":["../../src/patterns/enable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/enable/content-negotiation/modifies/hooks.ts","../../src/patterns/enable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/enable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = dedent`\n Wrap your exported handle with the negotiation handler:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { handle as handleNegotiate } from '$lib/negotiate';\n\n export const handle = sequence(handleNegotiate, /* your existing handle */);\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with a negotiation handle:\n\n export { handle } from '$lib/negotiate';\n`;\n\nfunction ensureSequenceImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (existing) {\n const has = existing\n .getNamedImports()\n .some((ni) => ni.getName() === \"sequence\");\n if (!has) existing.addNamedImport(\"sequence\");\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [\"sequence\"],\n moduleSpecifier: \"@sveltejs/kit/hooks\",\n });\n}\n\nfunction ensureNegotiateHandleImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n if (!has)\n existing.addNamedImport({ name: \"handle\", alias: \"handleNegotiate\" });\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"handle\", alias: \"handleNegotiate\" }],\n moduleSpecifier: \"$lib/negotiate\",\n });\n}\n\nexport function modifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const handleStmt = handleDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!handleStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = handleDecl.getInitializer();\n if (!init) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNegotiateHandleImport(sourceFile);\n\n if (init.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n call.insertArgument(0, \"handleNegotiate\");\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n }\n\n ensureSequenceImport(sourceFile);\n handleDecl.setInitializer(`sequence(handleNegotiate, ${init.getText()})`);\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEGOTIATE_ONLY_SNIPPET = dedent`\n import { reroute as negotiateReroute } from '$lib/negotiate';\n\n export const reroute = ({ url }) => negotiateReroute(url.pathname);\n`;\n\nconst FAILURE_HINT = dedent`\n Compose your existing reroute in src/hooks.ts with the negotiation reroute:\n\n import { reroute as negotiateReroute } from '$lib/negotiate';\n\n export const reroute = ({ url }) => existingReroute(negotiateReroute(url.pathname));\n`;\n\nfunction ensureNegotiateImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!has) {\n existing.addNamedImport({ name: \"reroute\", alias: \"negotiateReroute\" });\n }\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"reroute\", alias: \"negotiateReroute\" }],\n moduleSpecifier: \"$lib/negotiate\",\n });\n}\n\nexport function modifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n fs.mkdirSync(path.dirname(hooksPath), { recursive: true });\n fs.writeFileSync(hooksPath, NEGOTIATE_ONLY_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n\n if (!rerouteDecl) {\n ensureNegotiateImport(sourceFile);\n sourceFile.addStatements(\n `\\nexport const reroute = ({ url }) => negotiateReroute(url.pathname);\\n`,\n );\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const rerouteStmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!rerouteStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = rerouteDecl.getInitializer();\n if (!init) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n const initText = init.getText();\n\n if (hasI18nHelper && initText.includes(\"rerouteDeLocalize\")) {\n ensureNegotiateImport(sourceFile);\n rerouteDecl.setInitializer(\n \"({ url }) => rerouteDeLocalize(negotiateReroute(url.pathname))\",\n );\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n return { status: \"failed\", message: FAILURE_HINT };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { Negotiate } from '$lib/negotiate';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<Negotiate />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root +layout.svelte and mount <Negotiate /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nexport function modifyRootLayoutNegotiate(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(\"Negotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"Negotiate\"],\n moduleSpecifier: \"$lib/negotiate\",\n },\n ]);\n });\n return out;\n });\n\n file.appendMarkup(MARKUP_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\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 { modifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { modifyHooksNegotiate } from \"./modifies/hooks\";\nimport { modifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Modifying hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, modifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyRootLayoutNegotiate(rootLayoutPath),\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":";;;;;;;;AAKA,IAAM,IAAe,CAAM;;;;;;;GASrB,IAAiB,CAAM;;;;;AAM7B,SAAS,EAAqB,GAAwB;CACpD,IAAM,IAAW,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,qBAAqB;CACpE,IAAI,GAAU;EAIZ,AAHY,EACT,gBAAgB,CAAC,CACjB,MAAM,MAAO,EAAG,QAAQ,MAAM,UAC5B,KAAK,EAAS,eAAe,UAAU;EAC5C;CACF;CACA,EAAW,qBAAqB;EAC9B,cAAc,CAAC,UAAU;EACzB,iBAAiB;CACnB,CAAC;AACH;AAEA,SAAS,EAA4B,GAAwB;CAC3D,IAAM,IAAW,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,gBAAgB;CAC/D,IAAI,GAAU;EAOZ,AANY,EAAS,gBAAgB,CAAC,CAAC,MAAM,MAEzC,EAAG,QAAQ,MAAM,YACjB,EAAG,aAAa,CAAC,EAAE,QAAQ,MAAM,iBAGhC,KACH,EAAS,eAAe;GAAE,MAAM;GAAU,OAAO;EAAkB,CAAC;EACtE;CACF;CACA,EAAW,qBAAqB;EAC9B,cAAc,CAAC;GAAE,MAAM;GAAU,OAAO;EAAkB,CAAC;EAC3D,iBAAiB;CACnB,CAAC;AACH;AAEA,SAAgB,EACd,GACe;CACf,IAAI,CAAC,EAAG,WAAW,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAIxD,IAD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B,EAAQ,MACR,OACA,UACA,gBACF;CAQA,OAPA,EACE,EACE,GACA,EAA0B,CAAc,CAC1C,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"}
@@ -2,7 +2,7 @@ import { t as e } from "./dedent-Gq6Krl4n.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
3
  import { n } from "./generate-tOkjJFUf.js";
4
4
  import { modifyOutcomeToFile as r } from "./modify-file-Cgu_WeFk.js";
5
- import { c as i, l as a, r as o } from "./ts-morph-helpers-Bf5iuQW8.js";
5
+ import { c as i, l as a, r as o } from "./ts-morph-helpers-teS3yXg-.js";
6
6
  import { a as s, t as c } from "./config-target-DOi8kI_f.js";
7
7
  import l from "node:path";
8
8
  import u from "node:fs";
@@ -399,4 +399,4 @@ async function q(e) {
399
399
  //#endregion
400
400
  export { q as generate, W as keepMissing };
401
401
 
402
- //# sourceMappingURL=generate.runtime-BsuyMwoj.js.map
402
+ //# sourceMappingURL=generate.runtime-B_Fk1Jjs.js.map